问:
Get current value of Subject.asObservable() inside Angular service
I want to write a simple toggle inside an Angular2 service.

Therefore I need the current value of a Subject I observe (see below).

```<code>import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';

@Injectable()

export class SettingsService {

  private _panelOpened = new Subject<boolean>();
  panelOpened$ = this._panelOpened.asObservable();

  togglePanel() {
    this._panelOpened.next(!this.panelOpened$);
  }

}
</code>```

How do I get the current value from _panelOpened/panelOpened$?

Thanks.

答:
To elaborate on @MattBurnell in the comments of the accepted answer;

If you just want the current value right now (and you don't want a lot of subscriptions floating around), you can just use the method getValue() of the BehaviorSubject.

```<code>import {Component, OnInit} from 'angular2/core';
import {BehaviorSubject} from 'rxjs/subject/BehaviorSubject';

@Component({
  selector: 'bs-test',
  template: '<p>Behaviour subject test</p>'
})
export class BsTest implements OnInit {

  private _panelOpened = new BehaviorSubject<boolean>(false);
  private _subscription;

  ngOnInit() {
    console.log('initial value of _panelOpened', this._panelOpened.getValue());

    this._subscription = this._panelOpened.subscribe(next => {
      console.log('subscribing to it will work:', next);
    });

    // update the value:
    console.log('==== _panelOpened is now true ====');
    this._panelOpened.next(true);

    console.log('getValue will get the next value:', this._panelOpened.getValue());
  }
}
</code>```

This will result in:

```<code>initial value of _panelOpened false
subscribing to it will work: false
==== _panelOpened is now true ====
subscribing to it will work: true
getValue will get the next value: true
</code>```

See plunker:

Body:
I want to write a simple toggle inside an Angular2 service.

Therefore I need the current value of a Subject I observe (see below).

import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';

@Injectable()

export class SettingsService {

  private _panelOpened = new Subject<boolean>();
  panelOpened$ = this._panelOpened.asObservable();

  togglePanel() {
    this._panelOpened.next(!this.panelOpened$);
  }

}

How do I get the current value from _panelOpened/panelOpened$?

Thanks.

Body:
To elaborate on @MattBurnell in the comments of the accepted answer;

If you just want the current value right now (and you don't want a lot of subscriptions floating around), you can just use the method getValue() of the BehaviorSubject.

import {Component, OnInit} from 'angular2/core';
import {BehaviorSubject} from 'rxjs/subject/BehaviorSubject';

@Component({
  selector: 'bs-test',
  template: '<p>Behaviour subject test</p>'
})
export class BsTest implements OnInit {

  private _panelOpened = new BehaviorSubject<boolean>(false);
  private _subscription;

  ngOnInit() {
    console.log('initial value of _panelOpened', this._panelOpened.getValue());

    this._subscription = this._panelOpened.subscribe(next => {
      console.log('subscribing to it will work:', next);
    });

    // update the value:
    console.log('==== _panelOpened is now true ====');
    this._panelOpened.next(true);

    console.log('getValue will get the next value:', this._panelOpened.getValue());
  }
}

This will result in:

initial value of _panelOpened false
subscribing to it will work: false
==== _panelOpened is now true ====
subscribing to it will work: true
getValue will get the next value: true

See plunker:


来源: stackexchange

问:
Passing a value from listview to a textbox in another form C#
I have two forms as Main form and Product form. In the Main form I have a listview which contains the details of product. I want to sent the product id in the listview to the Product form through the 'Update' button click. Can any one help me? This is the code to bind the listview in the main form. And i have a textbox1 in Product form.

```<code>        public void BindGridProduct()
    {
    try
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");

            SqlCommand command = con.CreateCommand();
            command.CommandText = "sp_getAllProducts";

            SqlDataAdapter da = new SqlDataAdapter(command);
            DataTable dataTable = new DataTable();
            da.Fill(dataTable);

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow drow = dataTable.Rows[i];

                // Only row that have not been deleted
                if (drow.RowState != DataRowState.Deleted)
                {
                    // Define the list items
                    ListViewItem lvi = new ListViewItem(drow["ProductId"].ToString());
                    lvi.SubItems.Add(drow["ProductName"].ToString());
                    lvi.SubItems.Add(drow["TypeName"].ToString());
                    lvi.SubItems.Add(drow["Quantity"].ToString());
                    lvi.SubItems.Add(drow["Price"].ToString());
                    lvi.SubItems.Add(drow["Stock"].ToString());

                    // Add the list items to the ListView
                    listView2.Items.Add(lvi);
                }
            }

            con.Close();
        }

        catch(Exception ex)
        {
            throw ex;
        }
    }
</code>```

And this is the button in the Main form, to pass the value to other form

```<code>        private void button22_Click_1(object sender, EventArgs e)
    {
       //code

    }
</code>```

Regards

答:
Create a constructor:

```<code>public partial class frmProduct : Form
    {
        public frmProduct()
        {
            InitializeComponent();
        }

        public frmProduct(int yourId)
        {
            InitializeComponent();
        }
    }
</code>```

Show your form:

```<code>int id = 5;
frmProduct frm = new frmProduct(id);
frm.Show(this);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two forms as Main form and Product form. In the Main form I have a listview which contains the details of product. I want to sent the product id in the listview to the Product form through the 'Update' button click. Can any one help me? This is the code to bind the listview in the main form. And i have a textbox1 in Product form.

        public void BindGridProduct()
    {
    try
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");

            SqlCommand command = con.CreateCommand();
            command.CommandText = "sp_getAllProducts";

            SqlDataAdapter da = new SqlDataAdapter(command);
            DataTable dataTable = new DataTable();
            da.Fill(dataTable);

            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow drow = dataTable.Rows[i];

                // Only row that have not been deleted
                if (drow.RowState != DataRowState.Deleted)
                {
                    // Define the list items
                    ListViewItem lvi = new ListViewItem(drow["ProductId"].ToString());
                    lvi.SubItems.Add(drow["ProductName"].ToString());
                    lvi.SubItems.Add(drow["TypeName"].ToString());
                    lvi.SubItems.Add(drow["Quantity"].ToString());
                    lvi.SubItems.Add(drow["Price"].ToString());
                    lvi.SubItems.Add(drow["Stock"].ToString());

                    // Add the list items to the ListView
                    listView2.Items.Add(lvi);
                }
            }

            con.Close();
        }

        catch(Exception ex)
        {
            throw ex;
        }
    }

And this is the button in the Main form, to pass the value to other form

        private void button22_Click_1(object sender, EventArgs e)
    {
       //code

    }

Regards

Body:
Create a constructor:

public partial class frmProduct : Form
    {
        public frmProduct()
        {
            InitializeComponent();
        }

        public frmProduct(int yourId)
        {
            InitializeComponent();
        }
    }

Show your form:

int id = 5;
frmProduct frm = new frmProduct(id);
frm.Show(this);


问:
How big can a MySQL database get before performance starts to degrade
At what point does a MySQL database start to lose performance?

Does physical database size matter?

Do number of records matter?

Is any performance degradation linear or exponential?

I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years?

答: Database size DOES matter in terms of bytes and table's rows number. You will notice a huge performance difference between a light database and a blob filled one. Once my application got stuck because I put binary images inside fields instead of keeping images in files on the disk and putting only file names in database. Iterating a large number of rows on the other hand is not for free.</p>


问:
` __webpack_require__(...) is not a function` when using babel 6
Everything seems to build fine: http://d.pr/i/1aZxR
with the following configs.

However, when I run the code I get the following error this (via webpack-dev-server):

```<code>Uncaught TypeError: __webpack_require__(...) is not a function(anonymous function) @ login.js:4__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ bootstrap.js:2363__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ app.38790ff45722f55eb700.js:29__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50webpackJsonpCallback @ bootstrap 38790ff45722f55eb700?6a08:21(anonymous function) @ app.38790ff45722f55eb700.js:1
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.7/$injector/nomod?p0=app
    at http://localhost:3000/vendor.js:193:13
    at http://localhost:3000/vendor.js:2111:18
    at ensure (http://localhost:3000/vendor.js:2035:39)
    at module (http://localhost:3000/vendor.js:2109:15)
    at http://localhost:3000/vendor.js:4515:23
    at forEach (http://localhost:3000/vendor.js:461:21)
    at loadModules (http://localhost:3000/vendor.js:4499:6)
    at createInjector (http://localhost:3000/vendor.js:4424:12)
    at doBootstrap (http://localhost:3000/vendor.js:1782:21)
    at bootstrap (http://localhost:3000/vendor.js:1803:13)
http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=app&p1=Error%3A%20%…%20at%20bootstrap%20(http%3A%2F%2Flocalhost%3A3000%2Fvendor.js%3A1803%3A13)(anonymous function) @ angular.js:68(anonymous function) @ angular.js:4413forEach @ angular.js:336loadModules @ angular.js:4374createInjector @ angular.js:4299doBootstrap @ angular.js:1657bootstrap @ angular.js:1678angularInit @ angular.js:1572(anonymous function) @ angular.js:28899fire @ jquery.js:3099self.fireWith @ jquery.js:3211jQuery.extend.ready @ jquery.js:3417completed @ jquery.js:3433
</code>```

I think babel is interfering with __webpack_require__ in some way but I'm not sure. I did try using different transforms/plugins but I wasn't able to find a solution.

.babelrc:

```<code>{
  "plugins":[
    "transform-runtime",
    "transform-node-env-inline"
  ],
  "presets":[
    "stage-0",
    "es2015"
  ]
}
</code>```

here's my webpack.config.js:

```<code>var Clean = require('clean-webpack-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var path = require('path');
var StatsPlugin = require('stats-webpack-plugin');
var webpack = require('webpack');

//CONSTANTS

var NODE_ENV = process.env.NODE_ENV;
var IS_DEV = NODE_ENV === 'development';
var babelFile = fs.readFileSync('./.babelrc', 'utf8');
var BABELRC = JSON.parse(babelFile);
var cleanFonts = function(){
  return new Clean(['dist/tmp/*.{ttf,eot,svg,woff}']);
}
var cleanImages = function(){
  return new Clean(['dist/tmp/*.{png,jpg}']);
}
var cleanJs = function(){
  return new Clean(['dist/*.{js,map}']);
}
var plugins = [
  new webpack.NoErrorsPlugin(),
  cleanJs(),
  // new StatsPlugin('stats.json', {chunkModules: true}),
  new webpack.ProvidePlugin({$: "jquery",jQuery: "jquery","window.jQuery": "jquery" }),
  new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
  new HtmlWebpackPlugin({
    template: 'client/app/vendors/assets/index-tmpl.html',
    filename: 'index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.js',
    chunks:['customer','personalOrganization','app']
  })
  // new ngAnnotatePlugin({add: true})
  // new ExtractTextPlugin("style.[hash].css", {
  //    disable: false,
  //    allChunks: true
  // }),

  //new webpack.optimize.CommonsChunkPlugin({minChunks: 2, children: true, async: true}),
  // new CompressionPlugin({asset: "{file}.gz", algorithm: "gzip", regExp: /\.js$|\.html$/, threshold: 10240, minRatio: 0.8 })
];
var dev_plugins = [
]
var prod_plugins = [
  cleanFonts(),
  cleanImages(),
  new webpack.optimize.UglifyJsPlugin({
    minimize: true,
    sourceMap: false,
    compress: { warnings: false },
    mangle: false
  }),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.AggressiveMergingPlugin()
];
if(NODE_ENV !== 'development'){
  plugins = plugins.concat(prod_plugins);
}
else{
  plugins = plugins.concat(dev_plugins);
}
babelLoaderOpts = {
  cacheDirectory: true
};
Object.assign(babelLoaderOpts, BABELRC);
module.exports = {
  cache: IS_DEV,
  // watch: IS_DEV,
  devtool: 'source-map',
  entry: {
    "app": "./client/app/app.js",
    "devserver": 'webpack-dev-server/client?http://localhost:3000'
  },
  output: {
      path: __dirname + "/dist",
      filename: '[name].[hash].js'
  },
  module: {
        noParse: [
          /moment.js/
        ],
        loaders: [
            { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
            {
              test: /\.js$/,
              exclude: /(node_modules|bower_components|vendors)/,
              loader: 'babel',
              query: babelLoaderOpts
            },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded"+"&includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")},
            { test: /\.css$/,  loader: 'style!css' },
            { test: /\.(png|jpeg|jpg|gif)$/, loader: 'url-loader?limit=30000&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff(\?\S*)?$/,  loader : 'url?prefix=font/&limit=10000&mimetype=application/font-woff&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff2/, loader: 'url?prefix=font/&limit=100000&mimetype=application/font-woff2&name=tmp/[name].[ext]&no_emit_env=development' },
            { test: /\.ttf/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.eot/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.svg/,loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            //{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&&includePaths[]='+ path.resolve(__dirname, './node_modules/compass-mixins/lib')) },
            //{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
      ]
  },
  devServer: {
    contentBase: './client/app'
  },
  resolve: {
      modulesDirectories: ['vendors','node_modules', 'bower_components'],
      extensions: ['', '.js', '.json']
  },
  plugins: plugins
};
</code>```

答:
I'd like to add another reason why this error might pop up:

I did the following:

```<code>import mapActions from 'vuex'
</code>```

instead of:

```<code>import { mapActions } from 'vuex'
</code>```

The former was importing the entire vuex export, which is an object. Adding object destructuring fixed the problem.

Body:
Everything seems to build fine: http://d.pr/i/1aZxR
with the following configs.

However, when I run the code I get the following error this (via webpack-dev-server):

Uncaught TypeError: __webpack_require__(...) is not a function(anonymous function) @ login.js:4__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ bootstrap.js:2363__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ app.38790ff45722f55eb700.js:29__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50webpackJsonpCallback @ bootstrap 38790ff45722f55eb700?6a08:21(anonymous function) @ app.38790ff45722f55eb700.js:1
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.7/$injector/nomod?p0=app
    at http://localhost:3000/vendor.js:193:13
    at http://localhost:3000/vendor.js:2111:18
    at ensure (http://localhost:3000/vendor.js:2035:39)
    at module (http://localhost:3000/vendor.js:2109:15)
    at http://localhost:3000/vendor.js:4515:23
    at forEach (http://localhost:3000/vendor.js:461:21)
    at loadModules (http://localhost:3000/vendor.js:4499:6)
    at createInjector (http://localhost:3000/vendor.js:4424:12)
    at doBootstrap (http://localhost:3000/vendor.js:1782:21)
    at bootstrap (http://localhost:3000/vendor.js:1803:13)
http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=app&p1=Error%3A%20%…%20at%20bootstrap%20(http%3A%2F%2Flocalhost%3A3000%2Fvendor.js%3A1803%3A13)(anonymous function) @ angular.js:68(anonymous function) @ angular.js:4413forEach @ angular.js:336loadModules @ angular.js:4374createInjector @ angular.js:4299doBootstrap @ angular.js:1657bootstrap @ angular.js:1678angularInit @ angular.js:1572(anonymous function) @ angular.js:28899fire @ jquery.js:3099self.fireWith @ jquery.js:3211jQuery.extend.ready @ jquery.js:3417completed @ jquery.js:3433

I think babel is interfering with __webpack_require__ in some way but I'm not sure. I did try using different transforms/plugins but I wasn't able to find a solution.

.babelrc:

{
  "plugins":[
    "transform-runtime",
    "transform-node-env-inline"
  ],
  "presets":[
    "stage-0",
    "es2015"
  ]
}

here's my webpack.config.js:

var Clean = require('clean-webpack-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var path = require('path');
var StatsPlugin = require('stats-webpack-plugin');
var webpack = require('webpack');

//CONSTANTS

var NODE_ENV = process.env.NODE_ENV;
var IS_DEV = NODE_ENV === 'development';
var babelFile = fs.readFileSync('./.babelrc', 'utf8');
var BABELRC = JSON.parse(babelFile);
var cleanFonts = function(){
  return new Clean(['dist/tmp/*.{ttf,eot,svg,woff}']);
}
var cleanImages = function(){
  return new Clean(['dist/tmp/*.{png,jpg}']);
}
var cleanJs = function(){
  return new Clean(['dist/*.{js,map}']);
}
var plugins = [
  new webpack.NoErrorsPlugin(),
  cleanJs(),
  // new StatsPlugin('stats.json', {chunkModules: true}),
  new webpack.ProvidePlugin({$: "jquery",jQuery: "jquery","window.jQuery": "jquery" }),
  new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
  new HtmlWebpackPlugin({
    template: 'client/app/vendors/assets/index-tmpl.html',
    filename: 'index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.js',
    chunks:['customer','personalOrganization','app']
  })
  // new ngAnnotatePlugin({add: true})
  // new ExtractTextPlugin("style.[hash].css", {
  //    disable: false,
  //    allChunks: true
  // }),

  //new webpack.optimize.CommonsChunkPlugin({minChunks: 2, children: true, async: true}),
  // new CompressionPlugin({asset: "{file}.gz", algorithm: "gzip", regExp: /\.js$|\.html$/, threshold: 10240, minRatio: 0.8 })
];
var dev_plugins = [
]
var prod_plugins = [
  cleanFonts(),
  cleanImages(),
  new webpack.optimize.UglifyJsPlugin({
    minimize: true,
    sourceMap: false,
    compress: { warnings: false },
    mangle: false
  }),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.AggressiveMergingPlugin()
];
if(NODE_ENV !== 'development'){
  plugins = plugins.concat(prod_plugins);
}
else{
  plugins = plugins.concat(dev_plugins);
}
babelLoaderOpts = {
  cacheDirectory: true
};
Object.assign(babelLoaderOpts, BABELRC);
module.exports = {
  cache: IS_DEV,
  // watch: IS_DEV,
  devtool: 'source-map',
  entry: {
    "app": "./client/app/app.js",
    "devserver": 'webpack-dev-server/client?http://localhost:3000'
  },
  output: {
      path: __dirname + "/dist",
      filename: '[name].[hash].js'
  },
  module: {
        noParse: [
          /moment.js/
        ],
        loaders: [
            { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
            {
              test: /\.js$/,
              exclude: /(node_modules|bower_components|vendors)/,
              loader: 'babel',
              query: babelLoaderOpts
            },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded"+"&includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")},
            { test: /\.css$/,  loader: 'style!css' },
            { test: /\.(png|jpeg|jpg|gif)$/, loader: 'url-loader?limit=30000&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff(\?\S*)?$/,  loader : 'url?prefix=font/&limit=10000&mimetype=application/font-woff&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff2/, loader: 'url?prefix=font/&limit=100000&mimetype=application/font-woff2&name=tmp/[name].[ext]&no_emit_env=development' },
            { test: /\.ttf/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.eot/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.svg/,loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            //{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&&includePaths[]='+ path.resolve(__dirname, './node_modules/compass-mixins/lib')) },
            //{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
      ]
  },
  devServer: {
    contentBase: './client/app'
  },
  resolve: {
      modulesDirectories: ['vendors','node_modules', 'bower_components'],
      extensions: ['', '.js', '.json']
  },
  plugins: plugins
};

Body:
I'd like to add another reason why this error might pop up:

I did the following:

import mapActions from 'vuex'

instead of:

import { mapActions } from 'vuex'

The former was importing the entire vuex export, which is an object. Adding object destructuring fixed the problem.


问:
EHCache doesn't seem to work
I've set up ehcache on our Java application, which uses Spring and Hibernate.
However, when I run Junit tests and print the stats, it seems there is nothing in cache:

OUTPUT OF CACHE MANAGER STATS ON EVERY CACHE:

COM.****.SERVICES.CLARITY.DOMAIN.ACTIONITEM.BYRESOURCEUNIQUENAME:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

COM.****.SERVICES.CLARITY.DOMAIN.ACTIONITEM:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

COM.****.SERVICES.CLARITY.DOMAIN.RESOURCE:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

CONTENT OF THE MAPPING FILE (ONLY PARTS, TOO BIG TO PASTE ALL):

```<code><class name="ActionItem" table="CAL_ACTION_ITEMS" mutable="false" lazy="false" >
<cache region="com.****.services.clarity.domain.ActionItem" usage="read-only" include="all" />
</code>```

[...]

```<code><query name="byResourceUniqueName" cacheable="true" cache-region="com.****.services.clarity.domain.ActionItem.byResourceUniqueName" read-only="true">
    FROM ActionItem WHERE id IN (
        SELECT DISTINCT actionItemId FROM ActionItemAssignee as aia WHERE assigneeId IN (
            SELECT userId FROM Resource WHERE uniqueName = :uniqueName
        )
    )
    ORDER BY dueDate
</query>
</code>```

CONTENT OF EHCACHE.XML:

```<code><cache
    name="com.****.services.clarity.domain.ActionItem"
    maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
    timeToLiveSeconds="600" overflowToDisk="false" />

<cache
    name="com.****.services.clarity.domain.ActionItem.byResourceUniqueName"
    maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
    timeToLiveSeconds="60" overflowToDisk="false" />

<defaultCache maxElementsInMemory="200" eternal="false"
    timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
    memoryStoreEvictionPolicy="LRU" />
</code>```

HIBERNATE CONFIG:

```<code>    <property name="hibernateProperties">
        <value>
            hibernate.format_sql=true
            hibernate.dialect=org.hibernate.dialect.OracleDialect
            hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider
            hibernate.cache.use_query_cache=true
            hibernate.show_sql=true
        </value>
    </property>
</bean>
</code>```

Any ideas on how to populate the cache ?
Thanks.

答:
yeah,when you use second cache in hibernate , when you will query you must set like this:

```<code>Query q=....
q.setCacheable(tre);
</code>```

if you Spring you must write like this

```<code>getHibernateTemplate().setCacheQueries(true);
</code>```

ContentLicense: CC BY-SA 2.5

Title: EHCache doesn't seem to work

Body:
I've set up ehcache on our Java application, which uses Spring and Hibernate.
However, when I run Junit tests and print the stats, it seems there is nothing in cache:

OUTPUT OF CACHE MANAGER STATS ON EVERY CACHE:

COM.****.SERVICES.CLARITY.DOMAIN.ACTIONITEM.BYRESOURCEUNIQUENAME:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

COM.****.SERVICES.CLARITY.DOMAIN.ACTIONITEM:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

COM.****.SERVICES.CLARITY.DOMAIN.RESOURCE:
getCacheHits: 0
getCacheMisses: 0
getObjectCount: 0

CONTENT OF THE MAPPING FILE (ONLY PARTS, TOO BIG TO PASTE ALL):

<class name="ActionItem" table="CAL_ACTION_ITEMS" mutable="false" lazy="false" >
<cache region="com.****.services.clarity.domain.ActionItem" usage="read-only" include="all" />

[...]

<query name="byResourceUniqueName" cacheable="true" cache-region="com.****.services.clarity.domain.ActionItem.byResourceUniqueName" read-only="true">
    FROM ActionItem WHERE id IN (
        SELECT DISTINCT actionItemId FROM ActionItemAssignee as aia WHERE assigneeId IN (
            SELECT userId FROM Resource WHERE uniqueName = :uniqueName
        )
    )
    ORDER BY dueDate
</query>

CONTENT OF EHCACHE.XML:

<cache
    name="com.****.services.clarity.domain.ActionItem"
    maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
    timeToLiveSeconds="600" overflowToDisk="false" />

<cache
    name="com.****.services.clarity.domain.ActionItem.byResourceUniqueName"
    maxElementsInMemory="2000" eternal="false" timeToIdleSeconds="0"
    timeToLiveSeconds="60" overflowToDisk="false" />

<defaultCache maxElementsInMemory="200" eternal="false"
    timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
    memoryStoreEvictionPolicy="LRU" />

HIBERNATE CONFIG:

    <property name="hibernateProperties">
        <value>
            hibernate.format_sql=true
            hibernate.dialect=org.hibernate.dialect.OracleDialect
            hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider
            hibernate.cache.use_query_cache=true
            hibernate.show_sql=true
        </value>
    </property>
</bean>

Any ideas on how to populate the cache ?
Thanks.

Body:
yeah,when you use second cache in hibernate , when you will query you must set like this:

Query q=....
q.setCacheable(tre);

if you Spring you must write like this

getHibernateTemplate().setCacheQueries(true);


问:
How to retrieve specifics a firebase database entry?
I've been trying to retrieve data fields from the data that I have stored in a firebase realtime database, and I'm stuck.

This is what my database looks like:

This is a method that I've called in my AuthStateListener object and is defined as follows:

```<code>private void alterTextView(final String id) {
    if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    if (ds.exists()) {
                        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
                        String name = userInformation.getName();
                        mWelcomeUserMessage.setText(name);
                        //logging name
                        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}
</code>```

The call to this function is as such:

```<code> mAuthStatelistener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //if user is logged in, the sign_in and sign_up buttons should not be displayed
            if (firebaseAuth.getCurrentUser() != null) {
                userId = firebaseAuth.getCurrentUser().getUid();
                Log.d("Main Activity", "Current userId : " + userId);
                alterTextView(userId);
                mLogInButton.setVisibility(View.INVISIBLE);
                mSignUpButton.setVisibility(View.INVISIBLE);
                //getUserName(firebaseAuth.getCurrentUser().getUid());
                mLogOutButton.setVisibility(View.VISIBLE);
            } else {
                mLogInButton.setVisibility(View.VISIBLE);
                mSignUpButton.setVisibility(View.VISIBLE);
                mWelcomeUserMessage.setVisibility(View.GONE);
                mLogOutButton.setVisibility(View.GONE);
            }
        }
    };
</code>```

For some reason, I keep getting a null pointer exception in the first excerpt of code in the line where I store the name from the userInformation object -

```<code>String name = userInformation.getName();
</code>```

I just can't understand why this is happening.

My main goal is to print out the name of the logged in user once he/she has logged in.

Does anyone know a way to do this?

Update 1 This is what my UserInformation class looks like:

```<code>public class UserInformation {

private String name;
private String student_number;
private String faculty;
private boolean isAdmin;

public String getName() {
    return name;
}

public String getStudent_number() {
    return student_number;
}

public String getFaculty() {
    return faculty;
}

public void setName(String name) {
    this.name = name;
}

public boolean isAdmin() {
    return isAdmin;
}

public void setAdmin(boolean admin) {
    isAdmin = admin;
}

public void setStudent_number(String student_number) {
    this.student_number = student_number;
}

public void setFaculty(String faculty) {
    this.faculty = faculty;
}
}
</code>```

答:
You are trying to access a non exist child, that's the reason you are getting null value. Your listener already listens to "id child", replace the following line:

```<code> UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
</code>```

By:

```<code> UserInformation userInformation = ds.getValue(UserInformation.class);
</code>```

Then, back to your UserInformation.class, add the following changes:

```<code>@IgnoreExtraProperties // Add this tag
public class UserInformation {

    private String name;
    private String student_number;
    private String faculty;
    private boolean isAdmin;

    //Define this constructor
    public UserInformation() {
        // Default constructor required for calls to DataSnapshot.getValue(UserInformation.class)
    }
    // The rest of your class ...

}
</code>```

Body:
I've been trying to retrieve data fields from the data that I have stored in a firebase realtime database, and I'm stuck.

This is what my database looks like:

This is a method that I've called in my AuthStateListener object and is defined as follows:

private void alterTextView(final String id) {
    if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    if (ds.exists()) {
                        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
                        String name = userInformation.getName();
                        mWelcomeUserMessage.setText(name);
                        //logging name
                        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

The call to this function is as such:

 mAuthStatelistener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //if user is logged in, the sign_in and sign_up buttons should not be displayed
            if (firebaseAuth.getCurrentUser() != null) {
                userId = firebaseAuth.getCurrentUser().getUid();
                Log.d("Main Activity", "Current userId : " + userId);
                alterTextView(userId);
                mLogInButton.setVisibility(View.INVISIBLE);
                mSignUpButton.setVisibility(View.INVISIBLE);
                //getUserName(firebaseAuth.getCurrentUser().getUid());
                mLogOutButton.setVisibility(View.VISIBLE);
            } else {
                mLogInButton.setVisibility(View.VISIBLE);
                mSignUpButton.setVisibility(View.VISIBLE);
                mWelcomeUserMessage.setVisibility(View.GONE);
                mLogOutButton.setVisibility(View.GONE);
            }
        }
    };

For some reason, I keep getting a null pointer exception in the first excerpt of code in the line where I store the name from the userInformation object -

String name = userInformation.getName();

I just can't understand why this is happening.

My main goal is to print out the name of the logged in user once he/she has logged in.

Does anyone know a way to do this?

Update 1 This is what my UserInformation class looks like:

public class UserInformation {

private String name;
private String student_number;
private String faculty;
private boolean isAdmin;

public String getName() {
    return name;
}

public String getStudent_number() {
    return student_number;
}

public String getFaculty() {
    return faculty;
}

public void setName(String name) {
    this.name = name;
}

public boolean isAdmin() {
    return isAdmin;
}

public void setAdmin(boolean admin) {
    isAdmin = admin;
}

public void setStudent_number(String student_number) {
    this.student_number = student_number;
}

public void setFaculty(String faculty) {
    this.faculty = faculty;
}
}

Body:
You are trying to access a non exist child, that's the reason you are getting null value. Your listener already listens to "id child", replace the following line:

 UserInformation userInformation = ds.child(id).getValue(UserInformation.class);

By:

 UserInformation userInformation = ds.getValue(UserInformation.class);

Then, back to your UserInformation.class, add the following changes:

@IgnoreExtraProperties // Add this tag
public class UserInformation {

    private String name;
    private String student_number;
    private String faculty;
    private boolean isAdmin;

    //Define this constructor
    public UserInformation() {
        // Default constructor required for calls to DataSnapshot.getValue(UserInformation.class)
    }
    // The rest of your class ...

}


问:
initialize vector of pair of (bitset,int)
when initializing with

```<code>vector<pair< int,bitset<p> > > arr;
arr.push_back(make_pair(x,y));
</code>```

but I am gettig error:

‘pair’ cannot appear in a constant-expression

```<code>vector<pair< int,bitset<p> > > arr;
</code>```

how to make a vector of pair of bitset,int?

答:
Seems like "p" here is not constant. I tried the following and it works:</p>

```<code>const int p = 16;
vector<pair<int,bitset<p> >> v;
bitset<p> b = 0xfa2;
v.push_back(make_pair(10, b));
</code>```

Body:
when initializing with

vector<pair< int,bitset
 > > arr;
arr.push_back(make_pair(x,y));

but I am gettig error:

‘pair’ cannot appear in a constant-expression

vector<pair< int,bitset
 > > arr;

how to make a vector of pair of bitset,int?

Body:
Seems like "p" here is not constant. I tried the following and it works:

const int p = 16;
vector<pair<int,bitset<p> >> v;
bitset<p> b = 0xfa2;
v.push_back(make_pair(10, b));


问:
How to make multiple mp3 files play one after another on the click of a button using javascript or jquery?
I have the following html and script to play/pause an audio by clicking a button.

```<code><audio id="testAudio" hidden src="sample.mp3" type="audio/mpeg">
</audio>

<button id="playAudio">Play</button>

<script>
document.getElementById("playAudio").addEventListener("click", function(){
    var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }

});
</script>
</code>```

I need to edit it in such a way as to play multiple mp3 files one by one in a defined order and stop only when the last audio has played.

I just don't know how to make that work. Can anyone help?

答:
You can register an event handler for the audio tag, that first when the current file has finished;

```<code>document.getElementById("testAudio").addEventListener("ended",function(e) {
  // Play next track
});
</code>```

If you have a list of tracks to play in an array, then simply play the next one after the current track has finished.  Using the setTimeout function you can put in a delay between the tracks.  A simple example is as follows;

```<code><script>
var playlist= [
  'https://api.twilio.com/cowbell.mp3',
  'https://demo.twilio.com/hellomonkey/monkey.mp3'
];
var currentTrackIndex = 0;
var delayBetweenTracks = 2000;

document.getElementById("playAudio").addEventListener("click", function(){
  var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }
});

document.getElementById("testAudio").addEventListener("ended",function(e) {
  var audio = document.getElementById('testAudio');
  setTimeout(function() {
    currentTrackIndex++;
    if (currentTrackIndex < playlist.length) {
      audio.src = playlist[currentTrackIndex];
      audio.play();
    }
  }, delayBetweenTracks);
});
</script>
</code>```

Note that cowbell track is 52 seconds long, so if your testing the above (for your own sanity) set the controls property to the audio tag so you can skip through most of it.

Body:
I have the following html and script to play/pause an audio by clicking a button.

<audio id="testAudio" hidden src="sample.mp3" type="audio/mpeg">
</audio>

<button id="playAudio">Play</button>

I need to edit it in such a way as to play multiple mp3 files one by one in a defined order and stop only when the last audio has played.

I just don't know how to make that work. Can anyone help?

Body:
You can register an event handler for the audio tag, that first when the current file has finished;

document.getElementById("testAudio").addEventListener("ended",function(e) {
  // Play next track
});

If you have a list of tracks to play in an array, then simply play the next one after the current track has finished.  Using the setTimeout function you can put in a delay between the tracks.  A simple example is as follows;

<script>
var playlist= [
  'https://api.twilio.com/cowbell.mp3',
  'https://demo.twilio.com/hellomonkey/monkey.mp3'
];
var currentTrackIndex = 0;
var delayBetweenTracks = 2000;

document.getElementById("playAudio").addEventListener("click", function(){
  var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }
});

document.getElementById("testAudio").addEventListener("ended",function(e) {
  var audio = document.getElementById('testAudio');
  setTimeout(function() {
    currentTrackIndex++;
    if (currentTrackIndex < playlist.length) {
      audio.src = playlist[currentTrackIndex];
      audio.play();
    }
  }, delayBetweenTracks);
});
</script>

Note that cowbell track is 52 seconds long, so if your testing the above (for your own sanity) set the controls property to the audio tag so you can skip through most of it.


问:
Make image larger onclick
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

```<code>$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});
</code>```

need to achieve that it makes image smaller after another is selected

答:
pretty simple

img
{
height:50%;
width:50%;
transition:0.5s;
}
img:hover
{
height:100%;
width:100%;
transition:0.5s;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSGGB4NFcYsTk8ZYe35_aT0OmJ2e-NVS0rKxaFX5lhDCUkCW9IRVw">  </img>

</html></code>```

Title: Make image larger onclick

Body:
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});

need to achieve that it makes image smaller after another is selected

Body:
pretty simple

img
{
height:50%;
width:50%;
transition:0.5s;
}
img:hover
{
height:100%;
width:100%;
transition:0.5s;

}

<html>

  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSGGB4NFcYsTk8ZYe35_aT0OmJ2e-NVS0rKxaFX5lhDCUkCW9IRVw">  </img>

</html>


问:
Angular2 Material & angular2-color-picker error
Using angular2 with the new angular-material and third party directive angular2-color-picker throws error: </p>

```<code>"can't bind to 'colorPicker' since it isn't a known property"
</code>```

答:
Try importing it in app.module.ts</p>

```<code>import {...} from '..';
import {ColorPickerModule} from 'angular2-color-picker'; //SEE THIS

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ColorPickerModule,//SEE THIS
        ...
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

Body:
Using angular2 with the new angular-material and third party directive angular2-color-picker throws error:

"can't bind to 'colorPicker' since it isn't a known property"

Body:
Try importing it in app.module.ts

import {...} from '..';
import {ColorPickerModule} from 'angular2-color-picker'; //SEE THIS

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ColorPickerModule,//SEE THIS
        ...
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


问:
How to clone any object, including special types?
I need to write a function that returns a clone of an object.

Something like:

```<code>// non recursive clone
function clone( obj ) {
  const newObj = Object.create( Object.getPrototypeOf(obj) );
  return Object.assign( newObj, obj );
}
</code>```

This of course only works with objects, not with primitive types: it doesn't work with undefined, null, booleans, numbers, strings, symbols.

...But it also doesn't work with other types, e.g. Array, Set, Map.

I'd like to support as many types as I can, and my best idea on how to do this is handling special types case by case.

I believe that objects with Internal Methods or Internal Slots might be the ones that create problems. I'm not fully sure of this and I could not find a list of standard types with Internal Methods or Slots.

Which standard types cannot correctly be created by Object.create() exactly?

答:
Which standard types cannot correctly be created by Object.create() exactly?

All of them, indeed. Those special types you talk about can only be created using new or Reflect.construct, supplying the builtin constructor that will create the internal slots.

I could not find a list of standard types with Internal Methods or Slots.

It's right there in the spec, chapter 9 Exotic Objects (for internal methods). You can treat ordingary objects just fine (Object.create creates one), but you'll have problems with Function objects, Bound Function objects, Array objects, String objects, Arguments objects, TypedArray objects, Module namespace objects, and Proxies. Also, you can find objects with special internal slots by searching for usages of OrdinaryCreateFromConstructor (Generator, Boolean, Error and all the other native errors, Number, Date, RegExp, Map, Set, WeakMap, WeaskSet, ArrayBuffer, DataView, Promise) and  ObjectCreate (ListIterator, Arguments, all typed arrays, StringIterator, ArrayIterator, MapIterator, SetIterator).

I'd like to support as many types as I can

You should decide (and document) which are supported and which not. Especially for a recursive clone it would be a hassle. Also make sure to document how you deal with non-enumerable or symbol-keyed own properties and getters/setters, the default Object.assign behaviour might not be the desired one.

how to do this is handling special types case by case?

I'd define a Symbol.for("clone") method on the prototypes of all the supported types, that way it is easy to extend. Possibly use a known value instead where cloning cannot be supported and/or the default copy algorithm does not make sense, e.g. on iterators or function objects, so that those can be handled with an error message or be ignored.

Body:
I need to write a function that returns a clone of an object.

Something like:

// non recursive clone
function clone( obj ) {
  const newObj = Object.create( Object.getPrototypeOf(obj) );
  return Object.assign( newObj, obj );
}

This of course only works with objects, not with primitive types: it doesn't work with undefined, null, booleans, numbers, strings, symbols.

...But it also doesn't work with other types, e.g. Array, Set, Map.

I'd like to support as many types as I can, and my best idea on how to do this is handling special types case by case.

I believe that objects with Internal Methods or Internal Slots might be the ones that create problems. I'm not fully sure of this and I could not find a list of standard types with Internal Methods or Slots.

Which standard types cannot correctly be created by Object.create() exactly?


问:
Django: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
I am new to Python and Django. I am trying to install Django on Linux.
Python version currently available on the server is Python 2.4.3
I installed Python 3.4.2 following the below steps:

```<code>wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar -xvzf Python-3.4.2.tgz
cd Python-3.4.2
./configure --prefix=/root/python3
make
make install
</code>```

The python correctly got installed.
so when I do /root/python3/bin/python3.4 I get Python version 3.4.2
so i created a soft link -> ln -s /root/python3/bin/python3.4 python3

Now i created a virtualenv through

```<code>/root/python3/bin/pyvenv-3.4 venv3.4
source venv3.4/bin/activate
</code>```

then i installed DJango:

```<code>pip install Django==1.9
</code>```

Django got successfully installed

Created the project myproj:

```<code>django-admin startproject myproj
</code>```

myproj project successfully created:

```<code>cd myproj
</code>```

now when i do python manage.py migrate i get error:

```<code>Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 89, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 176, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema
    with self.connection.schema_editor() as editor:
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__
    self._initial_pragma_fk = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
</code>```

When i execute command python manage.py runserver i get error:

```<code>Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fc0df5e7f28>
Traceback (most recent call last):
  File "/root/venv3.4/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 176, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema
    with self.connection.schema_editor() as editor:
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__
    self._initial_pragma_fk = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
</code>```

I tried all the solutions provided in all stackoverflow discussions.

settings.py file

```<code>"""
Django settings for myproj project.

Generated by 'django-admin startproject' using Django 1.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qg#8o8)e*or5o#g+pxp3_&9r*=i2b*k59wjis=!*5a1&b6^^_='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproj.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
</code>```

manage.py file

```<code>#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
</code>```

Django version -> 1.9

I have not added any environment variable like PYTHONPATH or PATH. DO i need to do it.
If yes please let me know what to set and how to set.

Requesting you all to please help in resolving this error so that i can start working on Django. Its almost more than 3-4 days i am struggling.

答:
On a similar bug report, it looks like the problem was an old version of sqlite3.

Django only supports the latest point release of Python, so if you want to use Python 3.4, I suggest that you install 3.4.6 instead of 3.4.2.

Note that Django 1.9 is end of life and does not receive security fixes any more. I suggest you upgrade to the new 1.11 LTS (or possibly downgrade to the previous 1.8 LTS if you are not able to upgrade).

Body:
I am new to Python and Django. I am trying to install Django on Linux.
Python version currently available on the server is Python 2.4.3
I installed Python 3.4.2 following the below steps:

wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar -xvzf Python-3.4.2.tgz
cd Python-3.4.2
./configure --prefix=/root/python3
make
make install

The python correctly got installed.
so when I do /root/python3/bin/python3.4 I get Python version 3.4.2
so i created a soft link -> ln -s /root/python3/bin/python3.4 python3

Now i created a virtualenv through

/root/python3/bin/pyvenv-3.4 venv3.4
source venv3.4/bin/activate

then i installed DJango:

pip install Django==1.9

Django got successfully installed

Created the project myproj:

django-admin startproject myproj

myproj project successfully created:

cd myproj

now when i do python manage.py migrate i get error:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 89, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 176, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema
    with self.connection.schema_editor() as editor:
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__
    self._initial_pragma_fk = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

When i execute command python manage.py runserver i get error:

Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fc0df5e7f28>
Traceback (most recent call last):
  File "/root/venv3.4/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 176, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema
    with self.connection.schema_editor() as editor:
  File "/root/venv3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__
    self._initial_pragma_fk = c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

I tried all the solutions provided in all stackoverflow discussions.

settings.py file

"""
Django settings for myproj project.

Generated by 'django-admin startproject' using Django 1.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qg#8o8)e*or5o#g+pxp3_&9r*=i2b*k59wjis=!*5a1&b6^^_='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproj.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

manage.py file

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Django version -> 1.9

I have not added any environment variable like PYTHONPATH or PATH. DO i need to do it.
If yes please let me know what to set and how to set.

Requesting you all to please help in resolving this error so that i can start working on Django. Its almost more than 3-4 days i am struggling.


问:
How to PROVE the precedence of '&&' and '||' by coding in Java?
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

The code above produces the same results no matter the precedence of && and ||, that is,

```<code>false || false && true || false
</code>```

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

答:
Let's take your example expression:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

Now we believe that acts as:

```<code>boolExp1 || (boolExp2 && boolExp3) || boolExp4
</code>```

right?

So let's suppose the opposite is true, and it's actually

```<code>(boolExp1 || boolExp2) && (boolExp3 || boolExp4)
</code>```

What values of boolExp1 etc would give us different results?

Well, let's take:

```<code>boolExp1 = true
boolExp2 = false
boolExp3 = false
boolExp4 = false
</code>```

Under the "&& has higher precedence" rules, the result would be true. Under the "|| has higher precedence rules", the result would be false. A quick test shows that the expression evaluates to true, however.

Of course, this doesn't actually prove that && has higher precedence than || - merely that || doesn't have higher precedence than &&. We could consider whether they have equal precedence - and test that with other expressions in a similar way... find a sample expression and values which would give different results under different precedence rules, and test them.

Ultimately though, I prefer:

To trust the spec unless I have specific doubts

To use parentheses to make my intentions clear

I wouldn't use the first expression "as is" in the first place... because unless you actually know the precedence rules (and I suspect many Java devs don't - I couldn't swear that I'd have got && and || right) you're in the dark. Better to make it explicit and clear where there's any doubt.

ContentLicense: CC BY-SA 4.0

Body:
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

boolExp1 || boolExp2 && boolExp3 || boolExp4

The code above produces the same results no matter the precedence of && and ||, that is,

false || false && true || false

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

Body:
Let's take your example expression:

boolExp1 || boolExp2 && boolExp3 || boolExp4

Now we believe that acts as:

boolExp1 || (boolExp2 && boolExp3) || boolExp4

right?

So let's suppose the opposite is true, and it's actually

(boolExp1 || boolExp2) && (boolExp3 || boolExp4)

What values of boolExp1 etc would give us different results?

Well, let's take:

boolExp1 = true
boolExp2 = false
boolExp3 = false
boolExp4 = false

Under the "&& has higher precedence" rules, the result would be true. Under the "|| has higher precedence rules", the result would be false. A quick test shows that the expression evaluates to true, however.

Of course, this doesn't actually prove that && has higher precedence than || - merely that || doesn't have higher precedence than &&. We could consider whether they have equal precedence - and test that with other expressions in a similar way... find a sample expression and values which would give different results under different precedence rules, and test them.

Ultimately though, I prefer:

To trust the spec unless I have specific doubts

To use parentheses to make my intentions clear

I wouldn't use the first expression "as is" in the first place... because unless you actually know the precedence rules (and I suspect many Java devs don't - I couldn't swear that I'd have got && and || right) you're in the dark. Better to make it explicit and clear where there's any doubt.


问:
keras CNN same output
I have trained a CNN neural network in python with 800 samples and tested it on 60. The output accuracy is 50 and now every time I use model.predict it gives me the same result.

```<code>#main file - run this to train the network

import numpy as np
from keras.datasets import cifar10
from datasetFetch import DataFetch
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
import simplejson
from matplotlib import pyplot
from scipy.misc import toimage
# load data
#(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# create a grid of 3x3 images
#for i in range(0, 9):
#   pyplot.subplot(3,3,1 + i)
#   pyplot.imshow(toimage(X_train[i]))
# show the plot
#pyplot.show()

#init data
CONST_PHOTOS = 400 # number of photos of each type
y_train = []

#train data
data = DataFetch('orange',CONST_PHOTOS)
data1 = data.openPictures()
data = DataFetch('apple', CONST_PHOTOS)
data.removeErrorImages()
data2 = data.openPictures()

#test data
tdata = DataFetch('test-orange',30)
tdata1 = tdata.openPictures()
tdata = DataFetch('test-apple',30)
tdata2 = tdata.openPictures()

#add togheter data
X_train = data.connectData(data1,data2,'train')
y_train = data.getYtrain('train')
X_test = tdata.connectData(tdata1,tdata2,'test')
y_test = tdata.getYtrain('test')

# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

# normalize inputs from 0-255 to 0.0-1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0

#one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_train.shape[1] #number of categories

# Create the model
model = Sequential()
model.add(Conv2D(224, (11, 11), input_shape=(224, 224, 3), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(Conv2D(55, (5, 5), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
model.add(Conv2D(13, (3, 3), activation='relu', padding='same'))
model.add(Dropout(0.5))
model.add(Conv2D(13, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

# Compile model
epochs = 100
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
#print(model.summary())
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=10)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

#and then we save
# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))
# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")
</code>```

I used keras and tensorflow. Images are 224x224 pixels each split in 2 categories. I don't know very much about neural network, this being my first attempt to making one this big work. I heard it might be over fitting or maybe I need one more important layer, or maybe my batch-size/epochs/learn rate is wrong.

Any help is appreciated!

Edit1: How is the seed affecting the training of the network?
After training the accuracy is exactly 50% and by using a separate .py file which only loads the model and uses predict function on it returns the exact output percentage for any image I use. I tried with both images used for training and external ones.
I added the dataFetch code.

```<code>    #preparing the photos to be 224x224 and getting them from urls saved in txt files

from PIL import Image
import requests
from io import BytesIO
import numpy as np
import socket
import random
from scipy import misc
from PIL import ImageChops
import math, operator
from functools import reduce
import glob
import os
import signal

compare = Image.open('/home/mihai/PycharmProjects/neuralnet/compare.jpg')
compare1 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare1.jpg')
compare2 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare2.jpg')
compare3 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare3.jpg')
compare4 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare4.jpg')

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add, map(lambda h, i: h*(i**2), h, range(256))) / (float(im1.size[0]) * im1.size[1]))

class DataFetch:

    chosenFile = ''
    maxNumber = 0
    y_train = []
    y_test = []

    def __init__(self, choice, number):
        print('Images with '+choice+'s are being prepared')
        self.chosenFile = choice
        self.maxNumber = number

    def getPictures(self):
        imgArr = np.zeros((self.maxNumber, 224, 224, 3), dtype='uint8')
        count = 0
        class timeoutError(Exception):
            signal.alarm(0)
        def handler(signum, frame):
            raise timeoutError
        with open(self.chosenFile, "r") as ins:
            for line in ins:
                if count < self.maxNumber:
                    signal.signal(signal.SIGALRM, handler)
                    signal.alarm(3)
                    try:
                        try:
                            r = requests.get(line)
                            try:
                                img = Image.open(BytesIO(r.content))
                                ok = 0
                                try:
                                    if rmsdiff(compare, img) > 1.3 and rmsdiff(compare1, img) > 1.3 and rmsdiff(compare2, img) > 1.3 and rmsdiff(compare3, img) > 1.3 and rmsdiff(compare4, img) > 1.3:
                                        ok = 1
                                    else:
                                        print('Image removed from website')
                                except ValueError:
                                    ok = 1
                                if ok == 1:
                                    img = img.resize((224, 224))
                                    img = img.convert('RGB')
                                    img.save('/home/mihai/PycharmProjects/neuralnet/images/'+self.chosenFile+'/'+str(count)+".jpg", 'JPEG')
                                    imgArr[count, :, :, :] = img
                                    count = count + 1
                                    print(count)
                            except OSError:
                                print('Image not Available')
                        except socket.error:
                            print('URL not available')
                    except timeoutError:
                        print("URL not available")
        return imgArr

    def openPictures(self):
        cdir = os.getcwd()
        imgArr = np.zeros((self.maxNumber, 224, 224, 3), dtype='uint8')
        count = 0
        for filename in glob.glob(cdir+'/images/'+self.chosenFile+'/*.jpg'):
            if count < self.maxNumber:
                img = Image.open(filename)
                imgArr[count, :, :, :] = img
                count = count + 1
        return imgArr

    def removeErrorImages(self):
        cdir = os.getcwd()
        for filename in glob.glob(cdir+'/images/'+self.chosenFile+'/*.jpg'):
            img = Image.open(filename)
            try:
                if rmsdiff(compare, img) < 1.3 or rmsdiff(compare1, img) < 1.3 or rmsdiff(compare2, img) < 1.3 or rmsdiff(compare3, img) < 1.3 or rmsdiff(compare4, img) < 1.3:
                    os.remove(cdir+'/images/'+self.chosenFile+'/'+filename+'.jpg')
            except ValueError:
                pass

    def getYtrain(self,outParam):
        if outParam == 'train':
            self.y_train = np.reshape(self.y_train, (len(self.y_train), 1))
            return self.y_train
        else:
            self.y_test = np.reshape(self.y_test, (len(self.y_test), 1))
            return self.y_test

    def connectData(self, data1, data2, outParam):
        d1c = 0
        d2c = 0
        outList = []
        X_train = np.zeros((2 * self.maxNumber, 224, 224, 3), dtype='uint8')
        for i in range(2 * self.maxNumber):
            if d1c < self.maxNumber and d2c <self.maxNumber:
                if random.random() <= 0.5:
                    X_train[d1c + d2c, :, :, :] = data1[d1c, :, :, :]
                    d1c = d1c + 1
                    outList.append(0)
                else:
                    X_train[d1c + d2c, :, :, :] = data2[d2c, :, :, :]
                    d2c = d2c + 1
                    outList.append(1)
            else:
                if d1c < self.maxNumber:
                    X_train[d1c + d2c, :, :, :] = data1[d1c, :, :, :]
                    d1c = d1c + 1
                    outList.append(0)
                else:
                    if d2c < self.maxNumber:
                        X_train[d1c + d2c, :, :, :] = data2[d2c, :, :, :]
                        d2c = d2c + 1
                        outList.append(1)
        if outParam == 'train':
            self.y_train = outList
        else:
            if outParam == 'test':
                self.y_test = outList
        return X_train
</code>```

Code for predict:

```<code>#run this to test a sample

from keras.utils import np_utils
from keras.models import model_from_json
from keras.optimizers import SGD
from datasetFetch import DataFetch

# load json and create model
json_file = open('Data/model2.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model2.h5")
print("Loaded model from disk")

epochs = 100
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
loaded_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

#prepare X_test
tdata = DataFetch('test-orange',int(3))
tdata1 = tdata.openPictures()
tdata = DataFetch('test-apple',int(3))
tdata2 = tdata.openPictures()
X_test = tdata.connectData(tdata1,tdata2,'test')
y_test = tdata.getYtrain('test')
X_test = X_test.astype('float32')
X_test = X_test / 255.0
y_test = np_utils.to_categorical(y_test)
print('Number of samples to be tested: '+str(X_test.shape[0]))

scores = loaded_model.evaluate(X_test, y_test, verbose=0)
print(scores[1]*100)

score = loaded_model.predict(X_test,batch_size=6, verbose=1)
print(score) #prints percentages
</code>```

答:
The image preparation was correct. The problem was in the structure of the neural net plus the optimization method used.

Because of the huge number of neurons used for classifying just 2 classes, the structure was over fitting, causing the accuracy to stick at 50%.

The second problem was with the sgd optimizer. I instead used:

```<code>opt=keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']
</code>```

Hope this helps others as well!

Title: keras CNN same output

Body:
I have trained a CNN neural network in python with 800 samples and tested it on 60. The output accuracy is 50 and now every time I use model.predict it gives me the same result.

#main file - run this to train the network

import numpy as np
from keras.datasets import cifar10
from datasetFetch import DataFetch
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
import simplejson
from matplotlib import pyplot
from scipy.misc import toimage
# load data
#(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# create a grid of 3x3 images
#for i in range(0, 9):
#   pyplot.subplot(3,3,1 + i)
#   pyplot.imshow(toimage(X_train[i]))
# show the plot
#pyplot.show()

#init data
CONST_PHOTOS = 400 # number of photos of each type
y_train = []

#train data
data = DataFetch('orange',CONST_PHOTOS)
data1 = data.openPictures()
data = DataFetch('apple', CONST_PHOTOS)
data.removeErrorImages()
data2 = data.openPictures()

#test data
tdata = DataFetch('test-orange',30)
tdata1 = tdata.openPictures()
tdata = DataFetch('test-apple',30)
tdata2 = tdata.openPictures()

#add togheter data
X_train = data.connectData(data1,data2,'train')
y_train = data.getYtrain('train')
X_test = tdata.connectData(tdata1,tdata2,'test')
y_test = tdata.getYtrain('test')

# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

# normalize inputs from 0-255 to 0.0-1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0

#one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_train.shape[1] #number of categories

# Create the model
model = Sequential()
model.add(Conv2D(224, (11, 11), input_shape=(224, 224, 3), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(Conv2D(55, (5, 5), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
model.add(Conv2D(13, (3, 3), activation='relu', padding='same'))
model.add(Dropout(0.5))
model.add(Conv2D(13, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

# Compile model
epochs = 100
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
#print(model.summary())
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=10)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

#and then we save
# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))
# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

I used keras and tensorflow. Images are 224x224 pixels each split in 2 categories. I don't know very much about neural network, this being my first attempt to making one this big work. I heard it might be over fitting or maybe I need one more important layer, or maybe my batch-size/epochs/learn rate is wrong.

Any help is appreciated!

Edit1: How is the seed affecting the training of the network?
After training the accuracy is exactly 50% and by using a separate .py file which only loads the model and uses predict function on it returns the exact output percentage for any image I use. I tried with both images used for training and external ones.
I added the dataFetch code.

    #preparing the photos to be 224x224 and getting them from urls saved in txt files

from PIL import Image
import requests
from io import BytesIO
import numpy as np
import socket
import random
from scipy import misc
from PIL import ImageChops
import math, operator
from functools import reduce
import glob
import os
import signal

compare = Image.open('/home/mihai/PycharmProjects/neuralnet/compare.jpg')
compare1 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare1.jpg')
compare2 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare2.jpg')
compare3 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare3.jpg')
compare4 = Image.open('/home/mihai/PycharmProjects/neuralnet/compare4.jpg')

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add, map(lambda h, i: h*(i**2), h, range(256))) / (float(im1.size[0]) * im1.size[1]))

class DataFetch:

    chosenFile = ''
    maxNumber = 0
    y_train = []
    y_test = []

    def __init__(self, choice, number):
        print('Images with '+choice+'s are being prepared')
        self.chosenFile = choice
        self.maxNumber = number

    def getPictures(self):
        imgArr = np.zeros((self.maxNumber, 224, 224, 3), dtype='uint8')
        count = 0
        class timeoutError(Exception):
            signal.alarm(0)
        def handler(signum, frame):
            raise timeoutError
        with open(self.chosenFile, "r") as ins:
            for line in ins:
                if count < self.maxNumber:
                    signal.signal(signal.SIGALRM, handler)
                    signal.alarm(3)
                    try:
                        try:
                            r = requests.get(line)
                            try:
                                img = Image.open(BytesIO(r.content))
                                ok = 0
                                try:
                                    if rmsdiff(compare, img) > 1.3 and rmsdiff(compare1, img) > 1.3 and rmsdiff(compare2, img) > 1.3 and rmsdiff(compare3, img) > 1.3 and rmsdiff(compare4, img) > 1.3:
                                        ok = 1
                                    else:
                                        print('Image removed from website')
                                except ValueError:
                                    ok = 1
                                if ok == 1:
                                    img = img.resize((224, 224))
                                    img = img.convert('RGB')
                                    img.save('/home/mihai/PycharmProjects/neuralnet/images/'+self.chosenFile+'/'+str(count)+".jpg", 'JPEG')
                                    imgArr[count, :, :, :] = img
                                    count = count + 1
                                    print(count)
                            except OSError:
                                print('Image not Available')
                        except socket.error:
                            print('URL not available')
                    except timeoutError:
                        print("URL not available")
        return imgArr

    def openPictures(self):
        cdir = os.getcwd()
        imgArr = np.zeros((self.maxNumber, 224, 224, 3), dtype='uint8')
        count = 0
        for filename in glob.glob(cdir+'/images/'+self.chosenFile+'/*.jpg'):
            if count < self.maxNumber:
                img = Image.open(filename)
                imgArr[count, :, :, :] = img
                count = count + 1
        return imgArr

    def removeErrorImages(self):
        cdir = os.getcwd()
        for filename in glob.glob(cdir+'/images/'+self.chosenFile+'/*.jpg'):
            img = Image.open(filename)
            try:
                if rmsdiff(compare, img) < 1.3 or rmsdiff(compare1, img) < 1.3 or rmsdiff(compare2, img) < 1.3 or rmsdiff(compare3, img) < 1.3 or rmsdiff(compare4, img) < 1.3:
                    os.remove(cdir+'/images/'+self.chosenFile+'/'+filename+'.jpg')
            except ValueError:
                pass

    def getYtrain(self,outParam):
        if outParam == 'train':
            self.y_train = np.reshape(self.y_train, (len(self.y_train), 1))
            return self.y_train
        else:
            self.y_test = np.reshape(self.y_test, (len(self.y_test), 1))
            return self.y_test

    def connectData(self, data1, data2, outParam):
        d1c = 0
        d2c = 0
        outList = []
        X_train = np.zeros((2 * self.maxNumber, 224, 224, 3), dtype='uint8')
        for i in range(2 * self.maxNumber):
            if d1c < self.maxNumber and d2c <self.maxNumber:
                if random.random() <= 0.5:
                    X_train[d1c + d2c, :, :, :] = data1[d1c, :, :, :]
                    d1c = d1c + 1
                    outList.append(0)
                else:
                    X_train[d1c + d2c, :, :, :] = data2[d2c, :, :, :]
                    d2c = d2c + 1
                    outList.append(1)
            else:
                if d1c < self.maxNumber:
                    X_train[d1c + d2c, :, :, :] = data1[d1c, :, :, :]
                    d1c = d1c + 1
                    outList.append(0)
                else:
                    if d2c < self.maxNumber:
                        X_train[d1c + d2c, :, :, :] = data2[d2c, :, :, :]
                        d2c = d2c + 1
                        outList.append(1)
        if outParam == 'train':
            self.y_train = outList
        else:
            if outParam == 'test':
                self.y_test = outList
        return X_train

Code for predict:

#run this to test a sample

from keras.utils import np_utils
from keras.models import model_from_json
from keras.optimizers import SGD
from datasetFetch import DataFetch

# load json and create model
json_file = open('Data/model2.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model2.h5")
print("Loaded model from disk")

epochs = 100
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
loaded_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

#prepare X_test
tdata = DataFetch('test-orange',int(3))
tdata1 = tdata.openPictures()
tdata = DataFetch('test-apple',int(3))
tdata2 = tdata.openPictures()
X_test = tdata.connectData(tdata1,tdata2,'test')
y_test = tdata.getYtrain('test')
X_test = X_test.astype('float32')
X_test = X_test / 255.0
y_test = np_utils.to_categorical(y_test)
print('Number of samples to be tested: '+str(X_test.shape[0]))

scores = loaded_model.evaluate(X_test, y_test, verbose=0)
print(scores[1]*100)

score = loaded_model.predict(X_test,batch_size=6, verbose=1)
print(score) #prints percentages

Body:
The image preparation was correct. The problem was in the structure of the neural net plus the optimization method used.

Because of the huge number of neurons used for classifying just 2 classes, the structure was over fitting, causing the accuracy to stick at 50%.

The second problem was with the sgd optimizer. I instead used:

opt=keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']

Hope this helps others as well!