问:
AWK: increment a field based on values from previous line
Given the following input for AWK:

```<code>10;20;20
8;41;41
15;52;52
</code>```

How could I increase/decrease the values so that:

$1 = remains unchanged

$2 = $2 of previous line + $1 of previous line + 1

$3 = $3 of previous line + $1 of previous line + 1

So the desired output would be:

```<code>10;20;20
8;31;31
15;40;40
</code>```

I need to auto-increment and loop over the lines,
using associative arrays, but it's confusing for me.
Surely, this doesn't work as desired:

```<code>#!/bin/awk -f

BEGIN { FS = ";" }

{
print ln, st, of
ln=$1
st=$2 + ln + 1
of=$3 + ln + 1
}
</code>```

答:
with awk

```<code>awk -F";" -v OFS=";"
    'NR!=1{ $2=a[2]+a[1]+1; $3=a[3]+a[1]+1 } { split($0,a,FS) } 1' file
</code>```

split the line to an array and when processing the next line we can use the values stored.

test

```<code>10;20;20
8;31;31
15;40;40
</code>```

Body:
Given the following input for AWK:

10;20;20
8;41;41
15;52;52

How could I increase/decrease the values so that:

$1 = remains unchanged

$2 = $2 of previous line + $1 of previous line + 1

$3 = $3 of previous line + $1 of previous line + 1

So the desired output would be:

10;20;20
8;31;31
15;40;40

I need to auto-increment and loop over the lines,
using associative arrays, but it's confusing for me.
Surely, this doesn't work as desired:

#!/bin/awk -f

BEGIN { FS = ";" }

{
print ln, st, of
ln=$1
st=$2 + ln + 1
of=$3 + ln + 1
}

Body:
with awk

awk -F";" -v OFS=";"
    'NR!=1{ $2=a[2]+a[1]+1; $3=a[3]+a[1]+1 } { split($0,a,FS) } 1' file

split the line to an array and when processing the next line we can use the values stored.

test

10;20;20
8;31;31
15;40;40


来源: stackexchange

问:
php_oci8_12c.dll - The specified module could not be found
I am using Windows 7 and php5.6.

php_oci8_12c.dll exists but I could not find it. Other modules are normal.

errorlog:

PHP Warning:  PHP Startup: Unable to load dynamic library
  'C:/Server/bin/ext\php_oci8_12c.dll' - The specified module could not
  be found.\r\n in Unknown on line 0

答:
A bit late, but I faced the issue and found a possible answer just now.

First, Oracle binaries (from instant client 12 x86) must be in the system path.

