问:
file upload in react and node js not working
i am trying very hard to upload file but no way i could find a clear solution .
i have tried many ways but not working .  Now the console shows me 200 and give me message that file is uploaded but file is not going in the folder . i ahve checked file size limit and folder is ok but dont know why its not working. could any help please.

///react component

```<code> import { saveBasicUser, getOneBasicUser, uploadFile } from
 '../../actions/basicAction';

 this.state = { file: []};

 handleChange(event) {

 this.setState({
 [event.target.name]: event.target.value,
 file:
 event.target.files})
 }

 handleSubmit(event) {
 event.preventDefault();
   var file = this.state.file

    let formData = new FormData();
    formData.append('file', file);

    // console.log(obj);
    console.log(formData);

    //  this.props.dispatch(saveBasicUser(obj ))
     this.props.dispatch(uploadFile(formData ))
  }

<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" name = "file" onChange={this.handleChange} />
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</code>```

////////action part

```<code> export function uploadFile(formData) {
  console.log(formData)
  return (dispatch) => {

    return axios.post('/upload_file', {
      headers: { 'content-type': 'multipart/form-data' },
      data: formData
    }).then(function (res) {

      console.log(res)
    }).catch(function (err) {
      console.log(" err")
      console.log(err)
    })
  }
}
</code>```

//////server part

```<code>var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './uploads')
},
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file');

app.post('/upload_file', function(req, res){

        upload(req, res, function(err) {
          if(err) {
              return res.end("Error uploading file.");
          }
          res.end("File is uploaded");
      });

  });
</code>```

答:
I have found the solution at last.

react JS

```<code>import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getOneBasicUser ,uploadFile} from '../../actions/basicAction';
//--------------------------------------------------------------------------
class Upload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleFile = this.handleFile.bind(this);
      }
      //--------------------------------------------------------------------
      //--------------------------------------------------------------------------
      handleChange(event) {
        this.setState({
          [event.target.name]: event.target.value
        });
      }
      //--------------------------------------------------------------------------
      handleFile(e) {

            e.preventDefault();

            var id = this.props.params.id;

            console.log(id);

            var formData = new FormData($('form')[0]);

            var isFileExist = !!$('input[type=file]')[0].files[0];

            if (isFileExist) {

                $.ajax({

                    url:  '/upload_file/'+ id,

                    type: 'POST',

                    data: formData,

                    xhr: function () {

                        var xhr = new window.XMLHttpRequest();

                        xhr.upload.addEventListener("progress", function (e) {

                            if (e.lengthComputable) {

                                $('progress').attr({value: e.loaded, max: e.total});

                                $('#status').empty().text(parseInt((e.loaded / e.total * 100)) + '%');

                            }

                        }, false);

                        return xhr;

                    }.bind(this),

                    success: function (data) {

                        this.setState({

                            data: data

                        });

                        $('#status').empty().text('File Uploaded!');

                    }.bind(this),

                    error: function (xhr, status, err) {

                        console.log( err);

                    }.bind(this),

                    cache: false,

                    contentType: false,

                    processData: false

                });

            } else {

                $('#status').empty().text('Please choose the file.');

            }

            }
      //--------------------------------------------------------------------------
      render() {

        return (
          <div className="container ca-container">
            <div className="row">
              <div className="col-md-12">
                <h2> Upload File </h2>
                <hr />
              </div>
            </div>
               <form onSubmit={this.handleFile} encType="multipart/form-data">
              <div className="row">
                <div className="col-md-12">
                <div className="col-md-6">
                <h3 id="status" className ="label label-success"></h3>
                <div className="form-group">
                      <label>
                        Name:
                   </label>
                      <input  type="file" className="form-control" name="BasicUserFile"  onChange={this.handleChange} placeholder="file" />
                    </div>
                  <div className="btn-group" role="group">
                  <button type="submit" value="Upload File" className="btn btn-success btn-lg">Upload</button>
                  </div>
                  </div>

                </div>
              </div>
            </form>
          </div>
        );
      }

}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
  return {
    //basicUser: state.basicUser.basicUser

  };
};

export default connect(mapStateToProps)(Upload);
</code>```

////server.js

```<code>var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './uploads')
},
  filename: function (req, file, cb) {
    var basic_id = req.params.id
    cb(null, file.fieldname + '-' + basic_id+ path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('BasicUserFile');

app.post('/upload_file/:id', function(req, res){

  console.log("000000000000000000000000000000000000000000000000")

  console.log(req.params)

  console.log("000000000000000000000000000000000000000000000000")

        upload(req, res, function(err) {
          if(err) {
              return res.end("Error uploading file.");
          }
          res.end("File is uploaded");
      });

  });
</code>```

Body:
i am trying very hard to upload file but no way i could find a clear solution .
i have tried many ways but not working .  Now the console shows me 200 and give me message that file is uploaded but file is not going in the folder . i ahve checked file size limit and folder is ok but dont know why its not working. could any help please.

///react component

 import { saveBasicUser, getOneBasicUser, uploadFile } from
 '../../actions/basicAction';

 this.state = { file: []};

 handleChange(event) {

 this.setState({
 [event.target.name]: event.target.value,
 file:
 event.target.files})
 }

 handleSubmit(event) {
 event.preventDefault();
   var file = this.state.file

    let formData = new FormData();
    formData.append('file', file);

    // console.log(obj);
    console.log(formData);

    //  this.props.dispatch(saveBasicUser(obj ))
     this.props.dispatch(uploadFile(formData ))
  }

<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" name = "file" onChange={this.handleChange} />
<button type="submit" className="btn btn-success btn-lg">Submit</button>

////////action part

 export function uploadFile(formData) {
  console.log(formData)
  return (dispatch) => {

    return axios.post('/upload_file', {
      headers: { 'content-type': 'multipart/form-data' },
      data: formData
    }).then(function (res) {

      console.log(res)
    }).catch(function (err) {
      console.log(" err")
      console.log(err)
    })
  }
}

//////server part

var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './uploads')
},
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file');

app.post('/upload_file', function(req, res){

        upload(req, res, function(err) {
          if(err) {
              return res.end("Error uploading file.");
          }
          res.end("File is uploaded");
      });

  });

Body:
I have found the solution at last.

react JS

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getOneBasicUser ,uploadFile} from '../../actions/basicAction';
//--------------------------------------------------------------------------
class Upload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleFile = this.handleFile.bind(this);
      }
      //--------------------------------------------------------------------
      //--------------------------------------------------------------------------
      handleChange(event) {
        this.setState({
          [event.target.name]: event.target.value
        });
      }
      //--------------------------------------------------------------------------
      handleFile(e) {

            e.preventDefault();

            var id = this.props.params.id;

            console.log(id);

            var formData = new FormData($('form')[0]);

            var isFileExist = !!$('input[type=file]')[0].files[0];

            if (isFileExist) {

                $.ajax({

                    url:  '/upload_file/'+ id,

                    type: 'POST',

                    data: formData,

                    xhr: function () {

                        var xhr = new window.XMLHttpRequest();

                        xhr.upload.addEventListener("progress", function (e) {

                            if (e.lengthComputable) {

                                $('progress').attr({value: e.loaded, max: e.total});

                                $('#status').empty().text(parseInt((e.loaded / e.total * 100)) + '%');

                            }

                        }, false);

                        return xhr;

                    }.bind(this),

                    success: function (data) {

                        this.setState({

                            data: data

                        });

                        $('#status').empty().text('File Uploaded!');

                    }.bind(this),

                    error: function (xhr, status, err) {

                        console.log( err);

                    }.bind(this),

                    cache: false,

                    contentType: false,

                    processData: false

                });

            } else {

                $('#status').empty().text('Please choose the file.');

            }

            }
      //--------------------------------------------------------------------------
      render() {

        return (
          <div className="container ca-container">
            <div className="row">
              <div className="col-md-12">
                <h2> Upload File </h2>
                <hr />
              </div>
            </div>
               <form onSubmit={this.handleFile} encType="multipart/form-data">
              <div className="row">
                <div className="col-md-12">
                <div className="col-md-6">
                <h3 id="status" className ="label label-success"></h3>
                <div className="form-group">
                      <label>
                        Name:
                   </label>
                      <input  type="file" className="form-control" name="BasicUserFile"  onChange={this.handleChange} placeholder="file" />
                    </div>
                  <div className="btn-group" role="group">
                  <button type="submit" value="Upload File" className="btn btn-success btn-lg">Upload</button>
                  </div>
                  </div>

                </div>
              </div>
            </form>
          </div>
        );
      }

}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
  return {
    //basicUser: state.basicUser.basicUser

  };
};

