问:
Storing derived data in the state
Is it a good idea to store derived data in the state in React? The reason I'm looking to do this is to ensure that re-renders occur when the source data set changes.

One example I have with Flux;

class ProductList extends React.PureComponent {
    componentDidMount = () => {
        this.props.flux.store('ProductStore').on('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').on('change', this.getStateFromFlux);
    }

    componentWillUnmount = () => {
        this.props.flux.store('ProductStore').off('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').off('change', this.getStateFromFlux);
    }

    getStateFromFlux = () => this.setState({ products: this.props.flux.store('ProductStore').getProducts() })

    _isAvailable = product => this.props.flux.store('ProductAvailabilityStore').isAvailable(product.id);

    render = () => this.state.products.map(product => (
        <Product available={this._isAvailable(product)} product={product} />
    ))
}
```

<p>In this case, product availability changing <em>won't</em> cause a re-render, which is not what I want.</p>

<p>Now I could do something like this;</p>

<pre class="lang-js prettyprint-override"><code>class ProductList extends React.PureComponent {
    componentDidMount = () => {
        this.props.flux.store('ProductStore').on('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').on('change', this.getStateFromFlux);
    }

    componentWillUnmount = () => {
        this.props.flux.store('ProductStore').off('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').off('change', this.getStateFromFlux);
    }

    getStateFromFlux = () => this.setState({
        products: this.props.flux.store('ProductStore').getProducts().map(product => ({
            ...product,
            available: this._isAvailable(product),
        })),
    })

    _isAvailable = product => this.props.flux.store('ProductAvailabilityStore').isAvailable(product.id);

    render = () => this.state.products.map(product => (
        <Product available={this._isAvailable(product)} product={product} />
    ))
}
</code>```

However, that means that any time the availability store changes, we re-render (caused by shallow inequality of the derived state). This happens even if the availability of none of our products have changed.

Now I could implement a custom shouldComponentUpdate with something like _.isEqual, however I feel like this isn't the correct way to do this, or an efficient way at that.

Is there a correct way of handling this? One way I can think of would to be store the list of available products in the state, however that moves the isAvailable logic out of the store and into my component, which is something I don't really want to do.
        ))
    }

答:
One posible solution is to move isAvailable logic to your Product component. Something like this:

```<code>class ProductList extends React.PureComponent {
    getStateFromFlux = () => this.setState({
        available: this.props.flux.store('ProductAvailabilityStore').isAvailable(this.props.product.id)
    })
}
</code>```

This way, if availability changes, it will call setState in your Product component only (re-rending itself), instead of rerendering everything.

Title: Storing derived data in the state

Body:
Is it a good idea to store derived data in the state in React? The reason I'm looking to do this is to ensure that re-renders occur when the source data set changes.

One example I have with Flux;

class ProductList extends React.PureComponent {
    componentDidMount = () => {
        this.props.flux.store('ProductStore').on('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').on('change', this.getStateFromFlux);
    }

    componentWillUnmount = () => {
        this.props.flux.store('ProductStore').off('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').off('change', this.getStateFromFlux);
    }

    getStateFromFlux = () => this.setState({ products: this.props.flux.store('ProductStore').getProducts() })

    _isAvailable = product => this.props.flux.store('ProductAvailabilityStore').isAvailable(product.id);

    render = () => this.state.products.map(product => (
        <Product available={this._isAvailable(product)} product={product} />
    ))
}

In this case, product availability changing won't cause a re-render, which is not what I want.

Now I could do something like this;

class ProductList extends React.PureComponent {
    componentDidMount = () => {
        this.props.flux.store('ProductStore').on('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').on('change', this.getStateFromFlux);
    }

    componentWillUnmount = () => {
        this.props.flux.store('ProductStore').off('change', this.getStateFromFlux);
        this.props.flux.store('ProductAvailabilityStore').off('change', this.getStateFromFlux);
    }

    getStateFromFlux = () => this.setState({
        products: this.props.flux.store('ProductStore').getProducts().map(product => ({
            ...product,
            available: this._isAvailable(product),
        })),
    })

    _isAvailable = product => this.props.flux.store('ProductAvailabilityStore').isAvailable(product.id);

    render = () => this.state.products.map(product => (
        <Product available={this._isAvailable(product)} product={product} />
    ))
}

However, that means that any time the availability store changes, we re-render (caused by shallow inequality of the derived state). This happens even if the availability of none of our products have changed.

Now I could implement a custom shouldComponentUpdate with something like _.isEqual, however I feel like this isn't the correct way to do this, or an efficient way at that.

Is there a correct way of handling this? One way I can think of would to be store the list of available products in the state, however that moves the isAvailable logic out of the store and into my component, which is something I don't really want to do.
        ))
    }

Body:
One posible solution is to move isAvailable logic to your Product component. Something like this:

class ProductList extends React.PureComponent {
    getStateFromFlux = () => this.setState({
        available: this.props.flux.store('ProductAvailabilityStore').isAvailable(this.props.product.id)
    })
}

This way, if availability changes, it will call setState in your Product component only (re-rending itself), instead of rerendering everything.


来源: stackexchange

问:
PHP include causes white space at the top of the page
I have a problem on a site that I am making. There is this line of white space at the top of my page. I can not find out where it is coming from. It might be because of extra line breaks in my page thanks to php include() or maybe it is just some faulty css.

答:
BOM Character creates that problem. Sometimes it does not create such visual character that one see. Just check the file editor settings and set to "no BOM" to prevent such blank line.

Sometimes images won't work because of this character, since the character set of image is corrupted by such character.

To avoid such situations,
i). check if your Code Editor creates new file with BOM. If so, change this setting.
ii). Open all the files of your code and check BOM character at start (

ContentLicense: CC BY-SA 3.0


问:
How to set SSRS expression to return previous month?
I want to set parameter's default value using SSRS expression to previous month in a year.

I've tried:

```<code>=CDate(
    DateSerial(
        IIf(DatePart("m", Today())=12, DatePart("yyyy",Today())-1, DatePart("yyyy",Today())),
        IIf(DatePart("m", Today())=12, 1, DatePart("m",Today())-1),
        1
    )
)
</code>```

答:
I think you're over-complicating this, you don't need to check yourself for a change of year - let the built in functions do that for you.

There could be better solutions, but this has always worked for me.

If you just want the first day of the previous month, then:

```<code>=DateSerial(
    Year(
        DateAdd("m", -1, Today())
    ),
    Month(
        DateAdd("m", -1, Today())
    ),
    1
)
</code>```

For my purposes, I also typically need the last day of the previous month, for which I use the following:

```<code>=DateSerial(
    Year(
        DateAdd("m", -1, Today())
    ),
    Month(
        DateAdd("m", -1, Today())
    ),
    Day(
        DateAdd("d", -1, DateSerial(Year(Today()), Month(Today()), 1))
    )
)
</code>```

Body:
I want to set parameter's default value using SSRS expression to previous month in a year.

I've tried:

=CDate(
    DateSerial(
        IIf(DatePart("m", Today())=12, DatePart("yyyy",Today())-1, DatePart("yyyy",Today())),
        IIf(DatePart("m", Today())=12, 1, DatePart("m",Today())-1),
        1
    )
)

Body:
I think you're over-complicating this, you don't need to check yourself for a change of year - let the built in functions do that for you.

There could be better solutions, but this has always worked for me.

If you just want the first day of the previous month, then:

=DateSerial(
    Year(
        DateAdd("m", -1, Today())
    ),
    Month(
        DateAdd("m", -1, Today())
    ),
    1
)

For my purposes, I also typically need the last day of the previous month, for which I use the following:

=DateSerial(
    Year(
        DateAdd("m", -1, Today())
    ),
    Month(
        DateAdd("m", -1, Today())
    ),
    Day(
        DateAdd("d", -1, DateSerial(Year(Today()), Month(Today()), 1))
    )
)


问:
How to transfer basic objects between Ruby and Python?
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:

```<code>IO.popen('./convert.py', 'w') do |w|
    w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json)
    w.write "\n"
    w.close_write
end
</code>```

In this case height, width and job_id are all numbers and pix is an array of arrays of integers.

The python script this is running is:

```<code>#!/usr/bin/env python

from PIL import Image
import json
import sys

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'images/' + str(output['id']) + '/image.bmp'
data = [ tuple(datum) for datum in output['data'] ]

img = Image.new("RGB", (width, height))

img.putdata(data)

img.save(name)
</code>```

A bit of quick testing utilising an array with 3.9 million values (probably around 1/4 of the size that will normally be used) revealed the script to take around 105 seconds, and  90 seconds with all lines below output = ... commented out.  Obviously it would be good if the serialisation didn't take 85% of the processing time for such a simple script.

The only method to speed this up that I can think of is to find some form of binary serialisation/marshalling that could be utilised to transfer the data from Ruby to Python.  Unfortunately I have been unable to find any such system, only RMarshal which appears to be able to work the other way.

答: Maybe MessagePack is the way to go then. Bindings for several languages exist, including Ruby and Python.</p>

ContentLicense: CC BY-SA 2.5

Body:
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:

IO.popen('./convert.py', 'w') do |w|
    w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json)
    w.write "\n"
    w.close_write
end

In this case height, width and job_id are all numbers and pix is an array of arrays of integers.

The python script this is running is:

#!/usr/bin/env python

from PIL import Image
import json
import sys

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'images/' + str(output['id']) + '/image.bmp'
data = [ tuple(datum) for datum in output['data'] ]

img = Image.new("RGB", (width, height))

img.putdata(data)