Second (the most vicious), check which VC++ runtime is needed (on Oracle's download page) for this instant client and install it.

I spent 6 hours on it and finally got it. Even on a Windows 2016 server, VC++ runtimes are not installed by default. It's a real pain to realize that.

Hope this helps

ContentLicense: CC BY-SA 3.0


问:
Getting error Uncaught AssertionError: expected {} to have a property 'data'
I using chai.should(); for writing node js test case. I am calling REST API and getting the response

```<code>{
  "statuscode": 200,
  "message": "success",
  "data": {
    "getEducationDetails": [
      {
        "end_date": "1996-04-31",
        "degree_name": "BE",
        "degree_date": "1993-06-18",
        "location": "Hyderabad",
        "university_name": "Hyderabad",
        "institute_name": "VIT",
        "start_date": "1992-01-01"
      }
    ]
  }
}
</code>```

I want to test the statuscode in the response is 200 or not and proprieties like location etc.

I have tried

```<code>res.body.should.have.property('data')
                    .which.is.an('object')
                    .and.has.property('getEducationDetails')
                    .which.is.an('array')
                    .and.has.property('location')
    .and.has.property('location')
</code>```

and for stauscode

```<code>res.body.should.have.property('stauscode').eql(200)
</code>```

how can I test these properties?

Thank You in Advance

答:
https://www.npmjs.com/package/chai-things

It will check for all object in array should contain end_date . You can do for all properties

```<code>res.body.data.getEducationDetails.should.all.have.property('end_date')
</code>```

Body:
I using chai.should(); for writing node js test case. I am calling REST API and getting the response

{
  "statuscode": 200,
  "message": "success",
  "data": {
    "getEducationDetails": [
      {
        "end_date": "1996-04-31",
        "degree_name": "BE",
        "degree_date": "1993-06-18",
        "location": "Hyderabad",
        "university_name": "Hyderabad",
        "institute_name": "VIT",
        "start_date": "1992-01-01"
      }
    ]
  }
}

I want to test the statuscode in the response is 200 or not and proprieties like location etc.

I have tried

res.body.should.have.property('data')
                    .which.is.an('object')
                    .and.has.property('getEducationDetails')
                    .which.is.an('array')
                    .and.has.property('location')
    .and.has.property('location')

and for stauscode

res.body.should.have.property('stauscode').eql(200)

how can I test these properties?

Thank You in Advance

Body:
https://www.npmjs.com/package/chai-things

It will check for all object in array should contain end_date . You can do for all properties

res.body.data.getEducationDetails.should.all.have.property('end_date')


问:
Use Identifier before Defining for BNF-Style Definitions
In defining a BNF grammar it's common to use things before defining them so that the grammar reads "forwards."

How can one do this in coq and still be able to step through buffers?

答:
In Coq, the notion of buffer is not pre-defined, so it is quite hard to understand what you mean.  Still there are two aspects of Coq that give a feeling of possible look-ahead, and which could be used when defining a BNF grammar.

Recursive function definitions can introduce simultaneously several recursive functions.

Type definitions can introduce simultaneously several inductive types.

In both cases, the first object being defined can refer to the second one before it is defined.

Here are two examples, the first one is about recursive functions.

```<code>Fixpoint even (n : nat) : bool :=
   match n with
     0 => true
   | S p => negb( odd p)
   end
with odd (n : nat) : bool :=
  match n with
    0 => false
  | S p => negb (even p)
  end.
</code>```

You see in this example that the function even refers to the function odd before it is defined.

Now comes the second example.  I try to stick to your leading metaphor of BNF.  A grammar description can be given as an inductive predicate.  Here is a small example with a grammar for arithmetic expressions involving only addition, multiplication, and natural numbers.

```<code>Require Import String Ascii Arith.

Definition digit (c : ascii) : bool :=
  (nat_of_ascii "0" <=? nat_of_ascii c) &&
  (nat_of_ascii c <=? nat_of_ascii "9").

Fixpoint number (s : string) : bool :=
  match s with
  | String c EmptyString => digit c
  | String c tl => digit c && number tl
  | EmptyString => false
  end.

Inductive Exp1 : string -> Prop :=
  plus : forall x y, Exp2 x -> Exp1 y -> Exp1 (x ++ "+" ++ y)
| inj2 : forall x, Exp2 x -> Exp1 x
with
  Exp2 : string -> Prop :=
  times : forall x y, Exp3 x -> Exp2 y -> Exp2 (x ++ "*" ++ y)
| inj3 : forall x, Exp3 x -> Exp2 x
with
  Exp3 : string -> Prop :=
|  num : forall x, number x = true -> Exp3 x
|  inj1 : forall x, Exp1 x -> Exp3 ("(" ++ x ++ ")").
</code>```

With this description of a grammar, I can prove that a given expression respects the grammar.

```<code>Lemma example : Exp1 "3+2*(5*4)".
Proof.
apply (plus "3" "2*(5*4)").
  apply inj3.
  apply num; reflexivity.
apply inj2.
apply (times "2" "(5*4)").
  apply num; reflexivity.
apply inj3, (inj1 "5*4"), inj2, (times "5" "4").
  apply num; reflexivity.
apply inj3, num; reflexivity.
Qed.
</code>```

This does not describe a parser. This would be another exercise.

Your question is so terse that I don't even know whether this is an answer.

Body:
In Coq, the notion of buffer is not pre-defined, so it is quite hard to understand what you mean.  Still there are two aspects of Coq that give a feeling of possible look-ahead, and which could be used when defining a BNF grammar.

Recursive function definitions can introduce simultaneously several recursive functions.

Type definitions can introduce simultaneously several inductive types.

In both cases, the first object being defined can refer to the second one before it is defined.

Here are two examples, the first one is about recursive functions.

Fixpoint even (n : nat) : bool :=
   match n with
     0 => true
   | S p => negb( odd p)
   end
with odd (n : nat) : bool :=
  match n with
    0 => false
  | S p => negb (even p)
  end.

You see in this example that the function even refers to the function odd before it is defined.

Now comes the second example.  I try to stick to your leading metaphor of BNF.  A grammar description can be given as an inductive predicate.  Here is a small example with a grammar for arithmetic expressions involving only addition, multiplication, and natural numbers.

Require Import String Ascii Arith.

Definition digit (c : ascii) : bool :=
  (nat_of_ascii "0" <=? nat_of_ascii c) &&
  (nat_of_ascii c <=? nat_of_ascii "9").

Fixpoint number (s : string) : bool :=
  match s with
  | String c EmptyString => digit c
  | String c tl => digit c && number tl
  | EmptyString => false
  end.

Inductive Exp1 : string -> Prop :=
  plus : forall x y, Exp2 x -> Exp1 y -> Exp1 (x ++ "+" ++ y)
| inj2 : forall x, Exp2 x -> Exp1 x
with
  Exp2 : string -> Prop :=
  times : forall x y, Exp3 x -> Exp2 y -> Exp2 (x ++ "*" ++ y)
| inj3 : forall x, Exp3 x -> Exp2 x
with
  Exp3 : string -> Prop :=
|  num : forall x, number x = true -> Exp3 x
|  inj1 : forall x, Exp1 x -> Exp3 ("(" ++ x ++ ")").

With this description of a grammar, I can prove that a given expression respects the grammar.

Lemma example : Exp1 "3+2*(5*4)".
Proof.
apply (plus "3" "2*(5*4)").
  apply inj3.
  apply num; reflexivity.
apply inj2.
apply (times "2" "(5*4)").
  apply num; reflexivity.
apply inj3, (inj1 "5*4"), inj2, (times "5" "4").
  apply num; reflexivity.
apply inj3, num; reflexivity.
Qed.

This does not describe a parser. This would be another exercise.

Your question is so terse that I don't even know whether this is an answer.


问:
How to create a file for configuring the ConnectionString in a Analysis Services Project?
In the Analysis Services Project, I have set the ConnectionString in olap.ds and it works well.

However everytime I change the password of the database, I will need to deploy the project again as I can only config it in the olap.ds file.

Is there any way that I can setup a config file to manage the ConnectionString? So I just need to modify the config file instead of re-deploying the project.

Thanks for the help.

答:
You can use XMLA script. The following is an example for AdwentureWorks Cube. You can run such script from SSMS or from PowerShell.

```<code><Alter AllowCreate="true" ObjectExpansion="ObjectProperties" xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
<Object>
    <DatabaseID>AdventureWorksDW2012Multidimensional-EE</DatabaseID>
    <DataSourceID>Adventure Works DW</DataSourceID>
</Object>
<ObjectDefinition>
    <DataSource xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200" xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300" xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300" xmlns:ddl400="http://schemas.microsoft.com/analysisservices/2012/engine/400" xmlns:ddl400_400="http://schemas.microsoft.com/analysisservices/2012/engine/400/400" xsi:type="RelationalDataSource">
        <ID>Adventure Works DW</ID>
        <Name>AdventureWorksDW2012</Name>
        <ConnectionString>Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=AdventureWorksDW2012</ConnectionString>
        <ImpersonationInfo>
            <ImpersonationMode>ImpersonateAccount</ImpersonationMode>
                <Account>domain\login</Account>
                <Password>password</Password>
        </ImpersonationInfo>
        <Timeout>PT0S</Timeout>
    </DataSource>
</ObjectDefinition>
</code>```

Please note that you have to use windows domain accounts for data access, or store your login and password in connection string in plain text.

Body:
You can use XMLA script. The following is an example for AdwentureWorks Cube. You can run such script from SSMS or from PowerShell.

<Alter AllowCreate="true" ObjectExpansion="ObjectProperties" xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
<Object>
    <DatabaseID>AdventureWorksDW2012Multidimensional-EE</DatabaseID>
    <DataSourceID>Adventure Works DW</DataSourceID>
</Object>
<ObjectDefinition>
    <DataSource xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200" xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300" xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300" xmlns:ddl400="http://schemas.microsoft.com/analysisservices/2012/engine/400" xmlns:ddl400_400="http://schemas.microsoft.com/analysisservices/2012/engine/400/400" xsi:type="RelationalDataSource">
        <ID>Adventure Works DW</ID>
        <Name>AdventureWorksDW2012</Name>
        <ConnectionString>Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=AdventureWorksDW2012</ConnectionString>
        <ImpersonationInfo>
            <ImpersonationMode>ImpersonateAccount</ImpersonationMode>
                <Account>domain\login</Account>
                <Password>password</Password>
        </ImpersonationInfo>
        <Timeout>PT0S</Timeout>
    </DataSource>
</ObjectDefinition>

Please note that you have to use windows domain accounts for data access, or store your login and password in connection string in plain text.


问:
Unable to switch to debug build variant in Android Studio
I've switched to release build variant and configured signingConfigs. Now when I try to check the debug build variant from the drop down menu it switches immediately back to the release build variant. So I'm not able to run my app in debug mode any more.

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            ...
        }
    }

    compileSdkVersion rootProject.compileSdkVersion
    buildToolsVersion rootProject.buildToolsVersion

    defaultConfig {
        applicationId "com.kost.foo"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        versionCode 2
        versionName "1.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        }
        externalNativeBuild {
            cmake {
               ...
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            debuggable true
            signingConfig signingConfigs.config
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        main {
            jniLibs.srcDirs = ['src/main/jni']
        }
    }

    externalNativeBuild {
        cmake {
            path 'src/main/jni/CMakeLists.txt'
        }
    }
}

kapt {
    generateStubs = true
}

repositories {
    maven { url 'https://github.com/linchaolong/stetho-realm/raw/master/maven-repo' }
    mavenCentral()

}
</code>```

I've tried to revert all changes in build.gradle as it was before configuring, but with no luck.

Any ideas how to fix the issue?

答:
Just need to cut ".idea" Folder and paste it outside Project root folder( For Back up if you need).These files will be auto regenerated. On Opening the project it"ll ask add module (app) to your project. You can ignore the same.

It set set default build variant to be "debug".
You can see build variant tab on left corner or hover on "Monitor" Symbol on left bottom to get build variant option.

ContentLicense: CC BY-SA 4.0

Body:
I've switched to release build variant and configured signingConfigs. Now when I try to check the debug build variant from the drop down menu it switches immediately back to the release build variant. So I'm not able to run my app in debug mode any more.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            ...
        }
    }

    compileSdkVersion rootProject.compileSdkVersion
    buildToolsVersion rootProject.buildToolsVersion

    defaultConfig {
        applicationId "com.kost.foo"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        versionCode 2
        versionName "1.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        }
        externalNativeBuild {
            cmake {
               ...
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            debuggable true
            signingConfig signingConfigs.config
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        main {
            jniLibs.srcDirs = ['src/main/jni']
        }
    }

    externalNativeBuild {
        cmake {
            path 'src/main/jni/CMakeLists.txt'
        }
    }
}

kapt {
    generateStubs = true
}

repositories {
    maven { url 'https://github.com/linchaolong/stetho-realm/raw/master/maven-repo' }
    mavenCentral()

}

I've tried to revert all changes in build.gradle as it was before configuring, but with no luck.

Any ideas how to fix the issue?


问:
How to load a custom error page in webview when no internet connection?
Im trying to find out how I add a custom offline page to my webview app. The app works well I just feel like a custom offline page would look much better! I have looked at some answers online but they dont seem to work any more :(. I hope someone can help!
Here is my Main code is (Made in the android studio):

package com.rizwan.yvsse;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.onesignal.OneSignal;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();

        Intent intent = new Intent(MainActivity.this, splash_screen.class);
        startActivity(intent);

        progressBar= (ProgressBar)findViewById(R.id.progressBar);
        webView = (WebView) findViewById(R.id.webview);
        String url="https://yvsse.com/billing/";
        webView.loadUrl(url);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new HelloWebViewClient());

    }

    @Override
    public void onBackPressed() {

        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);

            // set title
            alertDialogBuilder.setTitle("Exit");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you really want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
    }

    private class HelloWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(view.GONE);
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }

    }
}```

Thank you!

答:
Overrride the onReceivedError method and check internet connectivity inside it to confirm that the url failed because of the internet connectivity

```<code>        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
               if(!isappOnline()) {
               webView.loadUrl("file:///android_asset/error.html");
               }
        }

        private boolean isappOnline() {
            ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo() != null;
        }
</code>```

also add your fallback page in assets folder src/main/assets/

Body:
Im trying to find out how I add a custom offline page to my webview app. The app works well I just feel like a custom offline page would look much better! I have looked at some answers online but they dont seem to work any more :(. I hope someone can help!
Here is my Main code is (Made in the android studio):

package com.rizwan.yvsse;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.onesignal.OneSignal;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();

        Intent intent = new Intent(MainActivity.this, splash_screen.class);
        startActivity(intent);

        progressBar= (ProgressBar)findViewById(R.id.progressBar);
        webView = (WebView) findViewById(R.id.webview);
        String url="https://yvsse.com/billing/";
        webView.loadUrl(url);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new HelloWebViewClient());

    }

    @Override
    public void onBackPressed() {

        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);

            // set title
            alertDialogBuilder.setTitle("Exit");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you really want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
    }

    private class HelloWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {

            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(view.GONE);
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }

    }
}

Thank you!

Body:
Overrride the onReceivedError method and check internet connectivity inside it to confirm that the url failed because of the internet connectivity

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
               if(!isappOnline()) {
               webView.loadUrl("file:///android_asset/error.html");
               }
        }

        private boolean isappOnline() {
            ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo() != null;
        }