export default connect(mapStateToProps)(Upload);

////server.js

var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './uploads')
},
  filename: function (req, file, cb) {
    var basic_id = req.params.id
    cb(null, file.fieldname + '-' + basic_id+ path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('BasicUserFile');

app.post('/upload_file/:id', function(req, res){

  console.log("000000000000000000000000000000000000000000000000")

  console.log(req.params)

  console.log("000000000000000000000000000000000000000000000000")

        upload(req, res, function(err) {
          if(err) {
              return res.end("Error uploading file.");
          }
          res.end("File is uploaded");
      });

  });


来源: stackexchange

问:
Universal Image Loader Library error with android studio on android 5.0.1
Universal Image Loader Library thought this crash while initializing in android studio on huawei device with android os version 5.0.1

Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.nostra13.universalimageloader.core.ImageLoaderConfiguration$Builder"
  on path: DexPathList[[zip file
  "/data/app/com.q8car.andriod.activity-2/base.apk", zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_dependencies_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_0_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_1_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_2_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_3_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_4_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_5_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_6_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_7_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_8_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.q8car.andriod.activity-2/lib/arm,
  /vendor/lib, /system/lib]]

my gradle file is as following

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

buildscript {
    repositories {
        mavenCentral()
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.mutualmobile.gradle.plugins:dexinfo:0.1.2'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 16
        multiDexEnabled = true
        ndk {
            abiFilter "armeabi-v7a"
        }

    }
    buildTypes {
        debug {
            debuggable true
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {

        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/dependencies'
        exclude 'META-INF/license'
        exclude 'META-INF/notice'
        exclude 'META-INF/LGPL2.1'
        exclude 'lib/armeabi-v7a/libblasV8.so'
    }

    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['libs']
        }
    }
    productFlavors {
    }
}

repositories {

    mavenCentral()
    jcenter()
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    // modules
    compile project(':ffmpeg4android')
    // sdks
    //compile 'com.android.support:multidex:1.0.2'
    compile 'com.danikula:videocache:2.3.4'
    compile 'com.android.support:support-v4:27.0.0'
    compile 'com.android.support:support-annotations:27.0.0'
    compile 'com.android.support:appcompat-v7:27.0.0'
    compile 'com.android.support:recyclerview-v7:27.0.0'
    compile 'com.android.support:cardview-v7:27.0.0'
    compile 'com.android.support:support-v13:27.0.0'

    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
}
</code>```

答: I have solved it by download library zip file and include it as module in my project , also I am not facing any problem now when I disable instant run in android studio</p>

ContentLicense: CC BY-SA 3.0

Body:
Universal Image Loader Library thought this crash while initializing in android studio on huawei device with android os version 5.0.1

Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.nostra13.universalimageloader.core.ImageLoaderConfiguration$Builder"
  on path: DexPathList[[zip file
  "/data/app/com.q8car.andriod.activity-2/base.apk", zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_dependencies_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_0_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_1_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_2_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_3_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_4_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_5_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_6_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_7_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_8_apk.apk",
  zip file
  "/data/app/com.q8car.andriod.activity-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.q8car.andriod.activity-2/lib/arm,
  /vendor/lib, /system/lib]]

my gradle file is as following

apply plugin: 'com.android.library'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.mutualmobile.gradle.plugins:dexinfo:0.1.2'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 16
        multiDexEnabled = true
        ndk {
            abiFilter "armeabi-v7a"
        }

    }
    buildTypes {
        debug {
            debuggable true
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {

        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/dependencies'
        exclude 'META-INF/license'
        exclude 'META-INF/notice'
        exclude 'META-INF/LGPL2.1'
        exclude 'lib/armeabi-v7a/libblasV8.so'
    }

    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['libs']
        }
    }
    productFlavors {
    }
}

repositories {

    mavenCentral()
    jcenter()
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    // modules
    compile project(':ffmpeg4android')
    // sdks
    //compile 'com.android.support:multidex:1.0.2'
    compile 'com.danikula:videocache:2.3.4'
    compile 'com.android.support:support-v4:27.0.0'
    compile 'com.android.support:support-annotations:27.0.0'
    compile 'com.android.support:appcompat-v7:27.0.0'
    compile 'com.android.support:recyclerview-v7:27.0.0'
    compile 'com.android.support:cardview-v7:27.0.0'
    compile 'com.android.support:support-v13:27.0.0'

    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
}


问:
What could possibly cause JQuery's selector to break?
I am trying to get an element using JQuery's selector, but it does not find it even though the element actually exists. Moreover, I can actually find the element using getElementById.

For example:

$('#outputDiv') gives me a null value. But document.getElementById("outputDiv") returns me the Div I was trying to access.

Any idea?

答:
If you're using IE7 the order of when things happen are very important, and selectors don't tend to work for dynamically generated content if the jQuery script is declared beforehand, i.e. in the head element.

A way we got around this was to place the code at the end of the document.  As weird as this sounds, it is documented by MS as a bug that's existed for many years.

OwnerDisplayName: Marcel Tjandraatmadja

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Marcel Tjandraatmadja

OwnerDisplayName: Kezzer


问:
Access Drupal's Voting API from theme
I'm a king of a noob in drupal.
I'm trying to use Voting API and Advanced Pool module, now I'm customizing node-advpoll_binary.tpl.php template, and i can access only the total votes.
I'd like to know how get the poll results for each answer in order to calculate percentage results.
Does anyone have the solution??</p>

答: You don't typically want to do calculations in the theme layer. You may be able to output the numbers you're looking for using the Views module.</p>

Title: Access Drupal's Voting API from theme


问:
How do I make my WritableRaster and pixelsize bigger in java?
I have a txt file with nrows, ncols etc and ex elevation values as numbers which we are supposed to make a map image of.

I have code (that works) but my problem is that the pixels are exactly one pixel big each, they actually have  a cellsize also that already is defined(10m). When the code runs I get the smallest greyscale map ever, I want it to be atleast 10x10 cm big imageicon so I can se what's going on but I don't know where to set it please help. Already searched for ways to resize etc but noone really fit me, what about a setpixels solution?

```<code>public void mapColor()
{
    int height = nRows; int width = nCols;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            double value = values[i][j];
            int[] color = new int[3];
            int colValue = getColorValue(value); //In this case Green to Red strength
            int percentage = ((100*colValue)/255);
            int R; int G; int B = 0;
            //Formula: Red= 255*percentage /100 G= (255*(100-percentage))/100
            R = (255*percentage)/100; G=(255*(100-percentage))/100;
            R = Math.round(R); G= Math.round(G);
            color[0]= R; color[1] = G; color[2] = B; //100% will be bright red and 50% yellow
            raster.setPixel(j, i, color);
            //System.out.println("Value " + value + " Red is " + R + " Green is " + G);
        }
    }

    JFrame jf = new JFrame();
    JLabel jl = new JLabel();
    ImageIcon ii = new ImageIcon(image);
    jl.setIcon(ii);
    jf.add(jl);
    jf.setSize(200, 200);
    jf.setVisible(true);
}
</code>```

This returns an image that is 2x2mm big, values is a double array with all elevation data. It's my first java course ever I want easy solutions.

答:
The most simple solution would be to use the getScaledInstance method
and use the resulting image to create the ImageIcon:

```<code>Image scaledImage = image.getScaledInstance(200 * nRows, 200 * nCols, Image.SCALE_DEFAULT);
ImageIcon ii = new ImageIcon(scaledImage);
</code>```

Body:
I have a txt file with nrows, ncols etc and ex elevation values as numbers which we are supposed to make a map image of.

I have code (that works) but my problem is that the pixels are exactly one pixel big each, they actually have  a cellsize also that already is defined(10m). When the code runs I get the smallest greyscale map ever, I want it to be atleast 10x10 cm big imageicon so I can se what's going on but I don't know where to set it please help. Already searched for ways to resize etc but noone really fit me, what about a setpixels solution?

public void mapColor()
{
    int height = nRows; int width = nCols;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            double value = values[i][j];
            int[] color = new int[3];
            int colValue = getColorValue(value); //In this case Green to Red strength
            int percentage = ((100*colValue)/255);
            int R; int G; int B = 0;
            //Formula: Red= 255*percentage /100 G= (255*(100-percentage))/100
            R = (255*percentage)/100; G=(255*(100-percentage))/100;
            R = Math.round(R); G= Math.round(G);
            color[0]= R; color[1] = G; color[2] = B; //100% will be bright red and 50% yellow
            raster.setPixel(j, i, color);
            //System.out.println("Value " + value + " Red is " + R + " Green is " + G);
        }
    }

    JFrame jf = new JFrame();
    JLabel jl = new JLabel();
    ImageIcon ii = new ImageIcon(image);
    jl.setIcon(ii);
    jf.add(jl);
    jf.setSize(200, 200);
    jf.setVisible(true);
}

This returns an image that is 2x2mm big, values is a double array with all elevation data. It's my first java course ever I want easy solutions.

Body:
The most simple solution would be to use the getScaledInstance method
and use the resulting image to create the ImageIcon:

Image scaledImage = image.getScaledInstance(200 * nRows, 200 * nCols, Image.SCALE_DEFAULT);
ImageIcon ii = new ImageIcon(scaledImage);


问:
Using BufferedWriter to get input from the user and write it to a file
I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)

```<code>package bufferedreader;
import java.io.*;
import java.util.Scanner;