img.save(name)

A bit of quick testing utilising an array with 3.9 million values (probably around 1/4 of the size that will normally be used) revealed the script to take around 105 seconds, and  90 seconds with all lines below output = ... commented out.  Obviously it would be good if the serialisation didn't take 85% of the processing time for such a simple script.

The only method to speed this up that I can think of is to find some form of binary serialisation/marshalling that could be utilised to transfer the data from Ruby to Python.  Unfortunately I have been unable to find any such system, only RMarshal which appears to be able to work the other way.


问:
React native-fbsdk unknown issue?
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}
</code>```

And here is my android/app/build.gradle

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
</code>```

How can I solve this issue? Any help on this?

答:
Go to android level build gradle and add/update this line.

```<code>subprojects {
   afterEvaluate {project ->
       if (project.hasProperty("android")) {
        android {
            compileSdkVersion 25
            buildToolsVersion '25.0.0'
        }
       }
   }
}
</code>```

to

```<code>subprojects {
afterEvaluate {project ->
    if (project.hasProperty("android")) {
        android {
            compileSdkVersion 26
            buildToolsVersion '26.0.1'
        }
    }
}
</code>```

}

this solve my problem.

Title: React native-fbsdk unknown issue?

Body:
I am using react native 0.49.5 and react 16.0.0-beta.5 for making an App.

I am using react native-fbsdk(^0.6.3) for facebook login. All necessary steps are taken to link android with the facebook sdk.

But When I ran react-native run-android, It threw an error.

Error log in CLI(TERMINAL):

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15:21-54: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

/home/sunny/projects/ReactNativeApp/node_modules/react-native-fbsdk/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:15: error: Error: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

:react-native-fbsdk:processReleaseResources FAILED

FAILURE: Build failed with an exception.

What went wrong:
  Execution failed for task ':react-native-fbsdk:processReleaseResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.015 secs
  Could not install the app on the device, read the error above for details.
  Make sure you have an Android emulator running or a device connected and have
  set up your Android development environment:
  https://facebook.github.io/react-native/docs/android-setup.html

Here is my android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

And here is my android/app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    dexOptions {
        jumboMode true
    }
    defaultConfig {
        applicationId "com.reactnativeapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-fetch-blob')
    compile project(':react-native-camera-kit')
    compile(project(':react-native-fbsdk')){
      exclude(group: 'com.facebook.android', module: 'facebook-android-sdk')
    }
    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile project(':react-native-maps')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-linear-gradient')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

How can I solve this issue? Any help on this?

Body:
Go to android level build gradle and add/update this line.

subprojects {
   afterEvaluate {project ->
       if (project.hasProperty("android")) {
        android {
            compileSdkVersion 25
            buildToolsVersion '25.0.0'
        }
       }
   }
}

to

subprojects {
afterEvaluate {project ->
    if (project.hasProperty("android")) {
        android {
            compileSdkVersion 26
            buildToolsVersion '26.0.1'
        }
    }
}

}

this solve my problem.


问:
Fatal error starting postgres
I'm unfamiliar with how to use postgres and need some help. I'm currently running OSX Yosemite.

When I start postgres I get this:

```<code>pg_ctl: could not start server
Examine the log output.
There was an error executing [start] on postgres. Check /Users/work/git/proj/var/log/postgres.log for details.
createuser: could not connect to database postgres: FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory
</code>```

The log is below.

When I try to stop postgres I get this:

```<code>Postgres not running
</code>```

And when I run ps -ef |grep postgres I get this:

```<code>20010    13398     1  0 Jul07 ?        00:00:00 /usr/pgsql-9.3/bin/postgres -h  -k /Users/work/git/proj/var/pg
20010    13399 13398  0 Jul07 ?        00:00:09 postgres: logger process
20010    13401 13398  0 Jul07 ?        00:00:10 postgres: checkpointer process
20010    13402 13398  0 Jul07 ?        00:00:00 postgres: writer process
20010    13403 13398  0 Jul07 ?        00:00:00 postgres: wal writer process
20010    13404 13398  0 Jul07 ?        00:00:36 postgres: autovacuum launcher process
20010    13405 13398  0 Jul07 ?        00:00:02 postgres: stats collector process
20010    18112 17723  0 10:22 pts/0    00:00:00 grep postgres
</code>```

What does this all mean and how could I possibly fix this?

log text

```<code>Postgres data dir doesn't exist. Creating
The files belonging to this database system will be owned by user "rose.smith".
This user must also own the server process.

The database cluster will be initialized with locale "C".
The default database encoding has accordingly been set to "SQL_ASCII".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /Users/work/git/proj/postgres ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
creating configuration files ... ok
creating template1 database in /Users/work/git/proj/postgres/base/1 ... ok
initializing pg_authid ... ok
initializing dependencies ... ok
creating system views ... ok
loading system objects' descriptions ... ok
creating collations ... ok
creating conversions ... ok
creating dictionaries ... ok
setting privileges on built-in objects ... ok
creating information schema ... ok
loading PL/pgSQL server-side language ... ok
vacuuming database template1 ... ok
copying template1 to template0 ... ok
copying template1 to postgres ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    /usr/pgsql-9.3/bin/postgres -D /Users/work/git/proj/postgres
or
    /usr/pgsql-9.3/bin/pg_ctl -D /Users/work/git/proj/postgres -l logfile start

waiting for server to start....< 2015-06-04 17:24:57.966 GMT >LOG:  redirecting log output to logging collector process
< 2015-06-04 17:24:57.966 GMT >HINT:  Future log output will appear in directory "pg_log".
 done
server started
waiting for server to shut down.... done
server stopped
waiting for server to start....< 2015-06-04 18:10:18.044 GMT >LOG:  redirecting log output to logging collector process
< 2015-06-04 18:10:18.044 GMT >HINT:  Future log output will appear in directory "pg_log".
 done
server started
"/Users/work/git/proj/var/log/postgres.log" 413L, 20935C
</code>```

after running /usr/pgsql-9.3/bin/postgres -D /Users/work/git/proj/postgres

```<code>< 2015-07-08 14:40:36.331 GMT >FATAL:  lock file "postmaster.pid" already exists
< 2015-07-08 14:40:36.331 GMT >HINT:  Is another postmaster (PID 18145) running in data directory "/Users/work/git/proj/postgres"?
</code>```

答:
I faced same issue. I solved the problem with the following commands.

If you install postgresql using HomeBrew...

```<code>rm /usr/local/var/postgres/postmaster.pid

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
</code>```

Hope this helps you!

Title: Fatal error starting postgres

Body:
I'm unfamiliar with how to use postgres and need some help. I'm currently running OSX Yosemite.

When I start postgres I get this:

pg_ctl: could not start server
Examine the log output.
There was an error executing [start] on postgres. Check /Users/work/git/proj/var/log/postgres.log for details.
createuser: could not connect to database postgres: FATAL:  could not open relation mapping file "global/pg_filenode.map": No such file or directory

The log is below.

When I try to stop postgres I get this:

Postgres not running

And when I run ps -ef |grep postgres I get this:

20010    13398     1  0 Jul07 ?        00:00:00 /usr/pgsql-9.3/bin/postgres -h  -k /Users/work/git/proj/var/pg
20010    13399 13398  0 Jul07 ?        00:00:09 postgres: logger process
20010    13401 13398  0 Jul07 ?        00:00:10 postgres: checkpointer process
20010    13402 13398  0 Jul07 ?        00:00:00 postgres: writer process
20010    13403 13398  0 Jul07 ?        00:00:00 postgres: wal writer process
20010    13404 13398  0 Jul07 ?        00:00:36 postgres: autovacuum launcher process
20010    13405 13398  0 Jul07 ?        00:00:02 postgres: stats collector process
20010    18112 17723  0 10:22 pts/0    00:00:00 grep postgres

What does this all mean and how could I possibly fix this?

log text

Postgres data dir doesn't exist. Creating
The files belonging to this database system will be owned by user "rose.smith".
This user must also own the server process.

The database cluster will be initialized with locale "C".
The default database encoding has accordingly been set to "SQL_ASCII".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /Users/work/git/proj/postgres ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
creating configuration files ... ok
creating template1 database in /Users/work/git/proj/postgres/base/1 ... ok
initializing pg_authid ... ok
initializing dependencies ... ok
creating system views ... ok
loading system objects' descriptions ... ok
creating collations ... ok
creating conversions ... ok
creating dictionaries ... ok
setting privileges on built-in objects ... ok
creating information schema ... ok
loading PL/pgSQL server-side language ... ok
vacuuming database template1 ... ok
copying template1 to template0 ... ok
copying template1 to postgres ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    /usr/pgsql-9.3/bin/postgres -D /Users/work/git/proj/postgres
or
    /usr/pgsql-9.3/bin/pg_ctl -D /Users/work/git/proj/postgres -l logfile start

waiting for server to start....< 2015-06-04 17:24:57.966 GMT >LOG:  redirecting log output to logging collector process
< 2015-06-04 17:24:57.966 GMT >HINT:  Future log output will appear in directory "pg_log".
 done
server started
waiting for server to shut down.... done
server stopped
waiting for server to start....< 2015-06-04 18:10:18.044 GMT >LOG:  redirecting log output to logging collector process
< 2015-06-04 18:10:18.044 GMT >HINT:  Future log output will appear in directory "pg_log".
 done
server started
"/Users/work/git/proj/var/log/postgres.log" 413L, 20935C

after running /usr/pgsql-9.3/bin/postgres -D /Users/work/git/proj/postgres

< 2015-07-08 14:40:36.331 GMT >FATAL:  lock file "postmaster.pid" already exists
< 2015-07-08 14:40:36.331 GMT >HINT:  Is another postmaster (PID 18145) running in data directory "/Users/work/git/proj/postgres"?

Body:
I faced same issue. I solved the problem with the following commands.

If you install postgresql using HomeBrew...

rm /usr/local/var/postgres/postmaster.pid

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Hope this helps you!


问:
How to zoom out from Google maps in Android Emulator?
I am testing a map based app on the emulator. I have zoomed into the map by double clicking with the mouse on the screen, but can not zoom out.

Please tell me how to zoom out?

答:
There is a way to zoom out of the emulator screen. After you have zoomed in appropriately and want to zoom out (return to original state), simply click the same zoom button again.

If instead, you want to zoom out in stages like the way you zoomed in, click the right mouse button.

Hope it helps you.


问:
Allow pointer (click) events to pass through element whilst maintaining scroll facility
My goal is to have an element which allows:

elements underneath to be clicked on/interacted with,

scrolling

The solution to 1 is widely known to be pointer-events: none. This is as described in Click through a DIV to underlying elements.

However, the element can not be scrolled, because the scroll bar appears on the element with pointer-events: none. This can be seen in this example: http://jsbin.com/madure/2/edit?html,css,output.

Is there a workaround to this, or is it something that would need to be addressed at the browser level? Perhaps with an additional rule, pointer-events: scrollOnly.

答:
The pointer-events CSS property specifies under what circumstances (if
  any) a particular graphic element can become the target of mouse
  events.

So basically if you make the upper layer insensitive for click it will be so for wheel events too. I suggest on of two things

JavaScript workaround:
Which basically use the fact that:

Note that preventing an element from being the target of mouse events
  by using pointer-events does not necessarily mean that mouse event
  listeners on that element cannot or will not be triggered

 $(function(){
  $("#stage-layer").on("wheel",function(e){
   eo=e.originalEvent;
   s=$("#scrollable")
   switch(eo.deltaMode){
    case 0:   //DOM_DELTA_PIXEL  Chrome
     s.scrollTop(eo.deltaY+s.scrollTop())
     s.scrollLeft(eo.deltaX+s.scrollLeft())
     break;
    case 1:   //DOM_DELTA_LINE  Firefox
     s.scrollTop(15*eo.deltaY+s.scrollTop()) //scroll(e.deltaX, e.deltaY);  Just a random small amount of scrolling
     s.scrollLeft(15*eo.deltaX+s.scrollLeft())
     break;
    case 2:   //DOM_DELTA_PAGE
     s.scrollTop(0.03*eo.deltaY+s.scrollTop())
     s.scrollLeft(0.03*eo.deltaX+s.scrollLeft())
     break;
   }
   e.stopPropagation();
   e.preventDefault()
  })

 })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    position: relative;
    width: 400px;
    height: 400px;
    border: 2px solid black;
}