also add your fallback page in assets folder src/main/assets/


问:
pandas: extract date and time from timestamp
I have a timestamp column where the timestamp is in the following format

```<code>2016-06-16T21:35:17.098+01:00
</code>```

I want to extract date and time from it. I have done the following:

```<code>import datetime as dt

df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))

df['dates'] = df['timestamp'].dt.date
</code>```

This worked for a while. But suddenly it does not.

If I again do df['dates'] = df['timestamp'].dt.date I get the following error

```<code>Can only use .dt accessor with datetimelike values
</code>```

Luckily, I have saved the data frame with dates in the csv but I now want to create another column time in the format 23:00:00.051

EDIT

From the raw data file (15 million samples), the timestamp column looks like following (first 5 samples):

```<code>            timestamp

0           2016-06-13T00:00:00.051+01:00
1           2016-06-13T00:00:00.718+01:00
2           2016-06-13T00:00:00.985+01:00
3           2016-06-13T00:00:02.431+01:00
4           2016-06-13T00:00:02.737+01:00
</code>```

After the following command

```<code>df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))
</code>```

the timestamp column looks like with dtype as dtype: datetime64[ns]

```<code>0    2016-06-12 23:00:00.051
1    2016-06-12 23:00:00.718
2    2016-06-12 23:00:00.985
3    2016-06-12 23:00:02.431
4    2016-06-12 23:00:02.737
</code>```

Then finally

```<code>df['dates'] = df['timestamp'].dt.date

0           2016-06-12
1           2016-06-12
2           2016-06-12
3           2016-06-12
4           2016-06-12
</code>```

EDIT 2

Found the mistake. I had cleaned the data and saved the data frame in a csv file, so I don't have to do the cleaning again. When I read the csv, the timestamp dtype changes to object. Now how do I fix this?

答:
If date is in string form then:

import datetime

# this line converts the string object in Timestamp object
df['DateTime'] = [datetime.datetime.strptime(d, "%Y-%m-%d %H:%M") for d in df["DateTime"]]

# extracting date from timestamp
df['Date'] = [datetime.datetime.date(d) for d in df['DateTime']]

# extracting time from timestamp
df['Time'] = [datetime.datetime.time(d) for d in df['DateTime']]
```

If the object is already in the Timestamp format then skip the first line of code.

%Y-%m-%d %H:%M this means your timestamp object must be in the form like  2016-05-16 12:35:00.

Body:
I have a timestamp column where the timestamp is in the following format

2016-06-16T21:35:17.098+01:00

I want to extract date and time from it. I have done the following:

import datetime as dt

df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))

df['dates'] = df['timestamp'].dt.date

This worked for a while. But suddenly it does not.

If I again do df['dates'] = df['timestamp'].dt.date I get the following error

Can only use .dt accessor with datetimelike values

Luckily, I have saved the data frame with dates in the csv but I now want to create another column time in the format 23:00:00.051

EDIT

From the raw data file (15 million samples), the timestamp column looks like following (first 5 samples):

            timestamp

0           2016-06-13T00:00:00.051+01:00
1           2016-06-13T00:00:00.718+01:00
2           2016-06-13T00:00:00.985+01:00
3           2016-06-13T00:00:02.431+01:00
4           2016-06-13T00:00:02.737+01:00

After the following command

df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))

the timestamp column looks like with dtype as dtype: datetime64[ns]

0    2016-06-12 23:00:00.051
1    2016-06-12 23:00:00.718
2    2016-06-12 23:00:00.985
3    2016-06-12 23:00:02.431
4    2016-06-12 23:00:02.737

Then finally

df['dates'] = df['timestamp'].dt.date

0           2016-06-12
1           2016-06-12
2           2016-06-12
3           2016-06-12
4           2016-06-12

EDIT 2

Found the mistake. I had cleaned the data and saved the data frame in a csv file, so I don't have to do the cleaning again. When I read the csv, the timestamp dtype changes to object. Now how do I fix this?

Body:
If date is in string form then:

import datetime

# this line converts the string object in Timestamp object
df['DateTime'] = [datetime.datetime.strptime(d, "%Y-%m-%d %H:%M") for d in df["DateTime"]]

# extracting date from timestamp
df['Date'] = [datetime.datetime.date(d) for d in df['DateTime']]

# extracting time from timestamp
df['Time'] = [datetime.datetime.time(d) for d in df['DateTime']]

If the object is already in the Timestamp format then skip the first line of code.

%Y-%m-%d %H:%M this means your timestamp object must be in the form like  2016-05-16 12:35:00.


问:
Connect to multiple database elixir
In Rails , we can connect to multiple database on fly as,

```<code>ActiveRecord::Base.establish_connection(
  database: "db_name", username: "postgres")
</code>```

But in Elixir - Phoenix framework, how to do the same process.

答:
For the raw connection one needs to use the lower abstraction level than Ecto provides on top. Ecto code is the good source to take an inspiration from. Basically, for MySQL database something like this should do:

```<code>with {:ok, conn} <- Mariaex.start_link(opts) do
  value = Ecto.Adapters.MySQL.Connection.execute(conn, sql, [], opts)
  GenServer.stop(conn)
  value
end
</code>```

where opts is a keyword list with database, username etc keys. The example of how to maintain a connection pool might be stolen from one of Ecto adapters source code as well.

Title: Connect to multiple database elixir

Body:
In Rails , we can connect to multiple database on fly as,

ActiveRecord::Base.establish_connection(
  database: "db_name", username: "postgres")

But in Elixir - Phoenix framework, how to do the same process.

Body:
For the raw connection one needs to use the lower abstraction level than Ecto provides on top. Ecto code is the good source to take an inspiration from. Basically, for MySQL database something like this should do:

with {:ok, conn} <- Mariaex.start_link(opts) do
  value = Ecto.Adapters.MySQL.Connection.execute(conn, sql, [], opts)
  GenServer.stop(conn)
  value
end

where opts is a keyword list with database, username etc keys. The example of how to maintain a connection pool might be stolen from one of Ecto adapters source code as well.


问:
How to generate serial number in a query?
We're using PostgreSQL v8.2.3.

How do I generate serial number in the query output?  I want to display serial number for each row returned by the query.

Example: SELECT employeeid, name FROM employee

I expect to generate and display serial number against each row starting from one.

答:
```
SELECT row_number() over (order by employeeid) as serial_number,
       employeeid,
       name
FROM employee
```

If you want to assign the numbers according to the sorting of the name, change the order by in the over clause

ContentLicense: CC BY-SA 2.5

Body:
SELECT row_number() over (order by employeeid) as serial_number,
       employeeid,
       name
FROM employee

If you want to assign the numbers according to the sorting of the name, change the order by in the over clause


问:
How do I set PropTypes for Higher Order Functional Component?
I'm using airbnb configuration for eslint and it's giving me this warning:

[eslint] 'isLoading' is missing in props validation (react/prop-types)

Is there a way to set PropTypes for isLoading?

```<code>const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <LoadingSpinner /> : <Component {...rest} />);
</code>```

Here's an example of how I use it:

```<code>const Button = ({ onClick, className, children }) => (
  <button onClick={onClick} className={className} type="button">
    {children}
  </button>
);
Button.propTypes = {
  onClick: PropTypes.func.isRequired,
  className: PropTypes.string,
  children: PropTypes.node.isRequired,
};
Button.defaultProps = {
  onClick: () => {},
  className: '',
  children: 'Click me',
};

const Loading = () => (
  <div>
    <p>Loading...</p>
  </div>
);

const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <Loading /> : <Component {...rest} />);

// How do I set propTypes for isLoading?
// I tried this but it didn't work:
// withLoading.propTypes = {
// isLoading: PropTypes.bool
// };

const ButtonWithLoading = withLoading(Button);

// The rendered component is based on this boolean.
// isLoading === false:  <Button /> is rendered
// isLoading === true:   <Loading /> is rendered
const isLoading = false;