public class BufferedReader {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
   writeToFile("morescores");
   processFile("morescores");
}

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
    int score = 1;
   while (true) {
   Scanner reader = new Scanner(System.in);
        System.out.print ("Enter a number: ");
       score = reader.nextInt();
        if (score < 0) {
            break;
       } else {
          outputWriter.write(score);
          outputWriter.newLine();
    }
    }
   outputWriter.flush();
   outputWriter.close();
}

public static void processFile2 (String filename) throws IOException {
    java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
    String line;
    while ((line = inputReader.readLine()) != null) {
        System.out.println (line);
    }
    inputReader.close();
}

}
</code>```

UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string.  I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value

答:
Convert your int to a String before writing to your file so

```<code>outputWriter.write(score);
</code>```

would be:

```<code>outputWriter.write(String.valueOf(score));
</code>```

if you are wondering why it has to be converted first look at the doc:
https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html#write(int)

you'll see that it doesn't write the int but the character represented by the int

Body:
I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)

package bufferedreader;
import java.io.*;
import java.util.Scanner;

public class BufferedReader {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
   writeToFile("morescores");
   processFile("morescores");
}

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
    int score = 1;
   while (true) {
   Scanner reader = new Scanner(System.in);
        System.out.print ("Enter a number: ");
       score = reader.nextInt();
        if (score < 0) {
            break;
       } else {
          outputWriter.write(score);
          outputWriter.newLine();
    }
    }
   outputWriter.flush();
   outputWriter.close();
}

public static void processFile2 (String filename) throws IOException {
    java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
    String line;
    while ((line = inputReader.readLine()) != null) {
        System.out.println (line);
    }
    inputReader.close();
}

}

UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string.  I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value

Body:
Convert your int to a String before writing to your file so

outputWriter.write(score);

would be:

outputWriter.write(String.valueOf(score));

if you are wondering why it has to be converted first look at the doc:
https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html#write(int)

you'll see that it doesn't write the int but the character represented by the int


问:
CakePHP Migration Creating a new table causes duplicate column name
I created a new Migration script on CakePHP 3 using the following command

```<code>bin/cake bake migration CreateOfficialTeams id:int name:string topic_id:int
</code>```

The id field should be the primary key, and topic_id is a foreign key. The script comes out like I want, except topic_id is a string for some reason, but I manually fix that.

When I attempt to run the script I get an error stating:

```<code>Exception: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' in [/home/bradygp/workspace/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php, line 306]
2017-02-27 21:52:16 Error [PDOException] SQLSTATE[45S21]: Column already exists: 1060 Duplicate column name 'id'
</code>```

I have other tables with a column name of 'id', but this is a new table, called with the create() function,

答:
The primary key column named id will be added implicitly. CakePHpp 3
For more detail you can visit on
Cakephp Migration overview</p>

Body:
I created a new Migration script on CakePHP 3 using the following command

bin/cake bake migration CreateOfficialTeams id:int name:string topic_id:int

The id field should be the primary key, and topic_id is a foreign key. The script comes out like I want, except topic_id is a string for some reason, but I manually fix that.

When I attempt to run the script I get an error stating:

Exception: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' in [/home/bradygp/workspace/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php, line 306]
2017-02-27 21:52:16 Error [PDOException] SQLSTATE[45S21]: Column already exists: 1060 Duplicate column name 'id'

I have other tables with a column name of 'id', but this is a new table, called with the create() function,


问:
Javascript: Flatten any array values within object (nested)
I would like to flatten any array values within an object e.g. like sample below. The solution should not just apply to ecommerce but literally anything that could be in the object as an array type. Example:

```<code>var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [
      {
        brand: "apple",
        category: "phone"
      },
      {
        brand: "google",
        category: "services"
      }
    ]
  }
};
</code>```

And I would like the output to be:

```<code>{
  price: "999",
  description: "..."
  ecommerce: {
    products_1: {
      brand: "apple",
      category: "phone"
    },
    products_2: {
      brand: "google",
      category: "services"
    }
  }
}
</code>```

What is the most efficient way to do this in JavaScript (ES6/7)?

Thanks in advance!

Updated due to comment and several minuses!!! Would be nice if those who were so quick to click minuses when the question was initially asked would revoke it!

I've tried this its completely wrong and I'm also sure theres a better functional way of doing this:

```<code>function flattenArray(array) {

  var obj = array.reduce((acc, cur, i) => {
    acc[i] = cur;
    return acc;
  }, {});

  return obj;
}

function cleanObject(object) {
  for (let key in object) {
    let testObject = object[key];

    if (Array.isArray(testObject)) {
      testObject = flattenArray(testObject)
    } else if (typeof(testObject) === 'object') {
      testObject = cleanObject(testObject);
    }

    return testObject;
  }

  return object;
}

var clean = cleanObject(sample);
</code>```

UPDATE 2: seeing as both solutions were so fixated on ecommerce how would the solution work if the next object was:

```<code>var sample = {
  price: "999",
  description: "...",
  differentArray: [
    {
      brand: "apple",
      category: "phone"
    },
    {
      brand: "google",
      category: "services"
    }
  ]
};
</code>```

Notice that not only is this different key its also at a different nesting level too.

答:
A recursively applied Array#reduce based approach does the job for this kind of key-value bags, ... a first generic solution then might look like this one ...

function recursivelyMapArrayItemsToGenericKeys(collector, key) {
  var
    source  = collector.source,
    target  = collector.target,
    type    = source[key];

  if (Array.isArray(type)) {
    type.forEach(function (item, idx) {
      var
        keyList     = Object.keys(item || ''),
        genericKey  = [key, idx].join('_');

      if (keyList.length >= 1) {
        target[genericKey] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

          source: item,
          target: {}

        }).target;
      } else {
        target[genericKey] = item;
      }
    });
  } else if (typeof type !== 'string') {
    var keyList = Object.keys(type || '');

    if (keyList.length >= 1) {
      target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

        source: type,
        target: {}

      }).target;
    } else {
      target[key] = type;
    }
  } else {
    target[key] = type;
  }
  return collector;
}

var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [{
      brand: "apple",
      category: "phone"
    }, {
      brand: "google",
      category: "services"
    }, {
      foo: [{
        brand: "bar",
        category: "biz"
      }, {
        brand: "baz",
        category: "biz"
      }]
    }]
  }
};

var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {

  source: sample,
  target: {}

}).target;

console.log('sample : ', sample);
console.log('result : ', result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100%!important; top: 0; }</code>```

... within a next code sanitizing step one might get rid of duplicated logic, thus ending up with two functions and an alternating/reciprocal recursion ...

function recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key) {
  if (keyList.length >= 1) {
    target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

      source: type,
      target: {}

    }).target;
  } else {
    target[key] = type;
  }
}