#stage-layer {
    position: absolute;
    width: 100%;
    box-sizing: border-box;
    height: 100%;
    border: 2px solid yellow;
}

#application-layer {
    position: relative;
    box-sizing: border-box;
    height: 100%;
    border: 2px solid pink;
    pointer-events: none;
}

rect:hover {
    fill: blue;
}

#scrollable {
    overflow: auto;
    color: hotpink;
    height: 100px;
}</code>```

        <svg id="stage-layer">
            <rect width="200" height="200"></rect>
        </svg>

foo1

foo2

foo3

foo4

foo5

foo6

```

A nice tip:

This will not probably yield an immediate solution but it is a good choice for long term web development :

We would like
  to provide finer grained control (than just auto and none) in HTML ...
  if you have any particular things that you would like to be able to do
  with this property, then please add them to the Use Cases section of
  this wiki page (don't worry about keeping it tidy).

Source : pointer-events

Body:
The pointer-events CSS property specifies under what circumstances (if
  any) a particular graphic element can become the target of mouse
  events.

So basically if you make the upper layer insensitive for click it will be so for wheel events too. I suggest on of two things

JavaScript workaround:
Which basically use the fact that:

Note that preventing an element from being the target of mouse events
  by using pointer-events does not necessarily mean that mouse event
  listeners on that element cannot or will not be triggered

 $(function(){
  $("#stage-layer").on("wheel",function(e){
   eo=e.originalEvent;
   s=$("#scrollable")
   switch(eo.deltaMode){
    case 0:   //DOM_DELTA_PIXEL  Chrome
     s.scrollTop(eo.deltaY+s.scrollTop())
     s.scrollLeft(eo.deltaX+s.scrollLeft())
     break;
    case 1:   //DOM_DELTA_LINE  Firefox
     s.scrollTop(15*eo.deltaY+s.scrollTop()) //scroll(e.deltaX, e.deltaY);  Just a random small amount of scrolling
     s.scrollLeft(15*eo.deltaX+s.scrollLeft())
     break;
    case 2:   //DOM_DELTA_PAGE
     s.scrollTop(0.03*eo.deltaY+s.scrollTop())
     s.scrollLeft(0.03*eo.deltaX+s.scrollLeft())
     break;
   }
   e.stopPropagation();
   e.preventDefault()
  })

 })

.container {
    position: relative;
    width: 400px;
    height: 400px;
    border: 2px solid black;
}

#stage-layer {
    position: absolute;
    width: 100%;
    box-sizing: border-box;
    height: 100%;
    border: 2px solid yellow;
}

#application-layer {
    position: relative;
    box-sizing: border-box;
    height: 100%;
    border: 2px solid pink;
    pointer-events: none;
}

rect:hover {
    fill: blue;
}

#scrollable {
    overflow: auto;
    color: hotpink;
    height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <div class="container">
        <svg id="stage-layer">
            <rect width="200" height="200"></rect>
        </svg>
        <div id="application-layer">
            <div id="scrollable">
                <p>foo1</p>
                <p>foo2</p>
                <p>foo3</p>
                <p>foo4</p>
                <p>foo5</p>
                <p>foo6</p>
            </div>
        </div>
    </div>

A nice tip:

This will not probably yield an immediate solution but it is a good choice for long term web development :

We would like
  to provide finer grained control (than just auto and none) in HTML ...
  if you have any particular things that you would like to be able to do
  with this property, then please add them to the Use Cases section of
  this wiki page (don't worry about keeping it tidy).

Source : pointer-events


问:
How to pass a reference to layout guides from VC to custom view
When overriding the main view of a View Controller, what would be a clean way to refer to Layout Guides inside that view class?

Create a custom initializer for that view, that would take the guides as parameters?

答:
I would say delegate procedure would be the best here.

You avoid custom constructors which then enables you to use view in storyboard. Also by using delegate the values may change on your view controller and your view should still respect that and call for them only when needed.

To take a step forward I believe you could actually make that an outlet by doing something like:

```<code>@IBOutlet weak var ownerController: UIViewController?
</code>```

So you could actually drag the view to its view controller in interface builder and assign the value to it.

But do make sure that the property is weak.

Body:
I would say delegate procedure would be the best here.

You avoid custom constructors which then enables you to use view in storyboard. Also by using delegate the values may change on your view controller and your view should still respect that and call for them only when needed.

To take a step forward I believe you could actually make that an outlet by doing something like:

@IBOutlet weak var ownerController: UIViewController?

So you could actually drag the view to its view controller in interface builder and assign the value to it.

But do make sure that the property is weak.


问:
Instant app not running on emulator
I have One instant app project, which after few hurdles I was able to run on the emulator (Nexus 5X API 26)

Android: Instant app showing just white screen

Now, after 2 months I am trying to run the same project but its not working out

Nexus 5X(Any api):

Adb devices give the following result

emulator-5554   unauthorized

Pixel APi 24 :

Side loading failed with message: Failure when trying to read bundle.Unable to connect to Google Play services.

 ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}

Physical Device's :

Provision failed with message: The device used is not whitelisted for Instant Apps deployment.

As per doc's Instant apps work on

Most Android devices running Android 5.1 (API level 21) or higher.

Devices that I have tried on

Mi Redmi Note 3(marshmallow)

Moto G4 plus (Nougat)

Android studio version 3

How can it be made to work?

答:
Pixel API 24 emulator:

You need to install an Android system image that have Google APIs. You can see those images while creating new emulator, they have a name like: "Android 7.1.1 (Google APIs)".

Make sure you have the latest version of Google Play Services in your emulator. To do that: go to emulator's extended controls (by clicking three dots) -> Google Play -> Update. Note that this only visible if you install a system image with Google APIs (see step 1.)

Make sure you enabled Instant Apps on your device/emulator. See: https://support.google.com/googleplay/answer/7240211?hl=en

Physical Device:

Only few selected devices (such as Pixel) are compatible with Instant Apps development.

See: https://github.com/googlesamples/android-instant-apps/issues/1

See the developer documents about setting up device or emulator for Instant Apps development.

Title: Instant app not running on emulator


问:
Prepend file location at start of file in WebStorm || Ang CLI
I've grown used to the format of having the file source as the 1st line in every file, but I'm curious if there is a way to automate this.

I found the Templates section within WebStorm, but it doesn't have a ${PATH} variable. https://www.jetbrains.com/help/webstorm/file-template-variables.html

I looked into it a bit for Ang CLI but it seems like I would have to clone it and modify it myself which seems wrong.

Essentially I'd love for any file generated via ng g c component to output the first line of the file as

etc, with a dynamic path.

Is this possible, or will I have to continue doing it manually, or writing a script to handle it after-the-fact?