ReactDOM.render(
  <ButtonWithLoading
      isLoading={isLoading}
      onClick={() => alert('hi')}
  >Click Me</ButtonWithLoading>,
  document.getElementById('root')
);
</code>```

I've also posted it to jsfiddle: http://jsfiddle.net/BernieLee/5kn2xa1j/36/

答:
Here is what you need:</p>

```<code>const withLoading = (Component) => {
  const wrapped = ({ isLoading, ...rest }) => (
    isLoading ? <div>Loading</div> : <Component {...rest} />
  );
  wrapped.propTypes = {
    isLoading: PropTypes.bool.isRequired,
  };
  return wrapped;
};
withLoading.propTypes = {
  Component: PropTypes.element,
};
</code>```

Body:
I'm using airbnb configuration for eslint and it's giving me this warning:

[eslint] 'isLoading' is missing in props validation (react/prop-types)

Is there a way to set PropTypes for isLoading?

const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <LoadingSpinner /> : <Component {...rest} />);

Here's an example of how I use it:

const Button = ({ onClick, className, children }) => (
  <button onClick={onClick} className={className} type="button">
    {children}
  </button>
);
Button.propTypes = {
  onClick: PropTypes.func.isRequired,
  className: PropTypes.string,
  children: PropTypes.node.isRequired,
};
Button.defaultProps = {
  onClick: () => {},
  className: '',
  children: 'Click me',
};

const Loading = () => (

Loading...

);

const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <Loading /> : <Component {...rest} />);

// How do I set propTypes for isLoading?
// I tried this but it didn't work:
// withLoading.propTypes = {
// isLoading: PropTypes.bool
// };

const ButtonWithLoading = withLoading(Button);

// The rendered component is based on this boolean.
// isLoading === false:  <Button /> is rendered
// isLoading === true:   <Loading /> is rendered
const isLoading = false;

ReactDOM.render(
  <ButtonWithLoading
      isLoading={isLoading}
      onClick={() => alert('hi')}
  >Click Me</ButtonWithLoading>,
  document.getElementById('root')
);

I've also posted it to jsfiddle: http://jsfiddle.net/BernieLee/5kn2xa1j/36/

Body:
Here is what you need:

const withLoading = (Component) => {
  const wrapped = ({ isLoading, ...rest }) => (
    isLoading ? <div>Loading</div> : <Component {...rest} />
  );
  wrapped.propTypes = {
    isLoading: PropTypes.bool.isRequired,
  };
  return wrapped;
};
withLoading.propTypes = {
  Component: PropTypes.element,
};


问:
Organize list of object in java
I have a class

```<code>public class ProductStock {

   private Long id;
   private Integer quantity;

}
</code>```

and a list like

```<code>List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}
</code>```

I want to group productStocks by id.
What is the best way to convert this list like bellow

```<code>productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
</code>```

答:
I'd do it that way:

```<code>Map<Long, Integer> counting = productStocks.stream().collect(
                Collectors.groupingBy(ProductStock::getId, Collectors.counting()));
</code>```

Create an new Map with the id as key and the Count as value.

Title: Organize list of object in java

Body:
I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and a list like

List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}

I want to group productStocks by id.
What is the best way to convert this list like bellow

productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}

Body:
I'd do it that way:

Map<Long, Integer> counting = productStocks.stream().collect(
                Collectors.groupingBy(ProductStock::getId, Collectors.counting()));

Create an new Map with the id as key and the Count as value.


问:
Cant put Query inside Create sequence sql
The Below query is failing. How to correct it I need to put max id from TBL_PLANNING_REPOSITORY in the create sequence start with.

```<code>CREATE sequence auto_id_planning_repo
start with (select MAX(ID) from TBL_PLANNING_REPOSITORY) increment by 1;
</code>```

答:
DDL statements cannot be mixed with DML expressions. Correct way is something like this:</p>

```<code>lock table tbl_planning_repository in exclusive mode;
var m number;
exec select max(id) into :m from tbl_planning_repository;
exec execute immediate 'create sequence ... start with ' || :m || ' increment by 1';
</code>```

Body:
The Below query is failing. How to correct it I need to put max id from TBL_PLANNING_REPOSITORY in the create sequence start with.

CREATE sequence auto_id_planning_repo
start with (select MAX(ID) from TBL_PLANNING_REPOSITORY) increment by 1;

Body:
DDL statements cannot be mixed with DML expressions. Correct way is something like this:

lock table tbl_planning_repository in exclusive mode;
var m number;
exec select max(id) into :m from tbl_planning_repository;
exec execute immediate 'create sequence ... start with ' || :m || ' increment by 1';


问:
Inserting a php variable in background-image
I'm trying to build a widget for a website that displays a random background image everytime the page is refreshed and i'm running into some trouble with string concatenation.

```<code>$display .= "<p class=\"ey-image-quote\" style\"background-image:url('".$img."')\">" . $this->quote . "</p>";
</code>```

This returns a url without slashes (replaced by spaces) and i have not found a viable solution yet.
Is there any way to achieve this in php?

答:
```<code>$display .= "<p class=\"ey-image-quote\" style=\"background-image:url('".$img."')\">" . $this->quote . "</p>";
</code>```

You forgot = in style

Body:
I'm trying to build a widget for a website that displays a random background image everytime the page is refreshed and i'm running into some trouble with string concatenation.

$display .= "
" . $this->quote . "
";

This returns a url without slashes (replaced by spaces) and i have not found a viable solution yet.
Is there any way to achieve this in php?

Body:
$display .= "<p class=\"ey-image-quote\" style=\"background-image:url('".$img."')\">" . $this->quote . "</p>";

You forgot = in style


问:
Loop with RxSwift
I'm new to Reactive Programming and I have a big problem that I can't solve alone... I need to upload several video assets and in a orderly sequence but I do not know how to do it, I have an array of PHAssets and I'm trying to iterate thru each element and send it over the network
Here is my code so far with comments:</p>

```<code>for item in items {
                    let fileName = item.media.localIdentifier

                    //Observable to generate local url to be used to save the compressed video
                    let compressedVideoOutputUrl = videoHelper.getDocumentsURL().appendingPathComponent(fileName)

                    //Observable to generate a thumbnail image for the video
                    let thumbnailObservable =  videoHelper.getBase64Thumbnail(myItem: item)

                    //Observable to request the video from the iPhone library
                    let videoObservable = videoHelper.requestVideo(myItem: item)

                        //Compress the video and save it on the previously generated local url
                        .flatMap { videoHelper.compressVideo(inputURL: $0, outputURL: compressedVideoOutputUrl) }
                    //Generate the thumbnail and share the video to send over the network
                    let send = videoObservable.flatMap { _ in thumbnailObservable }
                        .flatMap { api.uploadSharedFiles(item, filename: fileName, base64String: $0) }

                    //subscribe the observable
                    send.subscribe(onNext: { data in
                        print("- Done chain sharing Video -")
                    },
                                   onError: { error in
                                    print("Error sharing Video-> \(error.localizedDescription)")
                    }).disposed(by: actionDisposeBag)

                }
</code>```

答:
If you want to upload your items one by one in flatMap, then use enumeration

EDIT: enumeration is useful when you need to know the index of the element, otherwise just flatMap with one argument will do.

```<code>Observable.from(items)
    .enumerated()
    .flatMap() { index, item -> Observable<Item> in
        return uploadItem(item)
    }
    .subscribe(onNext: { print($0) })
    .disposed(by: disposeBag)
</code>```

Title: Loop with RxSwift

Body:
I'm new to Reactive Programming and I have a big problem that I can't solve alone... I need to upload several video assets and in a orderly sequence but I do not know how to do it, I have an array of PHAssets and I'm trying to iterate thru each element and send it over the network
Here is my code so far with comments:

for item in items {
                    let fileName = item.media.localIdentifier

                    //Observable to generate local url to be used to save the compressed video
                    let compressedVideoOutputUrl = videoHelper.getDocumentsURL().appendingPathComponent(fileName)

                    //Observable to generate a thumbnail image for the video
                    let thumbnailObservable =  videoHelper.getBase64Thumbnail(myItem: item)

                    //Observable to request the video from the iPhone library
                    let videoObservable = videoHelper.requestVideo(myItem: item)

                        //Compress the video and save it on the previously generated local url
                        .flatMap { videoHelper.compressVideo(inputURL: $0, outputURL: compressedVideoOutputUrl) }
                    //Generate the thumbnail and share the video to send over the network
                    let send = videoObservable.flatMap { _ in thumbnailObservable }
                        .flatMap { api.uploadSharedFiles(item, filename: fileName, base64String: $0) }

                    //subscribe the observable
                    send.subscribe(onNext: { data in
                        print("- Done chain sharing Video -")
                    },
                                   onError: { error in
                                    print("Error sharing Video-> \(error.localizedDescription)")
                    }).disposed(by: actionDisposeBag)

                }

Body:
If you want to upload your items one by one in flatMap, then use enumeration

EDIT: enumeration is useful when you need to know the index of the element, otherwise just flatMap with one argument will do.

Observable.from(items)
    .enumerated()
    .flatMap() { index, item -> Observable<Item> in
        return uploadItem(item)
    }
    .subscribe(onNext: { print($0) })
    .disposed(by: disposeBag)


问:
Add property to folder
I have a spec file in Jenkins uploading artifacts to Artifactory repository path test-local/web/develop/web-DEVELOP-12/ where 12 is the build number from Jenkins.

All artifacts are uploaded under web-DEVELOP-XX. I would like this folder to have the same properties as the artifacts such as vcs.revision, build.timestamp, build.name, build.number. Here I only get those properties in the artifact files under web-DEVELOP-XX folder, but I would like to also have those properties to the folder web-DEVELOP-XX.

Is it possible to do this from Jenkins?

答:
you're correct that currently Properties set using a file spec are not set on the root folder.
you can add (at the end of your current set props) a simple curl command to set the properties on the folder.
For ex, this will set a property a=b on "all-my-frogs" folder under my-local-repo repository:

```<code>PUT http://rtserver:port/artifactory/api/storage/my-local-repo/all-my-frogs?properties=a=b&recursive=0
</code>```

note: recursive=1  will set the properties on all files under the folder as well as the folder itself, so you can consider that as your solution (instead of spec)

Title: Add property to folder

Body:
you're correct that currently Properties set using a file spec are not set on the root folder.
you can add (at the end of your current set props) a simple curl command to set the properties on the folder.
For ex, this will set a property a=b on "all-my-frogs" folder under my-local-repo repository:

PUT http://rtserver:port/artifactory/api/storage/my-local-repo/all-my-frogs?properties=a=b&recursive=0

note: recursive=1  will set the properties on all files under the folder as well as the folder itself, so you can consider that as your solution (instead of spec)


问:
Where should HTML be rendered in Object-Oriented PHP design?
Using Object-Oriented PHP, where should HTML be rendered?

The business processes include several actions to maintain customer records.

Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?

Where should code like this reside?

```<code>$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];

     echo '<div class="custTrans">';
         echo '<span class="custTransAmount">'.$amount.'</span>';
         echo '<span class="custTransDate">'.$date.'</span>';
         echo '<span class="custTransproduct">'.$product.'</span>';
     echo '</div>';
}
</code>```

Perhaps an MVC framework like codeigniter would be better?

答:
I'm still figuring out what's the best way to keep php and layout seperate without too much fuzz. For the moment I really like the include-templating approach, beacause it's so simple and has no restrictions.

So, for your example, you would have a php file (example.php) that looks like this:

```<code><?php
$custTrans = Customer.getTransactions();