function recursivelyMapArrayItemsToGenericKeys(collector, key) {
  var
    source  = collector.source,
    target  = collector.target,
    type    = source[key];

  if (Array.isArray(type)) {
    type.forEach(function (item, idx) {
      var
        keyList     = Object.keys(item || ''),
        genericKey  = [key, idx].join('_');

      recursivelyAssignItemsFromTypeByKeys(target, item, keyList, genericKey);
    });
  } else if (typeof type !== 'string') {
    var keyList = Object.keys(type || '');

    recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key);
  } else {
    target[key] = type;
  }
  return collector;
}

var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [{
      brand: "apple",
      category: "phone"
    }, {
      brand: "google",
      category: "services"
    }, {
      foo: [{
        brand: "bar",
        category: "biz"
      }, {
        brand: "baz",
        category: "biz"
      }]
    }]
  }
};

var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {

  source: sample,
  target: {}

}).target;

console.log('sample : ', sample);
console.log('result : ', result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100%!important; top: 0; }</code>```

Body:
I would like to flatten any array values within an object e.g. like sample below. The solution should not just apply to ecommerce but literally anything that could be in the object as an array type. Example:

var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [
      {
        brand: "apple",
        category: "phone"
      },
      {
        brand: "google",
        category: "services"
      }
    ]
  }
};

And I would like the output to be:

{
  price: "999",
  description: "..."
  ecommerce: {
    products_1: {
      brand: "apple",
      category: "phone"
    },
    products_2: {
      brand: "google",
      category: "services"
    }
  }
}

What is the most efficient way to do this in JavaScript (ES6/7)?

Thanks in advance!

Updated due to comment and several minuses!!! Would be nice if those who were so quick to click minuses when the question was initially asked would revoke it!

I've tried this its completely wrong and I'm also sure theres a better functional way of doing this:

function flattenArray(array) {

  var obj = array.reduce((acc, cur, i) => {
    acc[i] = cur;
    return acc;
  }, {});

  return obj;
}

function cleanObject(object) {
  for (let key in object) {
    let testObject = object[key];

    if (Array.isArray(testObject)) {
      testObject = flattenArray(testObject)
    } else if (typeof(testObject) === 'object') {
      testObject = cleanObject(testObject);
    }

    return testObject;
  }

  return object;
}

var clean = cleanObject(sample);

UPDATE 2: seeing as both solutions were so fixated on ecommerce how would the solution work if the next object was:

var sample = {
  price: "999",
  description: "...",
  differentArray: [
    {
      brand: "apple",
      category: "phone"
    },
    {
      brand: "google",
      category: "services"
    }
  ]
};

Notice that not only is this different key its also at a different nesting level too.

Body:
A recursively applied Array#reduce based approach does the job for this kind of key-value bags, ... a first generic solution then might look like this one ...

function recursivelyMapArrayItemsToGenericKeys(collector, key) {
  var
    source  = collector.source,
    target  = collector.target,
    type    = source[key];

  if (Array.isArray(type)) {
    type.forEach(function (item, idx) {
      var
        keyList     = Object.keys(item || ''),
        genericKey  = [key, idx].join('_');

      if (keyList.length >= 1) {
        target[genericKey] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

          source: item,
          target: {}

        }).target;
      } else {
        target[genericKey] = item;
      }
    });
  } else if (typeof type !== 'string') {
    var keyList = Object.keys(type || '');

    if (keyList.length >= 1) {
      target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

        source: type,
        target: {}

      }).target;
    } else {
      target[key] = type;
    }
  } else {
    target[key] = type;
  }
  return collector;
}

var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [{
      brand: "apple",
      category: "phone"
    }, {
      brand: "google",
      category: "services"
    }, {
      foo: [{
        brand: "bar",
        category: "biz"
      }, {
        brand: "baz",
        category: "biz"
      }]
    }]
  }
};

var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {

  source: sample,
  target: {}

}).target;

console.log('sample : ', sample);
console.log('result : ', result);

.as-console-wrapper { max-height: 100%!important; top: 0; }

... within a next code sanitizing step one might get rid of duplicated logic, thus ending up with two functions and an alternating/reciprocal recursion ...

function recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key) {
  if (keyList.length >= 1) {
    target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {

      source: type,
      target: {}

    }).target;
  } else {
    target[key] = type;
  }
}

function recursivelyMapArrayItemsToGenericKeys(collector, key) {
  var
    source  = collector.source,
    target  = collector.target,
    type    = source[key];

  if (Array.isArray(type)) {
    type.forEach(function (item, idx) {
      var
        keyList     = Object.keys(item || ''),
        genericKey  = [key, idx].join('_');

      recursivelyAssignItemsFromTypeByKeys(target, item, keyList, genericKey);
    });
  } else if (typeof type !== 'string') {
    var keyList = Object.keys(type || '');

    recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key);
  } else {
    target[key] = type;
  }
  return collector;
}

var sample = {
  price: "999",
  description: "...",
  ecommerce: {
    products: [{
      brand: "apple",
      category: "phone"
    }, {
      brand: "google",
      category: "services"
    }, {
      foo: [{
        brand: "bar",
        category: "biz"
      }, {
        brand: "baz",
        category: "biz"
      }]
    }]
  }
};

var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {

  source: sample,
  target: {}

}).target;

console.log('sample : ', sample);
console.log('result : ', result);

.as-console-wrapper { max-height: 100%!important; top: 0; }


问:
Layout doesn't move up enough when clicking EditText
The view does move up when clicking in the EditText. But it doesn't move up enough. It should move up to someId, below someId the button should be displayed and below that the keyboard should be shown. Why doesn't this work?

Androidmanifest:

```<code><activity android:name=".MainActivity" android:windowSoftInputMode="adjustResize">
</code>```

activity_main:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:background="@android:color/holo_red_dark" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="132dp"
                android:padding="8dp"
                android:background="@android:color/holo_green_dark"/>

            <View
                android:id="@+id/someId"
                android:layout_width="match_parent"
                android:layout_height="20dp" />

        </LinearLayout>

    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_send"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="0dp"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:clickable="false"
            android:text="Test"
            android:textColor="@color/defaultGreen"
            android:textSize="18sp" />

    </LinearLayout>
</RelativeLayout>
</code>```

答:
How about scrolling to bottom on view changed</p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  final EditText editText = (EditText) findViewById(R.id.editText);
  final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);

  editText.getRootView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
      //Scroll to bottom of view
      scrollView.smoothScrollTo(0, editText.getBottom());
    }
  });

}
</code>```

Body:
The view does move up when clicking in the EditText. But it doesn't move up enough. It should move up to someId, below someId the button should be displayed and below that the keyboard should be shown. Why doesn't this work?

Androidmanifest:

<activity android:name=".MainActivity" android:windowSoftInputMode="adjustResize">

activity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:background="@android:color/holo_red_dark" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="132dp"
                android:padding="8dp"
                android:background="@android:color/holo_green_dark"/>

            <View
                android:id="@+id/someId"
                android:layout_width="match_parent"
                android:layout_height="20dp" />

        </LinearLayout>

    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_send"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="0dp"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:clickable="false"
            android:text="Test"
            android:textColor="@color/defaultGreen"
            android:textSize="18sp" />

    </LinearLayout>
</RelativeLayout>

Body:
How about scrolling to bottom on view changed

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  final EditText editText = (EditText) findViewById(R.id.editText);
  final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);

  editText.getRootView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
      //Scroll to bottom of view
      scrollView.smoothScrollTo(0, editText.getBottom());
    }
  });

}


问:
Periodic data doesn't seem periodic when plotted as a surface
I am simulating a problem where a wave is incident upon a multi-layered sphere.

I have a variable named forceZ1 which is a function of two other variables named phase and frequency. I have solved an equation and found the matrix for forceZ1. Also I know that frequency is a 1*3000 matrix and phase is the same size. So obviously forceZ1 will be 3000*3000.

In this case the phase is changing between 0 and 2*pi and based on the data, I got that the force should be periodic with a period of 2π. This can be verified by plotting any column vector in forceZ1 with respect to the angle, e.g.

```<code>figure(); plot(ang1, forceZ1(:,567));
</code>```

Which gives:

I tried to draw a surface forceZ1 vs. frequency and phase but the figure does not show the periodic behavior. What am I doing wrong?

Here's my plotting code:

```<code>Z=forceZ1;
X=ang1;
Y=frequency;