答:
Indeed, there are no predefined variables for file path, see IDEA-136387. Please vote for this request in order to move it up in the queue and receive notifications regarding the progress with it. See more information on this at https://intellij-support.jetbrains.com/hc/en-us/articles/207241135.
But modifying WebStorm file templates won't affect ng generate anyway...
According to https://github.com/angular/angular-cli/issues/2377, the most recent cli version already supports custom blueprints for code generation; didn't try it though


问:
Generating cXML classes from xsd throws error "The element 'uri:ds:Signature' is missing."
I'm trying to generate cXML classes for version cXML 1.2.034 as per http://cxml.org/ XSD (converted by visual studio).

I converted the cXML.dtd to xsd. Then Tried running:

xsd.exe cXML.xsd /c /language:CS /n:MyNamespace

But it threw an error:

Error: Error generating classes for schema 'cXML'.
  - The element 'uri:ds:Signature' is missing.

Then I found this issue here: Generating C# classes from XSD which seems relevant. So I downloaded xmldsig-core-schema.xsd from http://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd

Then I ran

xsd.exe cXML.xsd xmldsig-core-schema.xsd /c /language:CS /n:MyNamespace

But that threw

Error: Error generating classes for schema 'cXML_xmldsig-core-schema'.
  - The element 'uri:ds:Signature' is missing.

I'm lost as to what "'uri:ds:Signature'" is supposed to be?

I can see that

<xs:schema xmlns="http://tempuri.org/cXML" xmlns:ds="uri:ds" elementFormDefault="qualified" targetNamespace="http://tempuri.org/cXML" xmlns:xs="http://www.w3.org/2001/XMLSchema">

seems wrong. I changed it to xmlns:ds="http://www.w3.org/2000/09/xmldsig#" but same issue persists.

I also tried adding reference to local signature xsd by adding

<xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema.xsd"/> and yes I have the file in the same directory as my own xsd file.