$displ_transactions = array();

foreach ($custTrans as $ct){
     $transaction = array(
         'amount' => $ct[0],
         'date' => $ct[1];
         'product' => $ct[2];
     );
     $displ_transactions[] = $transaction; // this will push the transacion into the array
}
include 'example.tpl.php'
?>
</code>```

And then you need a second file (example.tpl.php):

```<code><?php foreach ($displ_transactions as $transaction) { ?>
     <div class="custTrans">
         <span class='custTransAmount'><?php echo $transaction['amount'] ?></span>;
         <span class='custTransDate'><?php echo $transaction['date'] ?></span>;
         <span class='custTransproduct'><?php echo $transaction['product'] ?></span>;
     </div>
<?php } ?>
</code>```

Just call example.php in your browser and you will see the same result as you had before.
This is all good and well for small websites, because this method causes some overhead. If you are serious about templating, use smarty. it's easy to learn, and it has automatic caching, so it's super fast.

I just realize you can also do it this way:

example.php:

```<code><?php
$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];
     include 'example.tpl.php';
}
?>
</code>```

example.tpl.php:

```<code> <div class="custTrans">
     <span class='custTransAmount'><?php echo $amount ?></span>;
     <span class='custTransDate'><?php echo $date ?></span>;
     <span class='custTransproduct'><?php echo $product ?></span>;
 </div>
</code>```

Use whatever suits you best :)

Body:
Using Object-Oriented PHP, where should HTML be rendered?

The business processes include several actions to maintain customer records.

Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?

Where should code like this reside?

$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];

     echo '
';
         echo ''.$amount.'';
         echo ''.$date.'';
         echo ''.$product.'';
     echo '
';
}

Perhaps an MVC framework like codeigniter would be better?

Body:
I'm still figuring out what's the best way to keep php and layout seperate without too much fuzz. For the moment I really like the include-templating approach, beacause it's so simple and has no restrictions.

So, for your example, you would have a php file (example.php) that looks like this:

<?php
$custTrans = Customer.getTransactions();

$displ_transactions = array();

foreach ($custTrans as $ct){
     $transaction = array(
         'amount' => $ct[0],
         'date' => $ct[1];
         'product' => $ct[2];
     );
     $displ_transactions[] = $transaction; // this will push the transacion into the array
}
include 'example.tpl.php'
?>

And then you need a second file (example.tpl.php):

<?php foreach ($displ_transactions as $transaction) { ?>
     <div class="custTrans">
         <span class='custTransAmount'><?php echo $transaction['amount'] ?></span>;
         <span class='custTransDate'><?php echo $transaction['date'] ?></span>;
         <span class='custTransproduct'><?php echo $transaction['product'] ?></span>;
     </div>
<?php } ?>

Just call example.php in your browser and you will see the same result as you had before.
This is all good and well for small websites, because this method causes some overhead. If you are serious about templating, use smarty. it's easy to learn, and it has automatic caching, so it's super fast.

I just realize you can also do it this way:

example.php:

<?php
$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];
     include 'example.tpl.php';
}
?>

example.tpl.php:

 <div class="custTrans">
     <span class='custTransAmount'><?php echo $amount ?></span>;
     <span class='custTransDate'><?php echo $date ?></span>;
     <span class='custTransproduct'><?php echo $product ?></span>;
 </div>

Use whatever suits you best :)


问:
Angular 4 - interceptor handle net::ERR_CONNECTION_REFUSED
In the code bellow, I try to intercept my http requests. Whenever I can establish a http connection, my interceptor works, but when I got net::ERR_CONNECTION_REFUSED, the event variable is not a instance of HttpResponse, so I can't deal with this kind of error. Here is my code:

```<code>intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.changeStatus(false);
    this.requests_count++;
    const my_req = req.clone({
        url: API_PATH + req.url
    });
    return next
        .handle(my_req)
        .do(event => {
            if (event instanceof HttpResponse) {
                this.requests_count--;
                if (!this.requests_count)
                    this.changeStatus(true);
            }
        });
}
</code>```

How can I detect in the interceptor errors like net::ERR_CONNECTION_REFUSED?

答:
Just got it!</p>

```<code>.do(
    event => {
        if (event instanceof HttpResponse) {
            this.requests_count--;
            if (!this.requests_count)
                this.changeStatus(true);
        }
    },
    error => {
        if (error instanceof HttpErrorResponse) {
            this.requests_count--;
            if (!this.requests_count)
                this.changeStatus(true);
        }
    }
);
</code>```

Body:
In the code bellow, I try to intercept my http requests. Whenever I can establish a http connection, my interceptor works, but when I got net::ERR_CONNECTION_REFUSED, the event variable is not a instance of HttpResponse, so I can't deal with this kind of error. Here is my code:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.changeStatus(false);
    this.requests_count++;
    const my_req = req.clone({
        url: API_PATH + req.url
    });
    return next
        .handle(my_req)
        .do(event => {
            if (event instanceof HttpResponse) {
                this.requests_count--;
                if (!this.requests_count)
                    this.changeStatus(true);
            }
        });
}

How can I detect in the interceptor errors like net::ERR_CONNECTION_REFUSED?

Body:
Just got it!

.do(
    event => {
        if (event instanceof HttpResponse) {
            this.requests_count--;
            if (!this.requests_count)
                this.changeStatus(true);
        }
    },
    error => {
        if (error instanceof HttpErrorResponse) {
            this.requests_count--;
            if (!this.requests_count)
                this.changeStatus(true);
        }
    }
);


问:
Vuejs component template : How to loop through specific array keys using v-for
This is how the template of my component looks like:

```<code><tr v-for="row in user.data">

                    <td v-for="(value,key) in row">

                        {{key}}-{{value}}

                    </td>