figure
surf(X,Y,Z,'edgecolor','none')
shading interp
view(3)
xlim([0,2*pi]);
xlabel('X=phase')
ylabel('Y=nondimensional frequency')
zlabel('Z=force in Z direction')
title('Force-Frequency-Phase')
colormap jet
</code>```

I uploaded a .mat file of my data for your reference.

答:
It seems like your forceZ1 matrix got transposed somewhere along the way. The data is indeed periodic, as you said, but the direction of the periodicity is your Y axis.

It will start making sense if you plot your data like this:

```<code>surf(X,Y,Z.','edgecolor','none');
</code>```

... leading to:

However, since your data contains harmonics differing by phase, magnitude and offset, you might want to try using a different type of chart that would accentuate the shapes of the harmonics, such as ribbon:

```<code>figure(); ribbon(Z(1:40:end,1:100:end));
</code>```

... or try to make an animation, or an interactive chart using a slider for the shown frequency.

Also, it's possible that your data wasn't just transposed, but also flipped so you might need to use flip to get the correct result.

Body:
I am simulating a problem where a wave is incident upon a multi-layered sphere.

I have a variable named forceZ1 which is a function of two other variables named phase and frequency. I have solved an equation and found the matrix for forceZ1. Also I know that frequency is a 1*3000 matrix and phase is the same size. So obviously forceZ1 will be 3000*3000.

In this case the phase is changing between 0 and 2*pi and based on the data, I got that the force should be periodic with a period of 2π. This can be verified by plotting any column vector in forceZ1 with respect to the angle, e.g.

figure(); plot(ang1, forceZ1(:,567));

Which gives:

I tried to draw a surface forceZ1 vs. frequency and phase but the figure does not show the periodic behavior. What am I doing wrong?

Here's my plotting code:

Z=forceZ1;
X=ang1;
Y=frequency;

figure
surf(X,Y,Z,'edgecolor','none')
shading interp
view(3)
xlim([0,2*pi]);
xlabel('X=phase')
ylabel('Y=nondimensional frequency')
zlabel('Z=force in Z direction')
title('Force-Frequency-Phase')
colormap jet

I uploaded a .mat file of my data for your reference.

Body:
It seems like your forceZ1 matrix got transposed somewhere along the way. The data is indeed periodic, as you said, but the direction of the periodicity is your Y axis.

It will start making sense if you plot your data like this:

surf(X,Y,Z.','edgecolor','none');

... leading to:

However, since your data contains harmonics differing by phase, magnitude and offset, you might want to try using a different type of chart that would accentuate the shapes of the harmonics, such as ribbon:

figure(); ribbon(Z(1:40:end,1:100:end));

... or try to make an animation, or an interactive chart using a slider for the shown frequency.

Also, it's possible that your data wasn't just transposed, but also flipped so you might need to use flip to get the correct result.


问:
Parameter 3 to mysqli_stmt_bind_param() expected to be a reference, value given - PHP
My code:

```<code>public function valRef($arr) {

        $refs = array();
        foreach ($arr as $key => $value) {
            $refs[$key] = &$arr[$key];
        }

        var_dump($refs);

       //var_dump($refs) returns something like this:
       array(1) {
       [0]=>
       &int(1)

        return $refs;
}
</code>```

This is where the function is used. I don't understand why the returned $refs array is different. Shouldn't it be the same as the one above?

```<code>var_dump($this->helperClass->valRef($ref));
array(1) {
  [0]=>
  int(1)
}

        call_user_func_array('mysqli_stmt_bind_param', array_merge(array($q, $prep), $this->helperClass->valRef($ref)));
</code>```

答: The reason this happens is because you are passing valRef($arr) as the parameter. since the function is not a referenced variable it cannot find a pointer to it. Once assigned to a variable, it will have a reference pointer to work with.</p>

Body:
My code:

public function valRef($arr) {

        $refs = array();
        foreach ($arr as $key => $value) {
            $refs[$key] = &$arr[$key];
        }

        var_dump($refs);

       //var_dump($refs) returns something like this:
       array(1) {
       [0]=>
       &int(1)

        return $refs;
}

This is where the function is used. I don't understand why the returned $refs array is different. Shouldn't it be the same as the one above?

var_dump($this->helperClass->valRef($ref));
array(1) {
  [0]=>
  int(1)
}

        call_user_func_array('mysqli_stmt_bind_param', array_merge(array($q, $prep), $this->helperClass->valRef($ref)));


问:
Python commands in the Command prompt
I try to enter some commands directly in the cmd. The commands work from the IDE PyCharm, but when i try to enter them directly it doesn't work. What do i have to do? I tried to change the direction of the cmd (using cd).
Im using windows. I try to do some pip commands but i acctualy have a bigger problem. I am using the spectral toolbox from python. in the File matplotlib there comes the error No module named 'matplotlib._path'.</p>

答:
The terminal in the PyCharm IDE is probably giving you a python prompt, and hence accepts python commands. The cmd terminal is expecting windows commands instead.

If you start python in the cmd terminal with the command python (or python3) then you should switch to a prompt starting with >>>, at which point you can enter commands.

e.g.

```<code>    C:\Users\Ben> python
    Python 2.7
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print("Hello")
    Hello
</code>```

Alternatively tell us what commands you're trying to run so we have a better idea how to help.

Title: Python commands in the Command prompt

Body:
The terminal in the PyCharm IDE is probably giving you a python prompt, and hence accepts python commands. The cmd terminal is expecting windows commands instead.

If you start python in the cmd terminal with the command python (or python3) then you should switch to a prompt starting with >>>, at which point you can enter commands.

e.g.

    C:\Users\Ben> python
    Python 2.7
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print("Hello")
    Hello

Alternatively tell us what commands you're trying to run so we have a better idea how to help.


问:
Confusion about realloc function
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

```<code>int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

```<code>int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?

答:
In the first case the program almost sure will finish by segmentation fault as the linked lists that are created in the heap to find segments are not coherent, in the second case you call the realloc with the NULL first parameter, which means, is a call equivalent to malloc(size)

man realloc says:

```<code>   void *malloc(size_t size);
   void *realloc(void *ptr, size_t size);
</code>```

If ptr is NULL, then the call is equivalent to malloc(size), for all values of size

Title: Confusion about realloc function

Body:
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?

Body:
In the first case the program almost sure will finish by segmentation fault as the linked lists that are created in the heap to find segments are not coherent, in the second case you call the realloc with the NULL first parameter, which means, is a call equivalent to malloc(size)

man realloc says:

   void *malloc(size_t size);
   void *realloc(void *ptr, size_t size);

If ptr is NULL, then the call is equivalent to malloc(size), for all values of size


问:
how to add a constrains to fix tableview to its parent bottom
i have a container in my view with two tableview controllers as childs.

i have the childs as this properties in class

```<code>lazy var photoFeedVC: UserPicsTableViewController = self.makeAndAddVC()
    lazy var postFeedVC: PostFeedVC = self.makeAndAddVC()
</code>```

the function to make the childs

```<code>func makeAndAddVC<T: UIViewController>() -> T {
        let vc = T()
        self.addChildViewController(vc)
        return vc
    }
</code>```

i want to fix each tableview to its container bottom after i increase the size of the container in viewDidAppear.

```<code>photoFeedVC.tableView.snp.makeConstraints({(make) -> Void in
        make.bottom.equalTo(containerView)
    })
    postFeedVC.tableView.snp.makeConstraints({ make -> Void in
        make.bottom.equalTo(self.view)
    })
</code>```

this is a contrainst tryin to fix to bottom but xcode gave me this error

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors
   and

  because they have no common ancestor.  Does the constraint or its
  anchors reference items in different view hierarchies?  That's
  illegal.'

here the method to increase the container

```<code>override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        print("aparecio la vista")
        containerView.frame.size.height += 150
        self.feed.frame.size.height += 150.0
        self.photoFeedVC.tableView.frame.size.height += 150.0
        self.postFeedVC.tableView.frame.size.height += 150
        self.scrollView.contentSize.height = containerView.height + 10
        self.scrollView.layoutIfNeeded()
    }
</code>```

答:
The error message in question is saying you're pinning 2 views that aren't in the same hierarchy. You're missing an addSubview() call somewhere (though I can't say exactly where, because there seem to be a lot of child view controllers and I'm not sure what the hierarchy should look like).

You're also doing both frame math and auto layout, which, except in very rare cases, is not what you want. If you want to be using auto layout, you should be modifying constraints to expand a container, not adjusting anything's frame.height.

Body:
i have a container in my view with two tableview controllers as childs.

i have the childs as this properties in class

lazy var photoFeedVC: UserPicsTableViewController = self.makeAndAddVC()
    lazy var postFeedVC: PostFeedVC = self.makeAndAddVC()

the function to make the childs

func makeAndAddVC<T: UIViewController>() -> T {
        let vc = T()
        self.addChildViewController(vc)
        return vc
    }

i want to fix each tableview to its container bottom after i increase the size of the container in viewDidAppear.

photoFeedVC.tableView.snp.makeConstraints({(make) -> Void in
        make.bottom.equalTo(containerView)
    })
    postFeedVC.tableView.snp.makeConstraints({ make -> Void in
        make.bottom.equalTo(self.view)
    })

this is a contrainst tryin to fix to bottom but xcode gave me this error

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors
   and

  because they have no common ancestor.  Does the constraint or its
  anchors reference items in different view hierarchies?  That's
  illegal.'

here the method to increase the container

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        print("aparecio la vista")
        containerView.frame.size.height += 150
        self.feed.frame.size.height += 150.0
        self.photoFeedVC.tableView.frame.size.height += 150.0
        self.postFeedVC.tableView.frame.size.height += 150
        self.scrollView.contentSize.height = containerView.height + 10
        self.scrollView.layoutIfNeeded()
    }


问:
How can I get property name strings used in a Func of T
I have a scenario where I have to get an array of strings that represent each of the property names used within a Func parameter.  Here is an example implementation:

```<code>public class CustomClass<TSource>
{
  public string[] GetPropertiesUsed
  {
    get
    {
      // do magical parsing based upon parameter passed into CustomMethod
    }
  }

  public void CustomMethod(Func<TSource, object> method)
  {
    // do stuff
  }
}
</code>```

Here would be an example usage:

```<code>var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]
</code>```

The part I'm stuck on in the above is the "do magical parsing based upon parameter passed into CustomMethod."

答: You should use Expression<Func<>> class instead. The expression contains actual tree, and can easily be complied to get a delegate (which is a func). What You are really trying to do is to look at the body of the expression and reason about it. Expression class provides You with all the neccessary infrastructure.

Body:
I have a scenario where I have to get an array of strings that represent each of the property names used within a Func parameter.  Here is an example implementation:

public class CustomClass<TSource>
{
  public string[] GetPropertiesUsed
  {
    get
    {
      // do magical parsing based upon parameter passed into CustomMethod
    }
  }

  public void CustomMethod(Func<TSource, object> method)
  {
    // do stuff
  }
}

Here would be an example usage:

var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]

The part I'm stuck on in the above is the "do magical parsing based upon parameter passed into CustomMethod."


问:
High values of the communication range between two vehicles
I use OMNeT++-4.6, sumo-0.22.0 and Veins-4a2.

I measured the distance between two bikes (in my scenario vehicles are considered as bikes and I modified my rou.xml file by adding vClass="bicycle") during a contact in my simulation and I had very high distance values: up to 1800m.

Normally, using the 802.11p model, the communication range is 15-20 meters in Europe.

I did not understand well these high values, can someone explain me please if it is a normal case else where does the problem come from ?

答:
ETSI ITS G5 is using IEEE 802.11p as transmission technology.

Someone can find many publications stating about different transmission distances while using IEEE 802.11p as transmission technology.

The article Evaluating the Impact of Transmission Range on the Performance of VANET mentions a communication distance up to one kilometer.

But, the transmission distance highly depends on the simulated scenario as various obstacles (cars, buildings, ...) may influence the maximum transmission distance significantly.

Also, the simulation accuracy of the physical transmission and the radio medium will influence the calculated transmission range.


问:
How to turn off .NET 4.5 features on CSharpCodeProvider?
I'm using CSharpCodeProvider to compile assembly. I want to get errors when user using features and classes from .NET Framework versions above 4.0.

For example, if run this code on machine with installed 4.5 version .NET framework, CSharpCodeProvider compiles successfully with .NET 4.5 APIs(e.g. System.Reflection.ReflectionContext)

```<code>var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var cs = new CSharpCodeProvider(options);
var compilerParams = new CompilerParameters();
var r = cs.CompileAssemblyFromSource(
    compilerParams,
    "namespace Sample {public class SampleClass{private System.Reflection.ReflectionContext a;}}");