答:
I had the same problem.  I tried several attemps like you  (import the https://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd schema, but did find how).

In my case, I just remove the whole line that was problematic :

```<code><!-- COMMENTED <xs:element minOccurs="0" maxOccurs="unbounded" ref="ds:Signature" /> -->
</code>```

and it then work perfectly.

Body:
I had the same problem.  I tried several attemps like you  (import the https://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd schema, but did find how).

In my case, I just remove the whole line that was problematic :

<!-- COMMENTED <xs:element minOccurs="0" maxOccurs="unbounded" ref="ds:Signature" /> -->

and it then work perfectly.


问:
html table with javascript sp
Basically, I am a beginner who recently started working with Javascript and I want to simplify my code. How can I simplify this? How would I apply a loop because it is too long to declare it by a single code if I want to change the id. Not manually changing in the html, but using a Javascript to change the value in html?

```<code><table border="2" cellpadding="4">
    <tbody>
        <tr>
            <td id="cell1"> one </td>
            <td id="cell2"> two </td>
            <td id="cell3"> three </td>
        </tr>
        <tr>
            <td id="cell4"> four </td>
            <td id="cell5"> five </td>
            <td id="cell6"> six </td>
        </tr>
    </tbody>
</table>

document.getElementById("cell1").innerHTML="1";
document.getElementById("cell2").innerHTML="2";
document.getElementById("cell3").innerHTML="3";
document.getElementById("cell4").innerHTML="4";
document.getElementById("cell5").innerHTML="5";
document.getElementById("cell6").innerHTML="6";
</code>```

答:
i hope that help you and you can start learn javascript on this site https://www.w3schools.com/js/ is very useful:</p>

```<code>var d = document;
var trs = d.getElementsByTagName("tr");
console.log(trs);
var count = 1;
for(var i=0 ; i<trs.length ; i++){
    tds = trs[i].getElementsByTagName("td");
    for(var j=0 ; j<tds.length ; j++){
        tds[j].innerHTML = count;
      count++;
    }
    console.log(trs[i]);
}
</code>```

Title: html table with javascript sp

Body:
Basically, I am a beginner who recently started working with Javascript and I want to simplify my code. How can I simplify this? How would I apply a loop because it is too long to declare it by a single code if I want to change the id. Not manually changing in the html, but using a Javascript to change the value in html?

             one
             two
             three

             four
             five
             six

document.getElementById("cell1").innerHTML="1";
document.getElementById("cell2").innerHTML="2";
document.getElementById("cell3").innerHTML="3";
document.getElementById("cell4").innerHTML="4";
document.getElementById("cell5").innerHTML="5";
document.getElementById("cell6").innerHTML="6";

Body:
i hope that help you and you can start learn javascript on this site https://www.w3schools.com/js/ is very useful:

var d = document;
var trs = d.getElementsByTagName("tr");
console.log(trs);
var count = 1;
for(var i=0 ; i<trs.length ; i++){
    tds = trs[i].getElementsByTagName("td");
    for(var j=0 ; j<tds.length ; j++){
        tds[j].innerHTML = count;
      count++;
    }
    console.log(trs[i]);
}


问:
Generating a Microsoft Word file in PHP
I am able to generate a Microsoft word file, but I want the data in table structure. I have used an HTML table tag in PHP, but the output does not look satisfactory. In the table are a lot of cellspacing and cellpadding even if I have initialize them to zero space. Any idea how can I solve this?

here goes my code

```<code>    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment;Filename=document_name.doc");
    $now_date = date('d-m-Y H:i');
    echo "<html>";
    echo "<body>";
    echo "</body>";
    echo "<head>";
    echo "<div>Seminarthema:</div>\n";
    echo "<div>Termin:$now_date</div>";
    echo "<br></br>";
    echo "<div style='size:20px;'><h2>Teilnehmerliste</h2></div>";
    echo "<table border='1' cellpadding='0' cellspacing='0'>
            <tr><th>Name</th><th>Vorname</th><th>Buchungskreis</th><th>Kurs-ID</th><th>Teilgenommen</th></tr>";
    $students = $GLOBALS["TYPO3_DB"]->exec_SELECTquery('*','tx_training_Registration','hidden=0 AND deleted=0');
    $countstud = $GLOBALS['TYPO3_DB']->sql_num_rows($students);
    if($countstud){
        while($row2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($students)){
            echo "<tr>";
                echo "<td>".utf8_decode($row2['firstname'])."</td>";
                echo "<td>".utf8_decode($row2['lastname'])."</td>";
                echo "<td>".utf8_decode($row2['companycode'])."</td>";
                echo "<td>".utf8_decode($row2['trainingid'])."</td>";
                echo "<td>".utf8_decode($row2[' status'])."</td>";
            echo "</tr>";
        }
    }
    echo  "</table>";
    echo "</head>";
    echo "</html>";
</code>```

答: Why not consider creating a "real" Word document rather than a "make-believe that HTML is actually Word" file. Take a look at PHPWord.</p>

Title: Generating a Microsoft Word file in PHP

Body:
I am able to generate a Microsoft word file, but I want the data in table structure. I have used an HTML table tag in PHP, but the output does not look satisfactory. In the table are a lot of cellspacing and cellpadding even if I have initialize them to zero space. Any idea how can I solve this?

here goes my code

    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment;Filename=document_name.doc");
    $now_date = date('d-m-Y H:i');
    echo "";
    echo "";
    echo "";
    echo "";
    echo "
Seminarthema:
\n";
    echo "
Termin:$now_date
";
    echo "

";
    echo "

Teilnehmerliste

";
    echo "

Name	Vorname	Buchungskreis	Kurs-ID	Teilgenommen
";
    $students = $GLOBALS["TYPO3_DB"]->exec_SELECTquery('*','tx_training_Registration','hidden=0 AND deleted=0');
    $countstud = $GLOBALS['TYPO3_DB']->sql_num_rows($students);
    if($countstud){
        while($row2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($students)){
            echo "
";
                echo "".utf8_decode($row2['firstname'])."	";
                echo "".utf8_decode($row2['lastname'])."	";
                echo "".utf8_decode($row2['companycode'])."	";
                echo "".utf8_decode($row2['trainingid'])."	";
                echo "".utf8_decode($row2[' status'])."	";
            echo "
";
        }
    }
    echo  "
";
    echo "";
    echo "";


问:
Variable "user" does not exist
Can someone help me please I had this error Variable "user" does not exist when I want to display the list of my friends added (todo)

listeami.html.twig
 (relation many to many between user and todo)

```<code>{% if not user.todos.empty %}

{% for todo in user.todos %}
  {{ todos.age }}{% if not loop.last %}, {% endif %}
{% endfor %}${% endif %}
</code>```

Controller:todoController.php
 (page to display list):

```<code>  /**
    * @Route("/todo/listeami", name="todo_listeami")
    */

     public function listeamiAction(Request $request)
     {
         $todos = $this->getDoctrine()
         ->getRepository('AppBundle:Todo')
         ->findAll();

         return $this->render('todo/listeami.html.twig',array('todos'=>$todos));

     }
</code>```

Controller edit:

```<code>  ` **/**
         * @Route("/todo/editmany/{id}", name="todo_editmany")
         */**

    public function editmanyAction($id, Request $request)
        {
          $em = $this->getDoctrine()->getManager();

          // On récupère l'annonce $id
          $user = $em->getRepository('AppBundle:User')->find($id);

          if (null === $user) {
            throw new NotFoundHttpException("L'user d'id ".$id." n'existe pas.");
          }

          // La méthode findAll retourne toutes les catégories de la base de données
          $listTodos = $em->getRepository('AppBundle:Todo')->findAll();

          // On boucle sur les catégories pour les lier à l'annonce
          foreach ($listTodos as $todo) {
            $user->addCategory($todo);
          }

          // Pour persister le changement dans la relation, il faut persister l'entité propriétaire
          // Ici, Advert est le propriétaire, donc inutile de la persister car on l'a récupérée depuis Doctrine

          // Étape 2 : On déclenche l'enregistrement
          $em->flush();

          // … reste de la méthode
        }
    `
</code>```

this page for DATA fixtures:

```<code><?php
// src/OC/PlatformBundle/DataFixtures/ORM/LoadCategory.php

namespace AppBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\Fixture;

use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\Todo;

class LoadTodo extends Fixture
{
  // Dans l'argument de la méthode load, l'objet $manager est l'EntityManager
  public function load(ObjectManager $manager)
  {
    // Liste des noms de catégorie à ajouter
    $ages = array(
      'un mois',
      'deux jours',
      'quatre jours',
      'trois heures',
      'un jour'
    );

    foreach ($ages as $age) {
      // On crée la catégorie
      $todo = new Todo();
      $todo->setAge($age);
      $todo->setNourriture('Omnivore');
      $todo->setRace('Race');
      $todo->setFamille('Famille');
      $todo->setEmail($age."@gmail.com");
      // On la persiste
      $manager->persist($todo);
    }

    // On déclenche l'enregistrement de toutes les catégories
    $manager->flush();
  }
}
</code>```

thanks in adavance

答:
You are not passing the user variable from listeamiAction action you should fix the problem this way

Option #1: Passing the variable to your view

```<code>public function listeamiAction(Request $request)
     {
</code>```

$user = $this->getUser();

```<code>         return $this->render('todo/listeami.html.twig',array('user'=>$user));

     }
</code>```

Option #2: Access to the user env variable(i think this is what you are trying to do)

```<code>  {% for todo in app.user.todos %}
      {{ todo.age }}{% if not loop.last %}, {% endif %}
    {% endfor %}${% endif %}
</code>```

With the app.user you can access to your UserInterface declared. It's important that the getTodos() is an accesible function in the User class.

Option #3: use the todo variables passed to the view(todos)

```<code>{% if not todos.empty %}

{% for todo in todos %}
  {{ todo.age }}{% if not loop.last %}, {% endif %}
{% endfor %}${% endif %}
</code>```

Hope it helps!!

Title: Variable "user" does not exist

Body:
Can someone help me please I had this error Variable "user" does not exist when I want to display the list of my friends added (todo)

listeami.html.twig
 (relation many to many between user and todo)

{% if not user.todos.empty %}

{% for todo in user.todos %}
  {{ todos.age }}{% if not loop.last %}, {% endif %}
{% endfor %}${% endif %}

Controller:todoController.php
 (page to display list):

  /**
    * @Route("/todo/listeami", name="todo_listeami")
    */

     public function listeamiAction(Request $request)
     {
         $todos = $this->getDoctrine()
         ->getRepository('AppBundle:Todo')
         ->findAll();

         return $this->render('todo/listeami.html.twig',array('todos'=>$todos));

     }

Controller edit:

  ` **/**
         * @Route("/todo/editmany/{id}", name="todo_editmany")
         */**

    public function editmanyAction($id, Request $request)
        {
          $em = $this->getDoctrine()->getManager();

          // On récupère l'annonce $id
          $user = $em->getRepository('AppBundle:User')->find($id);

          if (null === $user) {
            throw new NotFoundHttpException("L'user d'id ".$id." n'existe pas.");
          }

          // La méthode findAll retourne toutes les catégories de la base de données
          $listTodos = $em->getRepository('AppBundle:Todo')->findAll();

          // On boucle sur les catégories pour les lier à l'annonce
          foreach ($listTodos as $todo) {
            $user->addCategory($todo);
          }

          // Pour persister le changement dans la relation, il faut persister l'entité propriétaire
          // Ici, Advert est le propriétaire, donc inutile de la persister car on l'a récupérée depuis Doctrine

          // Étape 2 : On déclenche l'enregistrement
          $em->flush();

          // … reste de la méthode
        }
    `

this page for DATA fixtures:

<?php
// src/OC/PlatformBundle/DataFixtures/ORM/LoadCategory.php

namespace AppBundle\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\Fixture;

use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\Todo;

class LoadTodo extends Fixture
{
  // Dans l'argument de la méthode load, l'objet $manager est l'EntityManager
  public function load(ObjectManager $manager)
  {
    // Liste des noms de catégorie à ajouter
    $ages = array(
      'un mois',
      'deux jours',
      'quatre jours',
      'trois heures',
      'un jour'
    );

    foreach ($ages as $age) {
      // On crée la catégorie
      $todo = new Todo();
      $todo->setAge($age);
      $todo->setNourriture('Omnivore');
      $todo->setRace('Race');
      $todo->setFamille('Famille');
      $todo->setEmail($age."@gmail.com");
      // On la persiste
      $manager->persist($todo);
    }

    // On déclenche l'enregistrement de toutes les catégories
    $manager->flush();
  }
}

thanks in adavance

Body:
You are not passing the user variable from listeamiAction action you should fix the problem this way

Option #1: Passing the variable to your view

public function listeamiAction(Request $request)
     {

$user = $this->getUser();

         return $this->render('todo/listeami.html.twig',array('user'=>$user));

     }

Option #2: Access to the user env variable(i think this is what you are trying to do)

  {% for todo in app.user.todos %}
      {{ todo.age }}{% if not loop.last %}, {% endif %}
    {% endfor %}${% endif %}

With the app.user you can access to your UserInterface declared. It's important that the getTodos() is an accesible function in the User class.

Option #3: use the todo variables passed to the view(todos)

{% if not todos.empty %}

{% for todo in todos %}
  {{ todo.age }}{% if not loop.last %}, {% endif %}
{% endfor %}${% endif %}

Hope it helps!!


问:
Xpath extract all the text between multiple nodes?
I'm scraping an e-commerce web site using the Python requests modul.
Well I have some problem on extracting the text between multiple nodes. The following html is the part where I'm trying to extract the text. I need to extract all the text under the (div class="rte ingredients") embedded into the two (p) tags and all the (strong) tags. Pay attention! The (strong) tags can vary from page to page.

```<code><div class="rte ingredients">
    <p>Farina sbiancata arricchita (farina sbiancata di
    <strong>grano</strong>,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    <strong>latte</strong>
    scremato disidratato, olio di
    <strong>soia</strong> parzialmente
    idrogenato, sale,
    <strong>glutine</strong> di <strong>grano</strong>,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (<strong>latte</strong>), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di <strong>uova</strong>. Contiene OGM.</p>

    <p>Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.</p>
</div>
</code>```

Well, I'm using the following code but the result I get is partial.

```<code>ingredients = parser.xpath('//*[@id="bottom_right_product_infos"]/section[2]/div/p[1]/text()')
print ingredients
['Farina sbiancata arricchita (farina sbiancata di']
</code>```

Conversely I need to extract all the text under the (DIV) tag.

Can somebody help me on this? Thanks!

答:
The pure XML/XPath solution would be to change the XPath to directly select the string value of the targeted div:

```<code>string(/path/to/div)
</code>```

This way, your XPath should be portable to any conformant XPath library (and you can minimize your need to remember non-standard, idiosyncratic access functions such as text_content()).

Body:
I'm scraping an e-commerce web site using the Python requests modul.
Well I have some problem on extracting the text between multiple nodes. The following html is the part where I'm trying to extract the text. I need to extract all the text under the (div class="rte ingredients") embedded into the two (p) tags and all the (strong) tags. Pay attention! The (strong) tags can vary from page to page.

Farina sbiancata arricchita (farina sbiancata di
    grano,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    latte
    scremato disidratato, olio di
    soia parzialmente
    idrogenato, sale,
    glutine di grano,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (latte), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di uova. Contiene OGM.

Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.

Well, I'm using the following code but the result I get is partial.

ingredients = parser.xpath('//*[@id="bottom_right_product_infos"]/section[2]/div/p[1]/text()')
print ingredients
['Farina sbiancata arricchita (farina sbiancata di']

Conversely I need to extract all the text under the (DIV) tag.

Can somebody help me on this? Thanks!

Body:
The pure XML/XPath solution would be to change the XPath to directly select the string value of the targeted div:

string(/path/to/div)

This way, your XPath should be portable to any conformant XPath library (and you can minimize your need to remember non-standard, idiosyncratic access functions such as text_content()).


问:
Spring Controller double validation for @ModelAttribute object
I have implemented controller with method:

```<code>public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}
</code>```

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

```<code>@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}
</code>```

答:
Edited:

If you want both custom and default validation you can use addValidators in
initBinder to add your custom validations. This way default validations will not be deleted.

```<code>@Controller
public class MyController
{
    @Autowired
    private EventsCriteriaValidator validator;

    @InitBinder
    protected void initBinder(final WebDataBinder binder)
    {
         binder.addValidators(validator);
    }

  public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria   criteria, BindingResult result){

     if (result.hasErrors()) {
        // validation failed

     } else {
        //validation passed
     }
  }

}
</code>```

Body:
I have implemented controller with method:

public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria criteria){...}

It works. EventsCriteria did not have special separate validator for itself, because it has inner annotation checkers like @NotNull @NotEmpty. Right now situation is changed and it's not enough to have only this validators. so I've added and registered correspond service to verify some sates.

I want service to verify additional composite cases and single validation like before. But my single inner annotation checkers like @NotNull @NotEmpty do not work any more.

Am I configured something incorrectly or it can't work in in same time(specified service and inner checkers)?

My validator example (as it was asked in comments)

There are nothing special, if you know spring, so I missed this part like unimportant to concentrate your attention on my question.

@Component
public class EventsCriteriaValidator implements Validator {

    public static final String INVALID_RAGE_PARAMETERS_SPECIFIED = "Invalid rage parameters: please specify " +
            "'from' and 'to' or page 'size";

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(EventsCriteria.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EventsCriteria toValidate = (EventsCriteria) target;
        validateComplexRestriction(toValidate, errors);
    }

    private void validateComplexRestriction(EventsCriteria toValidate, Errors errors) {
        if (toValidate.isRangeEmpty() && toValidate.getSize() == 0) {
            errors.rejectValue(SIZE_FIELD, null, INVALID_RAGE_PARAMETERS_SPECIFIED);
        }
    }

}

Body:
Edited:

If you want both custom and default validation you can use addValidators in
initBinder to add your custom validations. This way default validations will not be deleted.

@Controller
public class MyController
{
    @Autowired
    private EventsCriteriaValidator validator;

    @InitBinder
    protected void initBinder(final WebDataBinder binder)
    {
         binder.addValidators(validator);
    }

  public Page<EventDto> search(@ModelAttribute @Valid EventsCriteria   criteria, BindingResult result){

     if (result.hasErrors()) {
        // validation failed

     } else {
        //validation passed
     }
  }

}


问:
Redirect a route group to a single page in laravel
what is the shortest and easy way to redirect a set of routes belonging to same route group to redirect to a common page? Like i list all the routes inside a route group and then inside the route group declaration redirect code is written.</p>

答:
Put this inside the route group and it should work,

```<code>Route::any('{any?}', function ($any = null) {
        return Redirect::to('your_route', 301);
})->where('any', '.*');
</code>```

Body:
Put this inside the route group and it should work,

Route::any('{any?}', function ($any = null) {
        return Redirect::to('your_route', 301);
})->where('any', '.*');


问:
how to remove inner brackets from arraylist object in javascript
I just want remove one extra brackets from below arrayList:

```<code>[
{
"small":"https://www.googleapis.com/photo.png?",
"medium":"https://www.googleapis.com/photo.png?",
"big":"https://www.googleapis.com/photo.png?"
},
[
{
"small":"https://www.googleapis.com/Jenner.jfif?",
"medium":"https://www.googleapis.com/Jenner.jfif?",
"big":"https://www.googleapis.com/Jenner.jfif?"
}
]
]

to

[
{
"small":"https://www.googleapis.com/photo.png?",
"medium":"https://www.googleapis.com/photo.png?",
"big":"https://www.googleapis.com/photo.png?"
},
{
"small":"https://www.googleapis.com/Jenner.jfif?",
"medium":"https://www.googleapis.com/Jenner.jfif?",
"big":"https://www.googleapis.com/Jenner.jfif?"
}
]
</code>```

please help me to solve this.....thanks

................................................

答:
Something like this?

It takes your original array and maps each element to a new array. If an original element is an array(it has the 'extra brackets'), then instead of copying the value across, it copies the first element of that array only, effectively 'removing the brackets'. I assume that is what you are looking for.

var a = [
    {
        "small": "https://www.googleapis.com/photo.png?",
        "medium": "https://www.googleapis.com/photo.png?",
        "big": "https://www.googleapis.com/photo.png?"
    },
    [
        {
            "small": "https://www.googleapis.com/Jenner.jfif?",
            "medium": "https://www.googleapis.com/Jenner.jfif?",
            "big": "https://www.googleapis.com/Jenner.jfif?"
        }
    ]
];

a = a.map(elem => {
    if (elem.constructor === Array) {
        return elem[0];
    } else {
        return elem;
    }
});

console.log(a);```

Body:
I just want remove one extra brackets from below arrayList:

[
{
"small":"https://www.googleapis.com/photo.png?",
"medium":"https://www.googleapis.com/photo.png?",
"big":"https://www.googleapis.com/photo.png?"
},
[
{
"small":"https://www.googleapis.com/Jenner.jfif?",
"medium":"https://www.googleapis.com/Jenner.jfif?",
"big":"https://www.googleapis.com/Jenner.jfif?"
}
]
]

to

[
{
"small":"https://www.googleapis.com/photo.png?",
"medium":"https://www.googleapis.com/photo.png?",
"big":"https://www.googleapis.com/photo.png?"
},
{
"small":"https://www.googleapis.com/Jenner.jfif?",
"medium":"https://www.googleapis.com/Jenner.jfif?",
"big":"https://www.googleapis.com/Jenner.jfif?"
}
]

please help me to solve this.....thanks

................................................


问:
How to do inclusion of schema in other schema using Z language
I am writing a formal specification for my model using z-notation of Z-language. I am stuck and don't know how to include one schema in another schema and creates its variables in other schemas. Any guidance and help would be appreciated.
Thanks.</p>

答:
Like this</p>

```<code>--- Agent---
| state: AgentState
-------

--- Shape ---
| agents :F Agent
----
| ∃ agt:agents · agt.state = stationary
 -------
</code>```

Body:
Like this

--- Agent---
| state: AgentState
-------

--- Shape ---
| agents :F Agent
----
| ∃ agt:agents · agt.state = stationary
 -------


问:
R ODBC - Querying Column name with spaces
I am trying to query through R OBDC. But one Column name has space on it. For example, [Account No].

I am using this code to query:

```<code>esiid_ac <- sqlQuery(myconn, paste("
 SELECT * FROM CustomerUsage WHERE ((CustomerUsage.Account No ='", 12345, "')) ", sep=""),as.is=TRUE)
</code>```

I am getting the following error:

[1] "42000 102 [Microsoft][ODBC Driver 11 for SQL Server][SQL
  Server]Incorrect syntax near 'No'."                           [2]
  "[RODBC] ERROR: Could not SQLExecDirect '\n SELECT * FROM
  CustomerUsage WHERE ((CustomerUsage.Account No ='678987')) '

How to solve this?

Can I read this table with column index instead of column names?

Thank you.

答:
After tinkering around with quotes a little bit, this worked for me:</p>

```<code>df <- sqlQuery(myconn, 'SELECT * FROM mytable WHERE "column name" =123', as.is=TRUE)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to query through R OBDC. But one Column name has space on it. For example, [Account No].

I am using this code to query:

esiid_ac <- sqlQuery(myconn, paste("
 SELECT * FROM CustomerUsage WHERE ((CustomerUsage.Account No ='", 12345, "')) ", sep=""),as.is=TRUE)

I am getting the following error:

[1] "42000 102 [Microsoft][ODBC Driver 11 for SQL Server][SQL
  Server]Incorrect syntax near 'No'."                           [2]
  "[RODBC] ERROR: Could not SQLExecDirect '\n SELECT * FROM
  CustomerUsage WHERE ((CustomerUsage.Account No ='678987')) '

How to solve this?

Can I read this table with column index instead of column names?

Thank you.

Body:
After tinkering around with quotes a little bit, this worked for me:

df <- sqlQuery(myconn, 'SELECT * FROM mytable WHERE "column name" =123', as.is=TRUE)


问:
Speeding up sklearn logistic regression
I have a model I'm trying to build using LogisticRegression in sklearn that has a couple thousand features and approximately 60,000 samples.  I'm trying to fit the model and it's been running for about 10 mins now.  The machine I'm running it on has gigabytes of RAM and several cores at its disposal and I was wondering if there is any way to speed the process up

EDIT
The machine has 24 cores and here is the output of top to give an idea of memory

```<code>Processes: 94 total, 8 running, 3 stuck, 83 sleeping, 583 threads      20:10:19
Load Avg: 1.49, 1.25, 1.19  CPU usage: 4.34% user, 0.68% sys, 94.96% idle
SharedLibs: 1552K resident, 0B data, 0B linkedit.
MemRegions: 51959 total, 53G resident, 46M private, 676M shared.
PhysMem: 3804M wired, 57G active, 1042M inactive, 62G used, 34G free.
VM: 350G vsize, 1092M framework vsize, 52556024(0) pageins, 85585722(0) pageouts
Networks: packets: 172806918/25G in, 27748484/7668M out.
Disks: 14763149/306G read, 26390627/1017G written.
</code>```

I'm trying to train the model with the following

```<code>classifier = LogisticRegression(C=1.0, class_weight = 'auto')
classifier.fit(train, response)
</code>```

train has rows that are approximately 3000 long (all floating point) and each row in  response is either 0 or 1.  I have approximately 50,000 observations

答:
The default solver for LogisticRegressin in sklearn is liblinear which is a suitable solver for normal datasets. For large datasets try the stochastic gradient descent solvers such as sag:

```<code>model = LogisticRegression(solver='sag')
</code>```

Title: Speeding up sklearn logistic regression

Body:
I have a model I'm trying to build using LogisticRegression in sklearn that has a couple thousand features and approximately 60,000 samples.  I'm trying to fit the model and it's been running for about 10 mins now.  The machine I'm running it on has gigabytes of RAM and several cores at its disposal and I was wondering if there is any way to speed the process up

EDIT
The machine has 24 cores and here is the output of top to give an idea of memory

Processes: 94 total, 8 running, 3 stuck, 83 sleeping, 583 threads      20:10:19
Load Avg: 1.49, 1.25, 1.19  CPU usage: 4.34% user, 0.68% sys, 94.96% idle
SharedLibs: 1552K resident, 0B data, 0B linkedit.
MemRegions: 51959 total, 53G resident, 46M private, 676M shared.
PhysMem: 3804M wired, 57G active, 1042M inactive, 62G used, 34G free.
VM: 350G vsize, 1092M framework vsize, 52556024(0) pageins, 85585722(0) pageouts
Networks: packets: 172806918/25G in, 27748484/7668M out.
Disks: 14763149/306G read, 26390627/1017G written.

I'm trying to train the model with the following

classifier = LogisticRegression(C=1.0, class_weight = 'auto')
classifier.fit(train, response)

train has rows that are approximately 3000 long (all floating point) and each row in  response is either 0 or 1.  I have approximately 50,000 observations

Body:
The default solver for LogisticRegressin in sklearn is liblinear which is a suitable solver for normal datasets. For large datasets try the stochastic gradient descent solvers such as sag:

model = LogisticRegression(solver='sag')


问:
How to embed a picture (jpg/png/etc,) into html and email it out with mail
Background: I am trying to my emails html based, as it is more versatile (I am new to html). I have been playing around with html for a few hours. I can so far embed tables, and different headings and links etc. into the emails that I send out, but have massive difficulty with embedding pictures.

I thought it might a client specific problem - but Hotmail, Outlook and G-mail all don't show the attached image. All I see is the the box with the alt (alternative) text.

```<code>#!/bin/bash
h_test=mytest.html

echo "This is a test email"> TESTEMAILTESTEMAILTESTEMAIL.txt

echo "<html>
<head>
<title>HTML E-mail</title>
</head>
<body>

<p><b>Note:</b> This is just a test email.</p>
<p>Trying to do different things all in one email.</p>

<h2>Table 1</h2>
<table style="width:25%">
  <tr>
    <td>New York</td>
    <td>UNITED STATE OF AMERICA</td>
  </tr>
  <tr>
    <td>Sydney</td>
    <td>AUSTRALIA</td>
  </tr>
  <tr>
    <td>Istanbul</td>
    <td>TURKEY</td>
  </tr>
</table>

<h2>Table 2</h2>
<table border="1"; style="width:50%">
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

<h2>Image 1</h2>
<img src='https://www.google.com.au/search?q=image+test&espv=2&biw=1366&bih=663&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMI1_fn1MrNyAIVITamCh32cQej#imgrc=driDe9TNSAxoAM%3A' alt='You should be seeing a picture'>

<h2>Link</h2>

<a href='http://www.google.com'>Click Here</a>
</body>
</html>" > $h_test

echo ">> Sending email..."

`mail -s "$(echo -e "This is Subject\nContent-Type: text/html")" my_email@me.com  <  mytest.html`

echo "...e-mail sent"
</code>```

Research: I have looked at websites such as this site, but didn't work. I have also looked up similiar questions on stackexchange but couldn't make it work.

Q: How can I embed pictures into my emails?

答:
You are using the URL https://www.google.com.au/search?q=image+test&espv=2&biw=1366&bih=663&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMI1_fn1MrNyAIVITamCh32cQej#imgrc=driDe9TNSAxoAM%3A which is the URL to an HTML document.

You need to use the URL to an image!

Note that most email clients will prompt users before displaying images on external URLs.

You can avoid this by attaching the image (i.e. sending a multipart MIME email) and then using the cid: URL scheme to point to the attachment.

Alternatively, you can convert the image to a data: URL scheme and embed it directly in the URL.

Body:
Background: I am trying to my emails html based, as it is more versatile (I am new to html). I have been playing around with html for a few hours. I can so far embed tables, and different headings and links etc. into the emails that I send out, but have massive difficulty with embedding pictures.

I thought it might a client specific problem - but Hotmail, Outlook and G-mail all don't show the attached image. All I see is the the box with the alt (alternative) text.

#!/bin/bash
h_test=mytest.html

echo "This is a test email"> TESTEMAILTESTEMAILTESTEMAIL.txt

echo "

<title>HTML E-mail</title>

Note: This is just a test email.

Trying to do different things all in one email.

Table 1

    New York
    UNITED STATE OF AMERICA

    Sydney
    AUSTRALIA

    Istanbul
    TURKEY

Table 2

    Month
    Savings

    January
    $100

    February
    $80

Image 1

Link

Click Here

" > $h_test

echo ">> Sending email..."

`mail -s "$(echo -e "This is Subject\nContent-Type: text/html")" my_email@me.com  <  mytest.html`

echo "...e-mail sent"

Research: I have looked at websites such as this site, but didn't work. I have also looked up similiar questions on stackexchange but couldn't make it work.

Q: How can I embed pictures into my emails?


问:
Google Tag Manager & Oracle APEX : Track close dialog
I've implemented Google Analytics in a ORACLE APEX application.
I would like to know how to track the event 'closing a modal dialog / press close button' in Google Analytics.

I've tried the following with Google Tag Manager:

Tag

I've created a tag, as an event type. Which contains a trigger which will trigger the tag when the clicked element matches .ui-dialog-titlebar-close.

Trigger

The close button HTML:

```<code><button type="button" class="ui-button ui-dialog-titlebar-close" role="button" title="Close">
<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>
<span class="ui-button-text">Close</span>
</button>
</code>```

When I change the CSS matches in the trigger with a Next(volgende) or cancel(annuleren) button, the tag get activated on click and the event can be viewed in Google Analytics Events:

I hope some one can help me out!

Edit

Changed the CSS ui-dialog-titlebar-close mention to
  .ui-dialog-titlebar-close, was missing a dot. But that didn't solved
  my problem. Still can't see the close action in events.

答:
It would be too long to post as a comment, so i'll add a possible answer here.
Try with this selector.

```<code>.ui-button.ui-dialog-titlebar-close,.ui-button.ui-dialog-titlebar-close .ui-button-icon-primary.ui-icon.ui-icon-closethick,.ui-button.ui-dialog-titlebar-close .ui-button-text
</code>```

This is a selector for the button and the two spans elements inside.

Body:
I've implemented Google Analytics in a ORACLE APEX application.
I would like to know how to track the event 'closing a modal dialog / press close button' in Google Analytics.

I've tried the following with Google Tag Manager:

Tag

I've created a tag, as an event type. Which contains a trigger which will trigger the tag when the clicked element matches .ui-dialog-titlebar-close.

Trigger

The close button HTML:

<button type="button" class="ui-button ui-dialog-titlebar-close" role="button" title="Close">

Close
</button>

When I change the CSS matches in the trigger with a Next(volgende) or cancel(annuleren) button, the tag get activated on click and the event can be viewed in Google Analytics Events:

I hope some one can help me out!

Edit

Changed the CSS ui-dialog-titlebar-close mention to
  .ui-dialog-titlebar-close, was missing a dot. But that didn't solved
  my problem. Still can't see the close action in events.

Body:
It would be too long to post as a comment, so i'll add a possible answer here.
Try with this selector.

.ui-button.ui-dialog-titlebar-close,.ui-button.ui-dialog-titlebar-close .ui-button-icon-primary.ui-icon.ui-icon-closethick,.ui-button.ui-dialog-titlebar-close .ui-button-text

This is a selector for the button and the two spans elements inside.


问:
C# and cXML - Best way to do it
Does anyone have worked with cXML and C#?

I'm working in a project that will need to create cXML files (integration will Dell's electronic Purchase Ordering system) and have found some libs like this one, but now I wonder if anyone here has another ideia of how to create those files.

Thanks!

答:
I may add that since cXML v1.1.xx, there is a new Digital Signature stuff in it that will prevent XSD from creating the classe file.  It should return an error like "

The element 'uri:ds:Signature' is missing.

"

However, you can take a look HERE : just remove that line from the XSD.

Title: C# and cXML - Best way to do it


问:
Python nested loop and update set
I am a new student and now I am learning diversity in a set. I want to implement the greedy heuristic algorithm, this algorithm is quite easy, but I am stuck in the code.

Greedy heuristics generally make use of two sets: the set X of available items and the set S which contains the selected ones. Items are iteratively moved from X to S and vice versa until |S| = k. Items are moved one-by-one from X to S until k of them have been selected. The item that is moved each time is the one that has the maximum item-set distance setdist from S. The item-set distance/setdist, denoted as following:

The algorithm looks like this:

This is my current code:

```<code>from scipy.spatial import distance

k = 5

# this is just sample set, the real set is complex.
S = [1,9]
X = [3,4,5,6,7,8,103,1035,2009]

i = 1
while i < k:
    mylist =[]
    for a in range(0, len(X)):
        d = 0
        for b in range(0, len(S)):
            ed = distance.euclidean(X[a],S[b])
            if ed > d:
                d = ed
                listku = [(X[a],S[b]), d]
                #print(listku)
                mylist.append(listku)
                max_dis = max(mylist,key=lambda item:item[1])
    i = i + 1
</code>```

From that code, I can get the max_dis, which is [(2009, 1), 2008.0] and I am stuck here.

The next step is, I want to take 2009 from max_dis [(2009, 1), 2008.0] then append to S and looping iteratively.

The expected output maybe: [1,9,103,1035,2009] this set is the optimum one/has max diverse.

答:
```<code>from scipy.spatial import distance as dd

def test():
    k = 5

    # this is just sample set, the real set is complex.
    S = [1, 9]
    X = [3, 4, 5, 6, 7, 8, 103, 1035, 2009]

    i = 1
    while i < k:
        mylist = []
        for a in xrange(len(X)):
            d = 0
            for b in xrange(len(S)):
                ed = dd.euclidean(X[a], S[b])
                if ed > d:
                    d = ed
                    listku = [(X[a], S[b]), d]
                    # print(listku)
                    mylist.append(listku)
                    max_dis = max(mylist, key=lambda x: x[1])
                    print "my list: "
                    print mylist
                    print "*************************************************"
                    print "max distance: "
                    print max_dis
            if max_dis[0][0] not in S:
                S.append(max_dis[0][0])
        print "----------------------------------"
        print "S: "
        print S
        i += 1

test()
</code>```

final output for S:

```<code>S: [1, 9, 3, 8, 103, 1035, 2009]
</code>```

Explanation

This prints, in each run, the element in X that gives you maximum distance, which then gets added to S.

if statement is actually union, it's only adding the unique element to S.
and I can see this is what's expected in your algorithm setup (line 5).

you can see for yourself using the print statement to check whether you have achieved what you wanted here.

The algo psuedocodes look to me suggested something slightly different from what you have implemented; but that doesn't matter, you can later sort it out yourself.

P.S. This is in Python 2, you might want to change the print statements to use brackets.

Title: Python nested loop and update set

Body:
I am a new student and now I am learning diversity in a set. I want to implement the greedy heuristic algorithm, this algorithm is quite easy, but I am stuck in the code.

Greedy heuristics generally make use of two sets: the set X of available items and the set S which contains the selected ones. Items are iteratively moved from X to S and vice versa until |S| = k. Items are moved one-by-one from X to S until k of them have been selected. The item that is moved each time is the one that has the maximum item-set distance setdist from S. The item-set distance/setdist, denoted as following:

The algorithm looks like this:

This is my current code:

from scipy.spatial import distance

k = 5

# this is just sample set, the real set is complex.
S = [1,9]
X = [3,4,5,6,7,8,103,1035,2009]

i = 1
while i < k:
    mylist =[]
    for a in range(0, len(X)):
        d = 0
        for b in range(0, len(S)):
            ed = distance.euclidean(X[a],S[b])
            if ed > d:
                d = ed
                listku = [(X[a],S[b]), d]
                #print(listku)
                mylist.append(listku)
                max_dis = max(mylist,key=lambda item:item[1])
    i = i + 1

From that code, I can get the max_dis, which is [(2009, 1), 2008.0] and I am stuck here.

The next step is, I want to take 2009 from max_dis [(2009, 1), 2008.0] then append to S and looping iteratively.

The expected output maybe: [1,9,103,1035,2009] this set is the optimum one/has max diverse.

Body:
from scipy.spatial import distance as dd

def test():
    k = 5

    # this is just sample set, the real set is complex.
    S = [1, 9]
    X = [3, 4, 5, 6, 7, 8, 103, 1035, 2009]

    i = 1
    while i < k:
        mylist = []
        for a in xrange(len(X)):
            d = 0
            for b in xrange(len(S)):
                ed = dd.euclidean(X[a], S[b])
                if ed > d:
                    d = ed
                    listku = [(X[a], S[b]), d]
                    # print(listku)
                    mylist.append(listku)
                    max_dis = max(mylist, key=lambda x: x[1])
                    print "my list: "
                    print mylist
                    print "*************************************************"
                    print "max distance: "
                    print max_dis
            if max_dis[0][0] not in S:
                S.append(max_dis[0][0])
        print "----------------------------------"
        print "S: "
        print S
        i += 1

test()

final output for S:

S: [1, 9, 3, 8, 103, 1035, 2009]

Explanation

This prints, in each run, the element in X that gives you maximum distance, which then gets added to S.

if statement is actually union, it's only adding the unique element to S.
and I can see this is what's expected in your algorithm setup (line 5).

you can see for yourself using the print statement to check whether you have achieved what you wanted here.

The algo psuedocodes look to me suggested something slightly different from what you have implemented; but that doesn't matter, you can later sort it out yourself.

P.S. This is in Python 2, you might want to change the print statements to use brackets.


问:
Using foreach with ArrayList - automatic casting?
```<code>ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}
</code>```

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

答: Yes of course when you run that loop and cast it with , the compiler will try to cast it to the type specified, which in your case it will be String. and if it cannot do it it will raise an InvalidCastException. </p>

Body:
ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?


问:
composer multiple apps use path repo local and vcs on server
I have multiple apps which share some repos.

In my local dev environment I have symlinked those repos via

```<code>{
    "repositories" : [
        {
            "type" : "path",
            "url" : "../../selion/importbundle"
        }
    ]
}
</code>```

to my apps such that I can test repo changes instantly on all apps.

I run composer update locally push the app changes to a git repo and just install them on the server. but server side this is kind of annoying
because

I need to update the repos and the apps

I need to update all apps

Is it possible to use path repos locally and vcs repos serverside?

答:
the solution i came up with is using a dev and a master branch and franzl/studio

install studio globally

add a studio.json file to your dev branch

{
    "version": 2,
    "paths": [
        "../../selion/*"
    ]
}

add a studio.json file to your master branch without a path

{
    "version": 2,
    "paths": [
    ]
}

Add a .gitattributes file in your master branch so that the studio.json file won't get overwritten when you merge the dev branch

studio.json merge=ours

Now you can develop in the dev branch and because of studio you have the symlinked repos. If you want to update merge the changes into the master branch run composer update which will use the vcs repos and push the changes

Body:
I have multiple apps which share some repos.

In my local dev environment I have symlinked those repos via

{
    "repositories" : [
        {
            "type" : "path",
            "url" : "../../selion/importbundle"
        }
    ]
}

to my apps such that I can test repo changes instantly on all apps.

I run composer update locally push the app changes to a git repo and just install them on the server. but server side this is kind of annoying
because

I need to update the repos and the apps

I need to update all apps

Is it possible to use path repos locally and vcs repos serverside?


问:
Where is bootstrap/autoload.php in Laravel 5.5?
In previous versions of Laravel there was a file autoload.php. After I installed Laravel 5.5, that file is not found. Is it moved or deleted?

答: like in all composer projects: vendor\autoload.php


问:
Why is there a type mismatch when unioning a collection of Datasets
I'm trying to get the union of an ArrayBuffer[Dataset[_]].

So I wrote the the following code:

```<code>var buffer: ArrayBuffer[Dataset[_]] = ArrayBuffer.empty[Dataset[_]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df)
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}
</code>```

I get the following error:

```<code>type mismatch;
[error]  found   : org.apache.spark.sql.Dataset[_$2(in value $anonfun)] where type _$2(in value $anonfun)
[error]  required: org.apache.spark.sql.Dataset[_$2(in variable buffer)]
[error]           val unionedDataset = buffer.reduce(_ union _)
[error]                                                      ^
</code>```

Shouldn't the type of the second argument in the anonymous function be the same type of the object at the index that was referenced?

答:
You could use Any instead of _, this should also work:

```<code>var buffer: ArrayBuffer[Dataset[Any]] = ArrayBuffer.empty[Dataset[Any]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df.asInstanceOf[Dataset[Any]])
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}
</code>```

Body:
I'm trying to get the union of an ArrayBuffer[Dataset[_]].

So I wrote the the following code:

var buffer: ArrayBuffer[Dataset[_]] = ArrayBuffer.empty[Dataset[_]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df)
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}

I get the following error:

type mismatch;
[error]  found   : org.apache.spark.sql.Dataset[_$2(in value $anonfun)] where type _$2(in value $anonfun)
[error]  required: org.apache.spark.sql.Dataset[_$2(in variable buffer)]
[error]           val unionedDataset = buffer.reduce(_ union _)
[error]                                                      ^

Shouldn't the type of the second argument in the anonymous function be the same type of the object at the index that was referenced?

Body:
You could use Any instead of _, this should also work:

var buffer: ArrayBuffer[Dataset[Any]] = ArrayBuffer.empty[Dataset[Any]]

var size:Long = 0
...

if size < 1000 {
  buffer.append(df.asInstanceOf[Dataset[Any]])
  size = size + df.count()
} else {
  val unionedDataset = buffer.reduce(_ union _)
}


问:
Is there any way to make JFrame in front of applications outside windows? For example during playing any game on full screen?
I am looking for a way to make my Chat GUI in front of all the applications not only in windows. AlwaysOnTop does not solve this problem. As I mentioned mainly during playing games on full screen. I couldn't find anything on the internet so here I am :P

EDIT: I found out that if you change display settings in the game to "Borderless" or "Windowed full screen" your GUI window will stay on top with "AlwaysOnTop". Thanks for help anyways.

答:
If I understand correctly, you want a JFrame to be always on top. Et voila,

JFrame frame = new JFrame ();
frame.setAlwaysOnTop (true);


问:
What exactly is Socket
I don't know exactly what socket means.
A server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
When the server accepts the connection, it gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client.
It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

So, socket is some class created in memory? And for every client connection there is created new instance of this class in memory? Inside socket is written the local port and port and IP number of the client which is connected. Can someone explain me more in details the definition of socket?

Thanks

答:
According to "TCP/IP Sockets in C-Practical Guide for Programmers" by Michael J. Doonahoo & Kenneth L. Calvert (Chptr 1, Section 1.4, Pg 7):

A socket is an abstraction through which an application may send
  and receive data,in much the same way as an open file allows an application to read and write data to stable storage.
  A socket allows an application to "plug in" to the network and communicate
  with other applications that are also plugged in to the same network.
  Information written to the socket by an application on one machine can be
  read by an application on a different machine, and vice versa.

Refer to this book to get clarity about sockets from a programmers point of view.

Title: What exactly is Socket