</tr>
</code>```

I want to exclude some keys from this loop, I know that the best solution is to use the computed function but a don't know how to implement it.

答:
You can create an array of keys you want to ignore:

```<code>data: function () {
        return {
            ignore: [
             'key1',
             'key2',
             'key3'
            ]
</code>```

Then add v-if statement that would loop through "ignore" array and skip the output if the key matches:

```<code>  <td v-for="(value,key) in row"
      v-if="!ignore.includes(row.key)">

                    {{key}}-{{value}}

  </td>
</code>```

Body:
This is how the template of my component looks like:

                        {{key}}-{{value}}

I want to exclude some keys from this loop, I know that the best solution is to use the computed function but a don't know how to implement it.

Body:
You can create an array of keys you want to ignore:

data: function () {
        return {
            ignore: [
             'key1',
             'key2',
             'key3'
            ]

Then add v-if statement that would loop through "ignore" array and skip the output if the key matches:

  <td v-for="(value,key) in row"
      v-if="!ignore.includes(row.key)">

                    {{key}}-{{value}}

  </td>


问:
Error: connect ECONNREFUSED 127.0.1.1:80 when launching grunt-fetch-pages (node.js)
I've got this issue launching fetchpages Grunt plugin:

```<code>Running "fetchpages:dist" (fetchpages) task
Fetching pages...
skipping duplicate page {"local":"public_html/speed/www-fetched/index.html","remote":"http://example.com/"}
Creating folders...
  https://example.com/ -> public_html/speed/www-fetched/index.html
{ Error: connect ECONNREFUSED 127.0.1.1:80
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.1.1',
  port: 80 }
  https://example.com/scrap-metal-prices -> public_html/speed/www-fetched/scrap-price.html
</code>```

I've never seen this kind of errors in other projects before.

I use grunt-fetch-pages@2.0.0 and Node v6.11.5.

What does it mean and how to solve?

答:
I just commented (#) this string in /etc/hosts:

```<code>#127.0.1.1 example.com example
</code>```

Now it's ok.

Body:
I've got this issue launching fetchpages Grunt plugin:

Running "fetchpages:dist" (fetchpages) task
Fetching pages...
skipping duplicate page {"local":"public_html/speed/www-fetched/index.html","remote":"http://example.com/"}
Creating folders...
  https://example.com/ -> public_html/speed/www-fetched/index.html
{ Error: connect ECONNREFUSED 127.0.1.1:80
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.1.1',
  port: 80 }
  https://example.com/scrap-metal-prices -> public_html/speed/www-fetched/scrap-price.html

I've never seen this kind of errors in other projects before.

I use grunt-fetch-pages@2.0.0 and Node v6.11.5.

What does it mean and how to solve?

Body:
I just commented (#) this string in /etc/hosts:

#127.0.1.1 example.com example

Now it's ok.


问:
DynamoDB Sort and select top 20 records
I wanted to get records like top 10 or 20 basically some configurable number which are sorted based on a date field stored as ISO-8601 format uuuu-MM-dd after applying some filters.

```<code>@DynamoDBTable(tableName = "Data")
@NoArgsConstructor
@ToString
public class Data {

    private LocalDate date;
    @Setter
    private Long number;
    @Setter
    private STATUS status;

    @DynamoDBHashKey
    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public LocalDate getDate() {
        return date;
    }

    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public void setDate(LocalDate date) {
        this.date = date;
    }

    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_number")
    public Long getCompetitionId() {
        return number;
    }

    @DynamoDBTypeConvertedEnum
    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_status")
    public STATUS getStatus() {
        return status;
    }
}
</code>```

I need to get say 20 records sorted based on date field after filtering based on number and multiple status. I was using ScanRequest to basically filter the records. Now I want to limit the results and get top records based on the date.

```<code>@AllArgsConstructor
public class DataRepositoryImpl implements DataRepository {
 private final DynamoDBMapper dynamoDBMapper;
 private final AmazonDynamoDB amazonDynamoDB;

 @Override
 public List<Data> findAll(Long number, List<String> status) {
    Condition numberCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withN(String.valueOf(number)));

    List<AttributeValue> attributeValues = newArrayList();
    status.forEach(s -> attributeValues.add(new AttributeValue().withS(s)));
    Condition statusCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.IN)
            .withAttributeValueList(attributeValues);

    Map<String, Condition> conditions = newHashMap();
    conditions.put("number", numberCondition);
    conditions.put("status", statusCondition);

    ScanRequest scanRequest = new ScanRequest()
            .withTableName("Data")
            .withScanFilter(conditions)
            .withConditionalOperator(ConditionalOperator.AND);

    ScanResult scanResult = amazonDynamoDB.scan(scanRequest);
    return dynamoDBMapper.marshallIntoObjects(Data.class, scanResult.getItems());
    }
}
</code>```

答:
I don't believe you can achieve this using DynamoDB. You will have to order and filter the result using application code.

The only way DynamoDB will return ordered results is if you use a sort key. However your initial query is multi dimensional (one number, many status'), so you cannot create a partition that would work in this case.

If you wanted to query on say a single number, and order by date, you could use number as your partition key and a new 'date as long number' attribute as your sort key. DynamoDB keys can only be String,Number or Binary attributes. I assume your LocalDateConverter changes the date to a string, so this wouldn't make a good sort key. However, you could add a new attribute that was a number and represented the date in YYYYMMDDHHMMSS format, which would naturally sort in the correct order. You could then use DynamoDB ScanIndexForward function and limit your result set to a given number of items.

Title: DynamoDB Sort and select top 20 records

Body:
I wanted to get records like top 10 or 20 basically some configurable number which are sorted based on a date field stored as ISO-8601 format uuuu-MM-dd after applying some filters.

@DynamoDBTable(tableName = "Data")
@NoArgsConstructor
@ToString
public class Data {

    private LocalDate date;
    @Setter
    private Long number;
    @Setter
    private STATUS status;

    @DynamoDBHashKey
    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public LocalDate getDate() {
        return date;
    }

    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public void setDate(LocalDate date) {
        this.date = date;
    }

    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_number")
    public Long getCompetitionId() {
        return number;
    }

    @DynamoDBTypeConvertedEnum
    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_status")
    public STATUS getStatus() {
        return status;
    }
}

I need to get say 20 records sorted based on date field after filtering based on number and multiple status. I was using ScanRequest to basically filter the records. Now I want to limit the results and get top records based on the date.

@AllArgsConstructor
public class DataRepositoryImpl implements DataRepository {
 private final DynamoDBMapper dynamoDBMapper;
 private final AmazonDynamoDB amazonDynamoDB;

 @Override
 public List<Data> findAll(Long number, List<String> status) {
    Condition numberCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withN(String.valueOf(number)));

    List<AttributeValue> attributeValues = newArrayList();
    status.forEach(s -> attributeValues.add(new AttributeValue().withS(s)));
    Condition statusCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.IN)
            .withAttributeValueList(attributeValues);

    Map<String, Condition> conditions = newHashMap();
    conditions.put("number", numberCondition);
    conditions.put("status", statusCondition);

    ScanRequest scanRequest = new ScanRequest()
            .withTableName("Data")
            .withScanFilter(conditions)
            .withConditionalOperator(ConditionalOperator.AND);

    ScanResult scanResult = amazonDynamoDB.scan(scanRequest);
    return dynamoDBMapper.marshallIntoObjects(Data.class, scanResult.getItems());
    }
}


问:
Array to string conversion - Laravel
I am trying to store the id of the selected item in my drop down but I get an error array to string conversion.

HTML

    Age

        <select class="form-control" id="age" name="age[]" mulitple>
            @foreach($ages as $age)
                <option value="{!! $age->id !!}" @if(in_array($age->id, $selectedAges)) selected="selected" @endif >
                    {!! $age->id !!}
                </option>
            @endforeach
        </select>

```

<p><strong>Controller</strong></p>

<pre class="lang-php prettyprint-override"><code>$user = new User(array(
    'name' => $request->get('name'),
    'age' => $request->get('age'),
));

$user->save();
</code>```

答:
As you are using mulitple and if you want to store in single column for [10,20,30] as 10,20,30 which is varchar not integer try like this

First change name in html from name="age[]" to name="age" and then get value in controller

```<code>'age' => implode(",",$request->age),
</code>```

Title: Array to string conversion - Laravel

Body:
I am trying to store the id of the selected item in my drop down but I get an error array to string conversion.

HTML

    Age

        <select class="form-control" id="age" name="age[]" mulitple>
            @foreach($ages as $age)
                <option value="{!! $age->id !!}" @if(in_array($age->id, $selectedAges)) selected="selected" @endif >
                    {!! $age->id !!}
                </option>
            @endforeach
        </select>

Controller

$user = new User(array(
    'name' => $request->get('name'),
    'age' => $request->get('age'),
));

$user->save();

Body:
As you are using mulitple and if you want to store in single column for [10,20,30] as 10,20,30 which is varchar not integer try like this

First change name in html from name="age[]" to name="age" and then get value in controller

'age' => implode(",",$request->age),


问:
Writing filenames from folder in CSV in Python
I want to write the filenames of a particular folder in a CSV file( for the purpose of bulk uploading to the Internet Archive). The CSV must be written in the prescribed format.

I have tried the following code :

```<code>import os
import csv

path = '/media/sarada/Lectures & Ebooks/Ebooks/03-Bengali Books/18.Darshan'