</code>```

Anyone any idea how I can specify to use the only 4.0 version for compile?

答:
I think that you have to link another mscorlib.dll, using the /nostdlib option.</p>

```<code>List<String> references = new List<string>();

String mscorlib = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Windows),
    @"Microsoft.NET\Framework\v4.0.30319\mscorlib.dll"
);

references.Add(mscorlib);
// Add other references...

var provider = new CSharpCodeProvider(new Dictionary<String,String> {{"CompilerVersion", "v4.0"}});

var parameters = new CompilerParameters(references.ToArray(), "MyApp.exe");
parameters.GenerateExecutable = true;
parameters.CompilerOptions = "/nostdlib";

var results = provider.CompileAssemblyFromSource(parameters,
    @"using System;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(""CLR Version: "" + Environment.Version);
        }
    }");
</code>```

Body:
I'm using CSharpCodeProvider to compile assembly. I want to get errors when user using features and classes from .NET Framework versions above 4.0.

For example, if run this code on machine with installed 4.5 version .NET framework, CSharpCodeProvider compiles successfully with .NET 4.5 APIs(e.g. System.Reflection.ReflectionContext)

var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var cs = new CSharpCodeProvider(options);
var compilerParams = new CompilerParameters();
var r = cs.CompileAssemblyFromSource(
    compilerParams,
    "namespace Sample {public class SampleClass{private System.Reflection.ReflectionContext a;}}");

Anyone any idea how I can specify to use the only 4.0 version for compile?

Body:
I think that you have to link another mscorlib.dll, using the /nostdlib option.

List<String> references = new List<string>();

String mscorlib = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Windows),
    @"Microsoft.NET\Framework\v4.0.30319\mscorlib.dll"
);

references.Add(mscorlib);
// Add other references...

var provider = new CSharpCodeProvider(new Dictionary<String,String> {{"CompilerVersion", "v4.0"}});

var parameters = new CompilerParameters(references.ToArray(), "MyApp.exe");
parameters.GenerateExecutable = true;
parameters.CompilerOptions = "/nostdlib";

var results = provider.CompileAssemblyFromSource(parameters,
    @"using System;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(""CLR Version: "" + Environment.Version);
        }
    }");


问:
Rails f.select not passing values
Here is code sample:

```<code><%= form_for @article, html: { class: "form-horizontal" } do |f| %>

  <div class="form-group">
    <%= f.label :keywords, class: 'col-md-1 control-label' %>
    <div class="col-md-3">
      <%= f.select :keywords, ['test_1', 'test_2', 'test_3', 'test_4', 'test_5'], {}, { :multiple => true, :size => 10, :class => 'form-control' } %>
    </div>
  </div>