with open('/home/sarada/ia_csv.csv', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for dirpath, _, filenames in os.walk(path):
    if filenames:
      writer.writerow([os.path.basename(dirpath)] + filenames)
</code>```

Now the file names are being printed in a row, i.e they are covering the description, title, creator etc. fields.

The issues:

File names should be printed in the file column only.

How to print only the file name(stripping the extension portion) in
title column?

How to add a string(e.g opensource) in

writer.writerow([os.path.basename(dirpath)] + filenames) so that

the creator column contains that string?

答:
For the simple CSV writer you will have to provide each field (you actually did this already for the header row). This is a bit tedious, you may want to consider using a DictWriter which is
easier to handle/understand.</p>

```<code>import os
import csv

path = 'YOUR_INPUT_DIRECTORY'

with open('YOUR_OUTPUT_FILE', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for root, dirs, files in os.walk(path):
    for filename in files:
        writer.writerow(['', os.path.join(root,filename), '','','', 'opensource','',''])
</code>```

Body:
I want to write the filenames of a particular folder in a CSV file( for the purpose of bulk uploading to the Internet Archive). The CSV must be written in the prescribed format.

I have tried the following code :

import os
import csv

path = '/media/sarada/Lectures & Ebooks/Ebooks/03-Bengali Books/18.Darshan'

with open('/home/sarada/ia_csv.csv', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for dirpath, _, filenames in os.walk(path):
    if filenames:
      writer.writerow([os.path.basename(dirpath)] + filenames)

Now the file names are being printed in a row, i.e they are covering the description, title, creator etc. fields.

The issues:

File names should be printed in the file column only.

How to print only the file name(stripping the extension portion) in
title column?

How to add a string(e.g opensource) in

writer.writerow([os.path.basename(dirpath)] + filenames) so that

the creator column contains that string?

Body:
For the simple CSV writer you will have to provide each field (you actually did this already for the header row). This is a bit tedious, you may want to consider using a DictWriter which is
easier to handle/understand.

import os
import csv

path = 'YOUR_INPUT_DIRECTORY'

with open('YOUR_OUTPUT_FILE', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for root, dirs, files in os.walk(path):
    for filename in files:
        writer.writerow(['', os.path.join(root,filename), '','','', 'opensource','',''])


问:
Smart Contract in Geth using web3j
I am trying to deploy my solidity smart contract on the ethereum testrpc network.
This is my solidity contract:

```<code>pragma solidity ^0.4.11;

contract Fibonacci {

    event Notify(uint input, uint result);

    function fibonacci(uint number) constant returns(uint result) {
        if (number == 0) return 0;
        else if (number == 1) return 1;
        else return Fibonacci.fibonacci(number - 1) + Fibonacci.fibonacci(number - 2);
    }

    function fibonacciNotify(uint number) returns(uint result) {
        result = fibonacci(number);
        Notify(number, result);
    }
}
</code>```

I am using web3j for deploying this contract in the ethereum testrpc network which is now running only in one computer.
Following is the command i am using in JAVA console:

```<code>Future<FibonacciZKF> fib= FibonacciZKF.deploy(Web3j.build(new HttpService()), ALICE, GAS_PRICE, GAS_LIMIT, BigInteger.valueOf(5));
</code>```

I have generated all the necessary abi and bin for the above contract.

I have even generated a wrapper as directed for the above contract.
This is my wrapper for the contract:

```<code>public final class Fibonacci extends Contract {
    private static final String BINARY = "6060604052341561000f57600080fd5b5b61015a8061001f6000396000f300606060405263ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633c7fdc70811461004857806361047ff414610070575b600080fd5b341561005357600080fd5b61005e600435610098565b60405190815260200160405180910390f35b341561007b57600080fd5b61005e6004356100e5565b60405190815260200160405180910390f35b60006100a3826100e5565b90507f71e71a8458267085d5ab16980fd5f114d2d37f232479c245d523ce8d23ca40ed828260405191825260208201526040908101905180910390a15b919050565b60008115156100f6575060006100e0565b8160011415610107575060016100e0565b610113600283036100e5565b61011f600184036100e5565b0190506100e0565b5b5b9190505600a165627a7a723058208c691bf2e824f14fefeb8b2e4932d9a9122cbe5835242992958daf1fc4a81af60029";

private Fibonacci(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}

private Fibonacci(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

public List<NotifyEventResponse> getNotifyEvents(TransactionReceipt transactionReceipt) {
    final Event event = new Event("Notify",
            Arrays.<TypeReference<?>>asList(),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));
    List<EventValues> valueList = extractEventParameters(event, transactionReceipt);
    ArrayList<NotifyEventResponse> responses = new ArrayList<NotifyEventResponse>(valueList.size());
    for (EventValues eventValues : valueList) {
        NotifyEventResponse typedResponse = new NotifyEventResponse();
        typedResponse.input = (Uint256) eventValues.getNonIndexedValues().get(0);
        typedResponse.result = (Uint256) eventValues.getNonIndexedValues().get(1);
        responses.add(typedResponse);
    }
    return responses;
}

public Observable<NotifyEventResponse> notifyEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("Notify",
            Arrays.<TypeReference<?>>asList(),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, NotifyEventResponse>() {
        @Override
        public NotifyEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            NotifyEventResponse typedResponse = new NotifyEventResponse();
            typedResponse.input = (Uint256) eventValues.getNonIndexedValues().get(0);
            typedResponse.result = (Uint256) eventValues.getNonIndexedValues().get(1);
            return typedResponse;
        }
    });
}

public Future<TransactionReceipt> fibonacciNotify(Uint256 number) {
    Function function = new Function("fibonacciNotify", Arrays.<Type>asList(number), Collections.<TypeReference<?>>emptyList());
    return executeTransactionAsync(function);
}

public Future<Uint256> fibonacci(Uint256 number) {
    Function function = new Function("fibonacci",
            Arrays.<Type>asList(number),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    return executeCallSingleValueReturnAsync(function);
}

public static Future<Fibonacci> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue) {
    return deployAsync(Fibonacci.class, web3j, credentials, gasPrice, gasLimit, BINARY, "", initialWeiValue);
}

public static Future<Fibonacci> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue) {
    return deployAsync(Fibonacci.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "", initialWeiValue);
}

public static Fibonacci load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    return new Fibonacci(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

public static Fibonacci load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    return new Fibonacci(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

public static class NotifyEventResponse {
    public Uint256 input;

    public Uint256 result;
}
</code>```

}

But I am not able to deploy on this tetrpc Ethereum Network. Could anyone answer WHY?

答:
You must check that your client has either; Connected to the testnet and is running a node, or has attached to a geth node that is connected to the testnet.

Can you provide code that shows how you try to connect to the testnet?

I was able to attach to my geth node by the following;

```<code>    try {
        web3j = Web3j.build(new HttpService("Http://localhost:8545"));
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
</code>```

Title: Smart Contract in Geth using web3j

Body:
I am trying to deploy my solidity smart contract on the ethereum testrpc network.
This is my solidity contract:

pragma solidity ^0.4.11;

contract Fibonacci {

    event Notify(uint input, uint result);

    function fibonacci(uint number) constant returns(uint result) {
        if (number == 0) return 0;
        else if (number == 1) return 1;
        else return Fibonacci.fibonacci(number - 1) + Fibonacci.fibonacci(number - 2);
    }

    function fibonacciNotify(uint number) returns(uint result) {
        result = fibonacci(number);
        Notify(number, result);
    }
}

I am using web3j for deploying this contract in the ethereum testrpc network which is now running only in one computer.
Following is the command i am using in JAVA console:

Future<FibonacciZKF> fib= FibonacciZKF.deploy(Web3j.build(new HttpService()), ALICE, GAS_PRICE, GAS_LIMIT, BigInteger.valueOf(5));

I have generated all the necessary abi and bin for the above contract.

I have even generated a wrapper as directed for the above contract.
This is my wrapper for the contract:

public final class Fibonacci extends Contract {
    private static final String BINARY = "6060604052341561000f57600080fd5b5b61015a8061001f6000396000f300606060405263ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633c7fdc70811461004857806361047ff414610070575b600080fd5b341561005357600080fd5b61005e600435610098565b60405190815260200160405180910390f35b341561007b57600080fd5b61005e6004356100e5565b60405190815260200160405180910390f35b60006100a3826100e5565b90507f71e71a8458267085d5ab16980fd5f114d2d37f232479c245d523ce8d23ca40ed828260405191825260208201526040908101905180910390a15b919050565b60008115156100f6575060006100e0565b8160011415610107575060016100e0565b610113600283036100e5565b61011f600184036100e5565b0190506100e0565b5b5b9190505600a165627a7a723058208c691bf2e824f14fefeb8b2e4932d9a9122cbe5835242992958daf1fc4a81af60029";

private Fibonacci(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}

private Fibonacci(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

public List<NotifyEventResponse> getNotifyEvents(TransactionReceipt transactionReceipt) {
    final Event event = new Event("Notify",
            Arrays.<TypeReference<?>>asList(),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));
    List<EventValues> valueList = extractEventParameters(event, transactionReceipt);
    ArrayList<NotifyEventResponse> responses = new ArrayList<NotifyEventResponse>(valueList.size());
    for (EventValues eventValues : valueList) {
        NotifyEventResponse typedResponse = new NotifyEventResponse();
        typedResponse.input = (Uint256) eventValues.getNonIndexedValues().get(0);
        typedResponse.result = (Uint256) eventValues.getNonIndexedValues().get(1);
        responses.add(typedResponse);
    }
    return responses;
}

public Observable<NotifyEventResponse> notifyEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
    final Event event = new Event("Notify",
            Arrays.<TypeReference<?>>asList(),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));
    EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
    filter.addSingleTopic(EventEncoder.encode(event));
    return web3j.ethLogObservable(filter).map(new Func1<Log, NotifyEventResponse>() {
        @Override
        public NotifyEventResponse call(Log log) {
            EventValues eventValues = extractEventParameters(event, log);
            NotifyEventResponse typedResponse = new NotifyEventResponse();
            typedResponse.input = (Uint256) eventValues.getNonIndexedValues().get(0);
            typedResponse.result = (Uint256) eventValues.getNonIndexedValues().get(1);
            return typedResponse;
        }
    });
}

public Future<TransactionReceipt> fibonacciNotify(Uint256 number) {
    Function function = new Function("fibonacciNotify", Arrays.<Type>asList(number), Collections.<TypeReference<?>>emptyList());
    return executeTransactionAsync(function);
}

public Future<Uint256> fibonacci(Uint256 number) {
    Function function = new Function("fibonacci",
            Arrays.<Type>asList(number),
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
    return executeCallSingleValueReturnAsync(function);
}

public static Future<Fibonacci> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue) {
    return deployAsync(Fibonacci.class, web3j, credentials, gasPrice, gasLimit, BINARY, "", initialWeiValue);
}

public static Future<Fibonacci> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialWeiValue) {
    return deployAsync(Fibonacci.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "", initialWeiValue);
}

public static Fibonacci load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    return new Fibonacci(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

public static Fibonacci load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    return new Fibonacci(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

public static class NotifyEventResponse {
    public Uint256 input;

    public Uint256 result;
}

}

But I am not able to deploy on this tetrpc Ethereum Network. Could anyone answer WHY?

Body:
You must check that your client has either; Connected to the testnet and is running a node, or has attached to a geth node that is connected to the testnet.

Can you provide code that shows how you try to connect to the testnet?

I was able to attach to my geth node by the following;

    try {
        web3j = Web3j.build(new HttpService("Http://localhost:8545"));
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }


问:
Is it possible to get `mvn tomcat6:run` to work correctly with a filtered web.xml?
I have a project that needs to have ${} placeholder substitution applied to web.xml that I want to run for development mode with mvn tomcat6:run. Is it possible to set this up?

This is a legacy codebase where I'm trying to introduce both deployment environments to get rid of the previous process that was "copy web.xml variants around and edit a config file and keep this out of source control." I also want to avoid having to maintain a Tomcat installation and setting up an IDE to deploy to it, and just have the application execute using tomcat6-maven-plugin.

What I have so far is this project layout:

```<code>foo
│   pom.xml
│
└───src
    └───main
        ├───environments
        │   ├───BAR
        │   │       filter.properties
        │   │
        │   └───FOO
        │           filter.properties
        │
        ├───java
        │   └───se
        │       └───millimoo
        │               IndexServlet.java
        │
        └───webapp
            └───WEB-INF
                    web.xml
</code>```

pom.xml

```<code>...
<build>
    <filters>
        <filter>src/main/environments/${environment}/filter.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/environments/${environment}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat6-maven-plugin</artifactId>
            <version>2.2</version>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>env-foo</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <environment>FOO</environment>
        </properties>
    </profile>
    <profile>
        <id>env-bar</id>
        <properties>
            <environment>BAR</environment>
        </properties>
    </profile>
</profiles>
...
</code>```

That is: I add the directory for an environment as a resource; tell Maven to load placeholder values from filter.properties in that directory; and tell the WAR plugin to filter the deployment descriptors. I also set up two profiles to switch between the environments.

FOO\filter.properties

```<code>filter.environment=foofoo
</code>```

BAR\filter.properties

```<code>filter.environment=barbar
</code>```

web.xml

```<code>...
<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>se.millimoo.IndexServlet</servlet-class>
    <init-param>
        <param-name>environment</param-name>
        <param-value>${filter.environment}</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
...
</code>```

IndexServlet.java

Prints the value of the environment init param.

What happens is that when I run this using mvn tomcat6:run, it uses the unfiltered web.xml, which is obviously not what I want. The filtered version is used when I use mvn tomcat6:run-war, but I'm not a fan of that: it's slower, and has other issues in my real code that generally slow down turnaround, which is the point of the exercise. (It uses the JAR files of dependent projects where the backend code is from the Maven repository to build the JAR, which can be either outdated or not available at all if I haven't installed them after a version number bump; rather than using the current code.)

Is there a way to get the best of both worlds here? Be able to run the app server through maven or in another easily embedded way, while also having filtering applied to web.xml? Preferrably without significantly changing the app itself, i.e. I don't want to load the configuration values without using servlet init params. (In the real code, the servlet is a third-party one.)

答:
It seems that the goal I want is tomcat6:run-war-only, which starts a Tomcat over the assembled webapp in target/. However, this goal doesn't invoke the rest of the lifecycle when run on its own, meaning the app might not be assembled or up-to-date. I resolved this by first replacing the war:war goal with war:war-exploded in the package phase of the lifecycle, and binding tomcat6:run-war-only to verify, the next lifecycle phase. (Which, conveniently enough, doesn't have any goals bound for war projects, and seems appropriate semantically.) To keep this contained, I put it into a profile:

```<code><profile>
    <id>embedded</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Replace running war:war with war:exploded in the lifecycle -->
                    <execution>
                        <id>embedded-war</id>
                        <goals>
                            <goal>exploded</goal>
                        </goals>
                        <phase>package</phase>
                    </execution>
                    <execution>
                        <id>default-war</id>
                        <phase>none</phase>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat6-maven-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <!-- Run Tomcat over the assembled webapp -->
                    <execution>
                        <id>embedded-verify</id>
                        <goals>
                            <goal>run-war-only</goal>
                        </goals>
                        <phase>verify</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

Combined with what's already given in the question, to run the foo environment, you use:

```<code>mvn -P embedded,env-foo verify
</code>```

One flaw this has is that it won't reflect live changes to views or such, but running mvn war:exploded to reassemble the app while the Tomcat server is running should take care of that.

Body:
I have a project that needs to have ${} placeholder substitution applied to web.xml that I want to run for development mode with mvn tomcat6:run. Is it possible to set this up?

This is a legacy codebase where I'm trying to introduce both deployment environments to get rid of the previous process that was "copy web.xml variants around and edit a config file and keep this out of source control." I also want to avoid having to maintain a Tomcat installation and setting up an IDE to deploy to it, and just have the application execute using tomcat6-maven-plugin.

What I have so far is this project layout:

foo
│   pom.xml
│
└───src
    └───main
        ├───environments
        │   ├───BAR
        │   │       filter.properties
        │   │
        │   └───FOO
        │           filter.properties
        │
        ├───java
        │   └───se
        │       └───millimoo
        │               IndexServlet.java
        │
        └───webapp
            └───WEB-INF
                    web.xml

pom.xml

...
<build>
    <filters>
        <filter>src/main/environments/${environment}/filter.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/environments/${environment}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat6-maven-plugin</artifactId>
            <version>2.2</version>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>env-foo</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <environment>FOO</environment>
        </properties>
    </profile>
    <profile>
        <id>env-bar</id>
        <properties>
            <environment>BAR</environment>
        </properties>
    </profile>
</profiles>
...

That is: I add the directory for an environment as a resource; tell Maven to load placeholder values from filter.properties in that directory; and tell the WAR plugin to filter the deployment descriptors. I also set up two profiles to switch between the environments.

FOO\filter.properties

filter.environment=foofoo

BAR\filter.properties

filter.environment=barbar

web.xml

...
<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>se.millimoo.IndexServlet</servlet-class>
    <init-param>
        <param-name>environment</param-name>
        <param-value>${filter.environment}</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
...

IndexServlet.java

Prints the value of the environment init param.

What happens is that when I run this using mvn tomcat6:run, it uses the unfiltered web.xml, which is obviously not what I want. The filtered version is used when I use mvn tomcat6:run-war, but I'm not a fan of that: it's slower, and has other issues in my real code that generally slow down turnaround, which is the point of the exercise. (It uses the JAR files of dependent projects where the backend code is from the Maven repository to build the JAR, which can be either outdated or not available at all if I haven't installed them after a version number bump; rather than using the current code.)

Is there a way to get the best of both worlds here? Be able to run the app server through maven or in another easily embedded way, while also having filtering applied to web.xml? Preferrably without significantly changing the app itself, i.e. I don't want to load the configuration values without using servlet init params. (In the real code, the servlet is a third-party one.)

Body:
It seems that the goal I want is tomcat6:run-war-only, which starts a Tomcat over the assembled webapp in target/. However, this goal doesn't invoke the rest of the lifecycle when run on its own, meaning the app might not be assembled or up-to-date. I resolved this by first replacing the war:war goal with war:war-exploded in the package phase of the lifecycle, and binding tomcat6:run-war-only to verify, the next lifecycle phase. (Which, conveniently enough, doesn't have any goals bound for war projects, and seems appropriate semantically.) To keep this contained, I put it into a profile:

<profile>
    <id>embedded</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Replace running war:war with war:exploded in the lifecycle -->
                    <execution>
                        <id>embedded-war</id>
                        <goals>
                            <goal>exploded</goal>
                        </goals>
                        <phase>package</phase>
                    </execution>
                    <execution>
                        <id>default-war</id>
                        <phase>none</phase>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat6-maven-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <!-- Run Tomcat over the assembled webapp -->
                    <execution>
                        <id>embedded-verify</id>
                        <goals>
                            <goal>run-war-only</goal>
                        </goals>
                        <phase>verify</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Combined with what's already given in the question, to run the foo environment, you use:

mvn -P embedded,env-foo verify

One flaw this has is that it won't reflect live changes to views or such, but running mvn war:exploded to reassemble the app while the Tomcat server is running should take care of that.