<% end %>
</code>```

When I set multiple to 'false' it works just fine, but if I set it to true (for multiple select), it just doesn't pass any data. If I have verification it gives me an "keyword is empty" error and if I remove validation - it is just empty. Any ideas?

答:
```<code><%= f.select :keywords, options_for_select([['test_1','test_1'], ['test_2','test_2'], ['test_3','test_3'], ['test_4','test_4'], ['test_5','test_5']]), {}, { :multiple => true, :size => 10, :class => 'form-control' } %>
</code>```

Title: Rails f.select not passing values

Body:
Here is code sample:

<%= form_for @article, html: { class: "form-horizontal" } do |f| %>

    <%= f.label :keywords, class: 'col-md-1 control-label' %>

      <%= f.select :keywords, ['test_1', 'test_2', 'test_3', 'test_4', 'test_5'], {}, { :multiple => true, :size => 10, :class => 'form-control' } %>

<% end %>

When I set multiple to 'false' it works just fine, but if I set it to true (for multiple select), it just doesn't pass any data. If I have verification it gives me an "keyword is empty" error and if I remove validation - it is just empty. Any ideas?


问:
What does it mean when a class comes right after an id:
What does it mean in css when a class comes right after an id (there is no space between them)? such as this:

```<code>#bgimage.header-image
</code>```

Thanks

答:
It means that this formula will be used for the same element, such as

```<code><div id="bgimage" class="header-image"></div>
</code>```

If you'll make space between #bgimage and .header-image then it will be used to:

```<code><div id="bgimage"><div class="header-image"></div></div>
</code>```

Body:
What does it mean in css when a class comes right after an id (there is no space between them)? such as this:

#bgimage.header-image

Thanks

Body:
It means that this formula will be used for the same element, such as

<div id="bgimage" class="header-image"></div>

If you'll make space between #bgimage and .header-image then it will be used to:

<div id="bgimage"><div class="header-image"></div></div>


问:
parsing multidimensional javascript json array with php
I have the following multidimensional javascript array:

My js array

and I want to parse it and return some values from it (name and url)

but when cleaning it up a bit $jsonData = str_replace('var stations = ','' ,$jsonDataUrl); and trying to parse it as json with json_decode($jsongoeshere), the parser returned error 4 even if this URL had told me
that The JSON input is valid in JavaScript.

So now I am a bit lost on how to parse it.

答:
quoted object property name expected is your error.

Your JSON string is not valid, object property names must be quoted.

This

```<code>{
        "aland": [
        {
            name: "Ålands Radio",
            logo: "stations/images-europe/aland/Ålands Radio.png",
            url: "http://194.110.182.131:8000/stream.ogg"
        },
...
</code>```

Should be

```<code>{
        "aland": [
        {
            "name": "Ålands Radio",
            "logo": "stations/images-europe/aland/Ålands Radio.png",
            "url": "http://194.110.182.131:8000/stream.ogg"
        },
...
</code>```

These JSON validators give you the correct error.

https://jsonlint.com/  &  https://jsonformatter.curiousconcept.com/

Also, what @JJAulde said is true.

You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =

Body:
quoted object property name expected is your error.

Your JSON string is not valid, object property names must be quoted.

This

{
        "aland": [
        {
            name: "Ålands Radio",
            logo: "stations/images-europe/aland/Ålands Radio.png",
            url: "http://194.110.182.131:8000/stream.ogg"
        },
...

Should be

{
        "aland": [
        {
            "name": "Ålands Radio",
            "logo": "stations/images-europe/aland/Ålands Radio.png",
            "url": "http://194.110.182.131:8000/stream.ogg"
        },
...

These JSON validators give you the correct error.

https://jsonlint.com/  &  https://jsonformatter.curiousconcept.com/

Also, what @JJAulde said is true.

You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =


问:
Save and load weights in keras
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

```<code>TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')
</code>```

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

```<code>from keras.models import load_model
model = load_model('myModel.h5')
</code>```

but i get this error:

```<code>ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.
</code>```

Any suggestions on what i may be doing wrong?
Thank you in advance.

答:
For loading weights, you need to have a model first. It must be:

```<code>existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
</code>```

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

```<code>model.save_model('filename')
model = load_model('filename')
</code>```

Title: Save and load weights in keras

Body:
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

from keras.models import load_model
model = load_model('myModel.h5')

but i get this error:

ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.

Any suggestions on what i may be doing wrong?
Thank you in advance.

Body:
For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

ContentLicense: CC BY-SA 4.0


问:
How do you use the GPU for 3D rendering in an Adobe Air app
I'm playing with Air and trying to get the PaperVision3D engine to display some 3D models.

But its really slow since Air seemingly does not support GPU acceleration. Any way to enable GPU rendering in air apps? browser apps can use "wmode=gpu" in the HTML settings...

答:
I think you'll need to wait for molehill, http://labs.adobe.com/technologies/flash/molehill/

the current hardware acceleration is pretty limited.

http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3_Flex/WS2E9C7F3B-6A7C-4c5d-8ADD-5B23446FBEEB.html

there is some info at the bottom of the page there

Direct and GPU-compositing window
  modes

Flash Player 10 introduces two window
  modes, direct and GPU compositing,
  which you can enable through the
  publish settings in the Flash
  authoring tool. These modes are not
  supported in AIR. To take advantage of
  these modes, you must enable hardware
  acceleration for Flash Player.

Direct mode uses the fastest, most
  direct path to push graphics to the
  screen, which is advantageous for
  video playback.

GPU Compositing uses the graphics
  processing unit on the video card to
  accelerate compositing. Video
  compositing is the process of layering
  multiple images to create a single
  video image. When compositing is
  accelerated with the GPU it can
  improve the performance of YUV
  conversion, color correction, rotation
  or scaling, and blending. YUV
  conversion refers to the color
  conversion of composite analog
  signals, which are used for
  transmission, to the RGB (red, green,
  blue) color model that video cameras
  and displays use. Using the GPU to
  accelerate compositing reduces the
  memory and computational demands that
  are otherwise placed on the CPU. It
  also results in smoother playback for
  standard-definition video.

Be cautious in implementing these
  window modes. Using GPU compositing
  can be expensive for memory and CPU
  resources. If some operations (such as
  blend modes, filtering, clipping or
  masking) cannot be carried out in the
  GPU, they are done by the software.
  Adobe recommends limiting yourself to
  one SWF file per HTML page when using
  these modes and you should not enable
  these modes for banners. The Flash
  Test Movie facility does not use
  hardware acceleration but you can use
  it through the Publish Preview option.

Setting a frame rate in your SWF file
  that is higher than 60, the maximum
  screen refresh rate, is useless.
  Setting the frame rate from 50 through
  55 allows for dropped frames, which
  can occur for various reasons from
  time to time.

Using direct mode requires Microsoft
  DirectX 9 with VRAM 128 MB on Windows
  and OpenGL for Apple Macintosh, Mac OS
  X v10.2 or higher. GPU compositing
  requires Microsoft DirectX 9 and Pixel
  Shader 2.0 support on Windows with 128
  MB of VRAM. On Mac OS X and Linux, GPU
  compositing requires OpenGL 1.5 and
  several OpenGL extensions (framebuffer
  object, multitexture, shader objects,
  shading language, fragment shader).

You can activate direct and gpu
  acceleration modes on a per-SWF basis
  through the Flash Publish Settings
  dialog box, using the Hardware
  Acceleration menu on the Flash tab. If
  you choose None, the window mode
  reverts to default, transparent, or
  opaque, as specified by the Window
  Mode setting on the HTML tab.

Also Mike Chambers has some info somewhere about GPU acceleration (look for notes on pewpew), but I think this is all meant for mobile only.


问:
Equivalent to RedirectToPage in MVC?
I have a ASP.NET Core 2.0 web application with a mix of Razor Pages and MVC. When I do a POST to the page, I often want to redirect the user back to the same page, but with a GET request.

In ASP.NET Core 2.0 Razor Pages, I typically do it like this:

```<code>public async Task<IActionResult> OnPostView(...)
{
    // Update based on POST data
    ...

    return RedirectToPage();  // Redirect back to GET
}
</code>```

What is the equivalent to this in a MVC controller?

答:
The equivalent method is:

```<code>return RedirectToAction();
</code>```

See the source for more information.

Title: Equivalent to RedirectToPage in MVC?

Body:
I have a ASP.NET Core 2.0 web application with a mix of Razor Pages and MVC. When I do a POST to the page, I often want to redirect the user back to the same page, but with a GET request.

In ASP.NET Core 2.0 Razor Pages, I typically do it like this:

public async Task<IActionResult> OnPostView(...)
{
    // Update based on POST data
    ...

    return RedirectToPage();  // Redirect back to GET
}

What is the equivalent to this in a MVC controller?

Body:
The equivalent method is:

return RedirectToAction();

See the source for more information.


答:
It means an element with id and class at the same time. Eg:</p>

```<code><div id="bgimage" class="header-image"></div>
</code>```

Title: What does it mean when a class comes right after an id:

Body:
It means an element with id and class at the same time. Eg:

<div id="bgimage" class="header-image"></div>


答:
See the below example for difference between the selectors.

/* _class should be a child of _id */
#_id ._class{
  background: #ccc;
  width: 100px;
  height: 100px;
}

/* It should have both id and class */
#_id._class{
  background: #faa;
  width: 100px;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="_id">
  <div class="_class">
      Box 1
  </div>
</div>

<div class="_class" id="_id">
  Box 2
</div></code>```

Body:
See the below example for difference between the selectors.

/* _class should be a child of _id */
#_id ._class{
  background: #ccc;
  width: 100px;
  height: 100px;
}

/* It should have both id and class */
#_id._class{
  background: #faa;
  width: 100px;
  height: 100px;
}

<div id="_id">
  <div class="_class">
      Box 1
  </div>
</div>

<div class="_class" id="_id">
  Box 2
</div>


问:
Color overlay on img tag with shape
I have a image with border radius, and want to add a color overlay over the image.

  img {
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-wrapper">
<img width="751" height="640" src="http://via.placeholder.com/751x640" class="" alt="">
</div></code>```

The image has a oval shape with border-radius

If I add a color with pseudo element on the div/container it doesn't overlay in a oval shape but the full container.

How to place a color overlay (just for the image) on a img tag with border radius?

答:
If you want to go with a pseudo, the container has to shrink on the image and image be displayed as a block or vertical-align reset to avoid the gap. From there, apply to the pseudo the same radius. a gradient overlay can even be used ;)

example:https://codepen.io/anon/pen/qVjdbg

img,
.image-wrapper:before {
  display: block;
  border-bottom-left-radius: 60% 65%;
  border-bottom-right-radius: 35%;
  border-top-left-radius: 40px 200px;
}

.image-wrapper {
  position: relative;
  display: table;
}

.image-wrapper:before {
  content: '';
  position: absolute;
  height: 100%;
  width: 100%;
  background: linear-gradient(45deg, rgba(200, 45, 125, 0.3), rgba(15, 235, 15, 0.5));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-wrapper"><img width="751" height="640" src="http://via.placeholder.com/751x640" class="" alt=""></div></code>```

Title: Color overlay on img tag with shape

Body:
I have a image with border radius, and want to add a color overlay over the image.

  img {
    border-bottom-left-radius: 60% 65%;
    border-bottom-right-radius: 35%;
    border-top-left-radius: 40px 200px;
    }

The image has a oval shape with border-radius

If I add a color with pseudo element on the div/container it doesn't overlay in a oval shape but the full container.

How to place a color overlay (just for the image) on a img tag with border radius?

Body:
If you want to go with a pseudo, the container has to shrink on the image and image be displayed as a block or vertical-align reset to avoid the gap. From there, apply to the pseudo the same radius. a gradient overlay can even be used ;)

example:https://codepen.io/anon/pen/qVjdbg

img,
.image-wrapper:before {
  display: block;
  border-bottom-left-radius: 60% 65%;
  border-bottom-right-radius: 35%;
  border-top-left-radius: 40px 200px;
}

.image-wrapper {
  position: relative;
  display: table;
}

.image-wrapper:before {
  content: '';
  position: absolute;
  height: 100%;
  width: 100%;
  background: linear-gradient(45deg, rgba(200, 45, 125, 0.3), rgba(15, 235, 15, 0.5));
}

<div class="image-wrapper"><img width="751" height="640" src="http://via.placeholder.com/751x640" class="" alt=""></div>


问:
Is good practice create a controller for auto-complete filters?
I'm a newbie in asp.net mvc.

I need to create a 'auto-complete tag search' functionality like stackoverflow. My intent is to create a controller with JsonResult to get a filtered tag to auto-complete the input-text element. This is a good practice? If yes, any recommendations for something I need to avoid?

Thanks in advance.

PS.: Sorry for poor English.

答:
The solution suggested by kekekela can be used even if there are multiple filter parameters, no need to create multiple actions unless the result set is of different type. For example:</p>

```<code>[HttpPost]
    [Authorize]
    public JsonResult FilterTasks(int maxResults, string users = "", string tags = "", string categories = "")
    {
        List<int> userIdList = MyHelper.GetIntList(users);
        List<string> tagNameList = MyHelper.GetStringList(tags);
        List<string> categoryIdList = MyHelper.GetStringList(categories);
        var tasks = from task in projectsEntities.Tasks select task;
        if (userIdList.Count >  0)
            tasks = tasks.Where(task => userIdList.Contains(task.UserId));
        if (tagNameList.Count > 0)
            tasks = tasks.Where(task => tagNameList.Contains(task.TagName));
        if (categoryIdList.Count > 0)
            tasks = tasks.Where(task => categoryIdList.Contains(task.CategoryId));
        var topTasks = tasks.Take(maxResults).ToArray();
        return Json(topTasks);
    }
</code>```

Body:
The solution suggested by kekekela can be used even if there are multiple filter parameters, no need to create multiple actions unless the result set is of different type. For example:

[HttpPost]
    [Authorize]
    public JsonResult FilterTasks(int maxResults, string users = "", string tags = "", string categories = "")
    {
        List<int> userIdList = MyHelper.GetIntList(users);
        List<string> tagNameList = MyHelper.GetStringList(tags);
        List<string> categoryIdList = MyHelper.GetStringList(categories);
        var tasks = from task in projectsEntities.Tasks select task;
        if (userIdList.Count >  0)
            tasks = tasks.Where(task => userIdList.Contains(task.UserId));
        if (tagNameList.Count > 0)
            tasks = tasks.Where(task => tagNameList.Contains(task.TagName));
        if (categoryIdList.Count > 0)
            tasks = tasks.Where(task => categoryIdList.Contains(task.CategoryId));
        var topTasks = tasks.Take(maxResults).ToArray();
        return Json(topTasks);
    }


问:
how to retrieve single data from the Firebase database
I need to retrieve single data from Firebase database. Where I have a list view contains id list. Whenever user clicks the listview i need to display the respective value field.

check screen shot of db

here is the code.

```<code> l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        r2= FirebaseDatabase.getInstance().getReference().child("type").child("discord").child("ad");

                        r2.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            String name1;
                            name1=dataSnapshot.getValue().toString();
                            Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onChildRemoved(DataSnapshot dataSnapshot) {

                        }

                        @Override
                        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
            });
</code>```

I need to execute the query

select value from table_name where id="01" ;

答:
Change the addChildEventListener to addValueEventListener.

For example:

```<code>r2.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String name1 = dataSnapshot.child("01").getValue(String.class);
        Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});
</code>```

Reference

Body:
I need to retrieve single data from Firebase database. Where I have a list view contains id list. Whenever user clicks the listview i need to display the respective value field.

check screen shot of db

here is the code.

 l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        r2= FirebaseDatabase.getInstance().getReference().child("type").child("discord").child("ad");

                        r2.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                            String name1;
                            name1=dataSnapshot.getValue().toString();
                            Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onChildRemoved(DataSnapshot dataSnapshot) {

                        }

                        @Override
                        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
            });

I need to execute the query

select value from table_name where id="01" ;

Body:
Change the addChildEventListener to addValueEventListener.

For example:

r2.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String name1 = dataSnapshot.child("01").getValue(String.class);
        Toast.makeText(Main2Activity.this, name1, Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e(TAG, "onCancelled", databaseError.toException());
    }
});

Reference


问:
i need to combine unique keys and their values grouping as list in python
mylist=[{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]

i need like this

Heading

mylist=[{'apple':[1,3],'mango':[2,15],'orange':[0,10]}]

答:
Here List of dictionary items:

```<code>example = [{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]
name=[]
for key_name in example:
    for i in key_name:
        if i not in name:
            name.append(i)

for ks in example:
    storeKey=[{listKey:0} for listKey in list(set(name)-set(ks.keys()))]
    for s in storeKey:
        for k,v in s.items():
            ks.update({k:v});

new = {}
for d in example:
    for k,v in d.iteritems():
        new.setdefault(k, []).append(v)
print new
</code>```

Body:
Here List of dictionary items:

example = [{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]
name=[]
for key_name in example:
    for i in key_name:
        if i not in name:
            name.append(i)

for ks in example:
    storeKey=[{listKey:0} for listKey in list(set(name)-set(ks.keys()))]
    for s in storeKey:
        for k,v in s.items():
            ks.update({k:v});

new = {}
for d in example:
    for k,v in d.iteritems():
        new.setdefault(k, []).append(v)
print new