问:
Backslash preservation with Docker, echo, and Perl
I am using perl to call docker exec in a very specific way to echo information into /etc/bashrc within a Docker container.

I have two Perl variables that I need interpolated into the echo command. $c_name will usually have a value of test1 or something.$net_ip will usually have a value of 192.168.0.x

```<code>my $prompt = '[\A][' . $c_name . '][' . $net_ip . '][\w]\n\$ ';
`docker exec --privileged $c_name bash -c "echo -e 'PS1=$prompt' >> /etc/bashrc"`;
</code>```

This concatentation effort is about the fourth shot at this. I've also tried

```<code>`docker exec --privileged $c_name bash -c "echo -e PS1='[\A][$c_name][$net_ip][\w]\n\$ ' >> /etc/bashrc"`;
</code>```

Neither of these work. When I do a docker exec -it test1 /bin/bash I get a prompt that looks like this:

```<code>bash: $: command not found
[A][test1][192.168.0.13][w]
</code>```

with my /etc/bashrc looking like the following:

```<code>PS1=[\A][test1][192.168.0.13][\w]
$
</code>```

Now this is kinda-correct. It looks like it didn't escape \n and \$ That is a problem. But what's more concerning is that the prompt is not respecting the \A and \w there. Even when I do source /etc/bashrc from within the container, I'm still getting the error message above from Bash and my prompt stays the same. Is there some weird interaction with Docker and $PS1 I don't know about?

What I want is at the end of my /etc/bashrc I want this line to exist, verbatim, with interpolated Perl $vars:

```<code>[\A][$c_name][$net_ip][\w]\n\$
</code>```

which, after Perl interpretation, might look like:

```<code>[\A][test_container][10.0.0.2][/home/docker]
$
</code>```

I've tried other attempts as well, such as trying to escape the backslashes with double \\ (e.g. [\\A], however, either Perl complains about not recognizing escaped characters ("Unrecognized escape option at $linenumber) or it simply has the same results as above where the backslashes are not placed into /etc/bashrc.

Note that when I'm in the container and I execute:

```<code>export PS1='[\A][test1][192.168.0.13][\w]\n\$ '
</code>```

then the prompt is correct:

```<code>[20:26][test1][192.168.0.13][/]
#
</code>```

答:
I would feed the prompt to docker via standard input, rather than use bash as you are. Then you need only run one command, tee -a /etc/bashrc; it will inherit its standard input from docker, whose standard input is the file handle $fh.

```<code>open my $fh, "|-", "docker exec --privileged '$c_name' tee -a /etc/bashrc";
printf $fh "PS1=$prompt\n";
close $fh;
</code>```

Body:
I am using perl to call docker exec in a very specific way to echo information into /etc/bashrc within a Docker container.

I have two Perl variables that I need interpolated into the echo command. $c_name will usually have a value of test1 or something.$net_ip will usually have a value of 192.168.0.x

my $prompt = '[\A][' . $c_name . '][' . $net_ip . '][\w]\n\$ ';
`docker exec --privileged $c_name bash -c "echo -e 'PS1=$prompt' >> /etc/bashrc"`;

This concatentation effort is about the fourth shot at this. I've also tried

`docker exec --privileged $c_name bash -c "echo -e PS1='[\A][$c_name][$net_ip][\w]\n\$ ' >> /etc/bashrc"`;

Neither of these work. When I do a docker exec -it test1 /bin/bash I get a prompt that looks like this:

bash: $: command not found
[A][test1][192.168.0.13][w]

with my /etc/bashrc looking like the following:

PS1=[\A][test1][192.168.0.13][\w]
$

Now this is kinda-correct. It looks like it didn't escape \n and \$ That is a problem. But what's more concerning is that the prompt is not respecting the \A and \w there. Even when I do source /etc/bashrc from within the container, I'm still getting the error message above from Bash and my prompt stays the same. Is there some weird interaction with Docker and $PS1 I don't know about?

What I want is at the end of my /etc/bashrc I want this line to exist, verbatim, with interpolated Perl $vars:

[\A][$c_name][$net_ip][\w]\n\$

which, after Perl interpretation, might look like:

[\A][test_container][10.0.0.2][/home/docker]
$

I've tried other attempts as well, such as trying to escape the backslashes with double \\ (e.g. [\\A], however, either Perl complains about not recognizing escaped characters ("Unrecognized escape option at $linenumber) or it simply has the same results as above where the backslashes are not placed into /etc/bashrc.

Note that when I'm in the container and I execute:

export PS1='[\A][test1][192.168.0.13][\w]\n\$ '

then the prompt is correct:

[20:26][test1][192.168.0.13][/]
#

Body:
I would feed the prompt to docker via standard input, rather than use bash as you are. Then you need only run one command, tee -a /etc/bashrc; it will inherit its standard input from docker, whose standard input is the file handle $fh.

open my $fh, "|-", "docker exec --privileged '$c_name' tee -a /etc/bashrc";
printf $fh "PS1=$prompt\n";
close $fh;


来源: stackexchange

问:
Makefile to create an executable .mexa64 file from matlab
I try to write a makefile to create an executable .mexa64 file. I have to use the gcc compiler. My current working folder looks like this:

```<code>FFTW_build.c
FFTW_func.c
Makefile.c
obj (Folder, here are my object files *.o which are created)
</code>```

Source code FFTW_build.c:

```<code>#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],  int nrhs, const mxArray *prhs[])
{
    FFTW_perform();
    return;
}
</code>```

Source code FFTW_func.c:

```<code>#include <math.h>
#include <stdio.h>
#include <complex.h>
#include <fftw3.h>
#include "mex.h"

void FFTW_perform() {

 int i;
 int Npoints=10;
 fftw_complex *in, *out;
 fftw_plan plan;

 in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Npoints);
 out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Npoints);
 plan = fftw_plan_dft_1d(Npoints, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
 mexPrintf("\nCoefficcients of the expansion:\n\n");

 for(i = 0; i < Npoints; i++)
    {
        in[i] = (i+1)+(3*i-1)*I;
        mexPrintf("%d %11.7f %11.7f\n", i, creal(in[i]), cimag(in[i]));

    }

 mexPrintf("\n");

    fftw_execute(plan);

    mexPrintf("Output:\n\n");
    for(i = 0; i < Npoints; i++)
    {
        mexPrintf("%d %11.7f %11.7f\n", i, creal(out[i]), cimag(out[i]));
    }
}
</code>```

Source code for Makefile.c:

```<code>##################    Compiler    ##################
CXX = gcc
####################################################

##################    MEXSUFFIX  ################
MEXSUFFIX  = mexa64
####################################################

##################   Home of my matlab version #####
MATLABHOME = /home/tuebel/matlab
####################################################

##################    Object_File_Declaration_Folder    ################

OBJS_MEX       = FFTW_build.o
OBJS_FFTW_FUNC = FFTW_func.o

ODIR=obj

_OBJ = $(OBJS_MEX) $(OBJS_FFTW_FUNC)
OBJ  = $(patsubst %,$(ODIR)/%,$(_OBJ))

####################################################

##################    Header_Files    ################

# Header for mex
DIR_MEX_HEADER = /home/tuebel/matlab/extern/include

_DEPS_MEX = mex.h
DEPS_MEX  = $(patsubst %,$(DIR_MEX_HEADER)/%,$(_DEPS_MEX))

# Header for fftw3
DIR_FFTW_HEADER = /usr/local/include

_DEPS_FFTW = fftw3.h
DEPS_FFTW  = $(patsubst %,$(DIR_FFTW_HEADER)/%,$(_DEPS_FFTW))

####################################################

##################    Library_Files    ################

# Libraries for mex
MEX_LIB  = /home/tuebel/matlab/bin/glnxa64/libmex.so

# Libraries for FFTW
FFTW_LIB = /usr/local/lib/libfftw3.a

# Libraries for math_function
MATH_LIB = -lm

####################################################

##################    Flags    ################

# MEXFLAGS         = -shared -Wl,--no-undefined -Wl,-rpath-link,$(MATLABHOME)/bin/glnxa64 -L$(MATLABHOME)/bin/glnxa64 -lmex -lmat -lmx -lm

MEXFLAGS         =  -shared -Wl,-rpath-link,$(MATLABHOME)/bin/glnxa64 -L$(MATLABHOME)/bin/glnxa64 -lmex -lmat -lmx -lm
COMPILERFLAGS    =  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG

FFTW_FLAGS_INCLUDE     = -I$(DIR_FFTW_HEADER)
MEX_FLAGS_INCLUDE      = -I$(DIR_MEX_HEADER)

####################################################

####################  Final_Part   ######################

TARGET = FFTW_MEX

all: $(TARGET)
    echo ALL DONE

clean:
    rm -f $(ODIR)/*.o
    rm -f $(TARGET).mexa64
    echo CLEAN DONE

$(ODIR)/%.o: %.c $(DEPS_MEX) $(DEPS_FFTW)
    $(CXX) -c -o $@ $<  $(COMPILERFLAGS) $(MEX_FLAGS_INCLUDE) $(FFTW_FLAGS_INCLUDE)

# Final_Linking

$(TARGET) : $(OBJ)  $(MATH_LIB) $(FFTW_LIB)
    $(CXX) -o $@.$(MEXSUFFIX) $(MEX_FLAGS_INCLUDE) $(FFTW_FLAGS_INCLUDE) $^ $(MEXFLAGS)

####################################################

####################################################

####################################################
</code>```

The idea is to make a FFTW using fftw3. The code works fine in the command window, but if I try to make it executable from matlab (.mexa64 file) it is not working. I get the following error message using make:

```<code>gcc  -c -o obj/FFTW_build.o FFTW_build.c  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG -I/home/tuebel/matlab/extern/include -I/usr/local/include
gcc  -c -o obj/FFTW_func.o FFTW_func.c  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG -I/home/tuebel/matlab/extern/include -I/usr/local/include
gcc  -o FFTW_MEX.mexa64   -I/home/tuebel/matlab/extern/include -I/usr/local/include obj/FFTW_build.o obj/FFTW_func.o /usr/lib64/libm.so /usr/local/lib/libfftw3.a -shared -Wl,-rpath-link,/home/tuebel/matlab/bin/glnxa64 -L/home/tuebel/matlab/bin/glnxa64 -lmex -lmat -lmx -lm
/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/bin/ld: /usr/local/lib/libfftw3.a(lt4-problem.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/local/lib/libfftw3.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
Makefile:92: recipe for target 'FFTW_MEX' failed
make: *** [FFTW_MEX] Error 1
</code>```

Can someone help me out? This is my first Makefile and I would be glad for any help... I am also glad for corrections to the Makefile...

Thanks a lot!

答:
It is a bit unclear what you mean by an "executable" .mexa64 file.

MATLAB's mex compiler will let you compile C/C++ code with MATLAB libraries into a mex file (with 64 bit architecture for you here) that you can then "execute" via MATLAB's command line.  This seems to be what you have gotten to work already.

However, if you want to have a stand alone "executable" outside of MATLAB, you need to work with MATLAB's mcr compiler (see the reference here).  There are flags that you can set in the process to be build an object file which you can then link with later on with your makefile as you are trying to now.

So, don't mix mex compiled files which are runnable within MATLAB and mcr compiled code that is executable outside of it.

Apart from this, gcc is complaining that there is no main() function.  I don't see one in your code here either, but you need a main() function for a standalone executable.

ContentLicense: CC BY-SA 3.0

Body:
I try to write a makefile to create an executable .mexa64 file. I have to use the gcc compiler. My current working folder looks like this:

FFTW_build.c
FFTW_func.c
Makefile.c
obj (Folder, here are my object files *.o which are created)

Source code FFTW_build.c:

#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],  int nrhs, const mxArray *prhs[])
{
    FFTW_perform();
    return;
}

Source code FFTW_func.c:

#include <math.h>
#include <stdio.h>
#include <complex.h>
#include <fftw3.h>
#include "mex.h"

void FFTW_perform() {

 int i;
 int Npoints=10;
 fftw_complex *in, *out;
 fftw_plan plan;

 in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Npoints);
 out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*Npoints);
 plan = fftw_plan_dft_1d(Npoints, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
 mexPrintf("\nCoefficcients of the expansion:\n\n");

 for(i = 0; i < Npoints; i++)
    {
        in[i] = (i+1)+(3*i-1)*I;
        mexPrintf("%d %11.7f %11.7f\n", i, creal(in[i]), cimag(in[i]));

    }

 mexPrintf("\n");

    fftw_execute(plan);

    mexPrintf("Output:\n\n");
    for(i = 0; i < Npoints; i++)
    {
        mexPrintf("%d %11.7f %11.7f\n", i, creal(out[i]), cimag(out[i]));
    }
}

Source code for Makefile.c:

##################    Compiler    ##################
CXX = gcc
####################################################

##################    MEXSUFFIX  ################
MEXSUFFIX  = mexa64
####################################################

##################   Home of my matlab version #####
MATLABHOME = /home/tuebel/matlab
####################################################

##################    Object_File_Declaration_Folder    ################

OBJS_MEX       = FFTW_build.o
OBJS_FFTW_FUNC = FFTW_func.o

ODIR=obj

_OBJ = $(OBJS_MEX) $(OBJS_FFTW_FUNC)
OBJ  = $(patsubst %,$(ODIR)/%,$(_OBJ))

####################################################

##################    Header_Files    ################

# Header for mex
DIR_MEX_HEADER = /home/tuebel/matlab/extern/include

_DEPS_MEX = mex.h
DEPS_MEX  = $(patsubst %,$(DIR_MEX_HEADER)/%,$(_DEPS_MEX))

# Header for fftw3
DIR_FFTW_HEADER = /usr/local/include

_DEPS_FFTW = fftw3.h
DEPS_FFTW  = $(patsubst %,$(DIR_FFTW_HEADER)/%,$(_DEPS_FFTW))

####################################################

##################    Library_Files    ################

# Libraries for mex
MEX_LIB  = /home/tuebel/matlab/bin/glnxa64/libmex.so

# Libraries for FFTW
FFTW_LIB = /usr/local/lib/libfftw3.a

# Libraries for math_function
MATH_LIB = -lm

####################################################

##################    Flags    ################

# MEXFLAGS         = -shared -Wl,--no-undefined -Wl,-rpath-link,$(MATLABHOME)/bin/glnxa64 -L$(MATLABHOME)/bin/glnxa64 -lmex -lmat -lmx -lm

MEXFLAGS         =  -shared -Wl,-rpath-link,$(MATLABHOME)/bin/glnxa64 -L$(MATLABHOME)/bin/glnxa64 -lmex -lmat -lmx -lm
COMPILERFLAGS    =  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG

FFTW_FLAGS_INCLUDE     = -I$(DIR_FFTW_HEADER)
MEX_FLAGS_INCLUDE      = -I$(DIR_MEX_HEADER)

####################################################

####################  Final_Part   ######################

TARGET = FFTW_MEX

all: $(TARGET)
    echo ALL DONE

clean:
    rm -f $(ODIR)/*.o
    rm -f $(TARGET).mexa64
    echo CLEAN DONE

$(ODIR)/%.o: %.c $(DEPS_MEX) $(DEPS_FFTW)
    $(CXX) -c -o $@ $<  $(COMPILERFLAGS) $(MEX_FLAGS_INCLUDE) $(FFTW_FLAGS_INCLUDE)

# Final_Linking

$(TARGET) : $(OBJ)  $(MATH_LIB) $(FFTW_LIB)
    $(CXX) -o $@.$(MEXSUFFIX) $(MEX_FLAGS_INCLUDE) $(FFTW_FLAGS_INCLUDE) $^ $(MEXFLAGS)

####################################################

####################################################

####################################################

The idea is to make a FFTW using fftw3. The code works fine in the command window, but if I try to make it executable from matlab (.mexa64 file) it is not working. I get the following error message using make:

gcc  -c -o obj/FFTW_build.o FFTW_build.c  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG -I/home/tuebel/matlab/extern/include -I/usr/local/include
gcc  -c -o obj/FFTW_func.o FFTW_func.c  -fPIC -pthread -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -O3 -DNDEBUG -I/home/tuebel/matlab/extern/include -I/usr/local/include
gcc  -o FFTW_MEX.mexa64   -I/home/tuebel/matlab/extern/include -I/usr/local/include obj/FFTW_build.o obj/FFTW_func.o /usr/lib64/libm.so /usr/local/lib/libfftw3.a -shared -Wl,-rpath-link,/home/tuebel/matlab/bin/glnxa64 -L/home/tuebel/matlab/bin/glnxa64 -lmex -lmat -lmx -lm
/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/bin/ld: /usr/local/lib/libfftw3.a(lt4-problem.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/local/lib/libfftw3.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
Makefile:92: recipe for target 'FFTW_MEX' failed
make: *** [FFTW_MEX] Error 1

Can someone help me out? This is my first Makefile and I would be glad for any help... I am also glad for corrections to the Makefile...

Thanks a lot!


问:
Webpack Module RefrenceError module is not defined
I'm tyring to bundle some modules using webpack2.  The modules are written using common module patterns (not CommonJS or AMD).

```<code>// in spUtil.js
var spUtil = (function(){
  var sp={};
  /* build some helper functions to set up urls and rest queries for sharepoint */
  return sp;
})();

// in listcrud.js
var listCrud=(function(){
  lc={};
  /* build some functions that get data from sharepoint lists */
  return lc;
})();

// in util.js
require("exports-loader?spUtil!./spUtil.js");
require("exports-loader?listCrud!./listcrud.js");
var util=(function(spUtil,listCrud){
  ut={};
  /* build some functions that query data from sharepoint */
  return ut;
})($,spUtil,listCrud);

// in myModule.js
var myModule=(function($,util){
  my={};
  /* build a view of some SP data */
  return my;
})($,util);
</code>```

However I get an error while webpack tries to load the bundle;

```<code>Uncaught ReferenceError: spUtil is not defined
    at Object.$.ajax.url (dashboard.bundle.js:389)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:1076)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:813)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:1729)
    at __webpack_require__ (dashboard.bundle.js:20)
    at dashboard.bundle.js:66
    at dashboard.bundle.js:69
</code>```

Webpack builds something like this:

```<code>/* 0 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(2);
__webpack_require__(1);
var util =(function($,spUtil,listCrud){
....
})($,sqUtil,listCrud);

/* 4 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(0);
var myModule=(function($,util){
  var my={};
  .....
  return my;
})($,util);
</code>```

Where module 2 is spUtil and module 1 is listCrud.  Stepping through the dev tools debugger - spUtil is loaded, listCrud has already been 'installed' by webpack this function is called:

```<code>/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
</code>```

How can I resolve this error?

答:
I figured out my error I was missing one key component.  Declaring the variable in in the module for it to use.</p>

```<code>var spUtil = require('...spUtil.js');
var listCrud = require('...listcrud.js');
</code>```

Body:
I'm tyring to bundle some modules using webpack2.  The modules are written using common module patterns (not CommonJS or AMD).

// in spUtil.js
var spUtil = (function(){
  var sp={};
  /* build some helper functions to set up urls and rest queries for sharepoint */
  return sp;
})();

// in listcrud.js
var listCrud=(function(){
  lc={};
  /* build some functions that get data from sharepoint lists */
  return lc;
})();

// in util.js
require("exports-loader?spUtil!./spUtil.js");
require("exports-loader?listCrud!./listcrud.js");
var util=(function(spUtil,listCrud){
  ut={};
  /* build some functions that query data from sharepoint */
  return ut;
})($,spUtil,listCrud);

// in myModule.js
var myModule=(function($,util){
  my={};
  /* build a view of some SP data */
  return my;
})($,util);

However I get an error while webpack tries to load the bundle;

Uncaught ReferenceError: spUtil is not defined
    at Object.$.ajax.url (dashboard.bundle.js:389)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:1076)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:813)
    at __webpack_require__ (dashboard.bundle.js:20)
    at Object.<anonymous> (dashboard.bundle.js:1729)
    at __webpack_require__ (dashboard.bundle.js:20)
    at dashboard.bundle.js:66
    at dashboard.bundle.js:69

Webpack builds something like this:

/* 0 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(2);
__webpack_require__(1);
var util =(function($,spUtil,listCrud){
....
})($,sqUtil,listCrud);

/* 4 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(0);
var myModule=(function($,util){
  var my={};
  .....
  return my;
})($,util);

Where module 2 is spUtil and module 1 is listCrud.  Stepping through the dev tools debugger - spUtil is loaded, listCrud has already been 'installed' by webpack this function is called:

/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }

How can I resolve this error?

Body:
I figured out my error I was missing one key component.  Declaring the variable in in the module for it to use.

var spUtil = require('...spUtil.js');
var listCrud = require('...listcrud.js');


问:
Add files to classpath or loops in batch files?
I have this script in BASH (linux) shells script that adds all *.jar files into the classpath automatically. Is there a way to do the in window's batch file or do I have to add all the files manually?

```<code>CLASSPATH=.
for file in ./libs/*.jar; do
    CLASSPATH=$CLASSPATH:$file
done
</code>```

Thanks!

答: See BAT file to create Java CLASSPATH</p>

ContentLicense: CC BY-SA 2.5

Body:
I have this script in BASH (linux) shells script that adds all *.jar files into the classpath automatically. Is there a way to do the in window's batch file or do I have to add all the files manually?

CLASSPATH=.
for file in ./libs/*.jar; do
    CLASSPATH=$CLASSPATH:$file
done

Thanks!

Body: See BAT file to create Java CLASSPATH


问:
Scroll on next button
Trying to scroll to next button on button click:

It works when you click on the title, but not when you click on
Here is code: https://codepen.io/anon/pen/YQyNyw

Anyone ideas?

Particular part that I'm having trouble with:

```<code>let activeIndex = 0; let scrollTopPadding = -100; let wrapper; let fields;

$(document).ready(() => {   wrapper = $('.wrapper');   fields = $('.field');    fields.click(function() {
    scrollToActiveField(this);   });
     let inputs = $('.field button');
     inputs.click(function(){
    scrollToActiveField($(this).parent());   });   inputs.click(function(event) { // enter
        let nextInputIndex = inputs.index(this) + 1;
        if (nextInputIndex < inputs.length) {
          inputs.eq(nextInputIndex).focus();
        }
         });
     setActiveTab(); });
</code>```

Here is the working example https://codepen.io/benelliott/pen/beBPyJ - I need buttons instead of inputs.

答:
The problem arises from the the buttons in your form being an unknown type. I believe the form is defaulting them to a "submit" button which causes funny behavior (would love an additional answer/comment that explains this, I don't have the time right now to research it).

Easy fix though. Just add type="button" to each button and your codepen works: https://codepen.io/hyrumwhite/pen/WOQRzK

```<code><div class="wrapper">
<form class="form" action="">
  <div class="field">
    <label>First name</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Last name</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Telephone</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Email</label>
    <button type="button"> test</button>
  </div>
</form>
</div>
</code>```

Title: Scroll on next button

Body:
Trying to scroll to next button on button click:

It works when you click on the title, but not when you click on
Here is code: https://codepen.io/anon/pen/YQyNyw

Anyone ideas?

Particular part that I'm having trouble with:

let activeIndex = 0; let scrollTopPadding = -100; let wrapper; let fields;

$(document).ready(() => {   wrapper = $('.wrapper');   fields = $('.field');    fields.click(function() {
    scrollToActiveField(this);   });
     let inputs = $('.field button');
     inputs.click(function(){
    scrollToActiveField($(this).parent());   });   inputs.click(function(event) { // enter
        let nextInputIndex = inputs.index(this) + 1;
        if (nextInputIndex < inputs.length) {
          inputs.eq(nextInputIndex).focus();
        }
         });
     setActiveTab(); });

Here is the working example https://codepen.io/benelliott/pen/beBPyJ - I need buttons instead of inputs.

Body:
The problem arises from the the buttons in your form being an unknown type. I believe the form is defaulting them to a "submit" button which causes funny behavior (would love an additional answer/comment that explains this, I don't have the time right now to research it).

Easy fix though. Just add type="button" to each button and your codepen works: https://codepen.io/hyrumwhite/pen/WOQRzK

<div class="wrapper">
<form class="form" action="">
  <div class="field">
    <label>First name</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Last name</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Telephone</label>
    <button type="button"> test</button>
  </div>
  <div class="field">
    <label>Email</label>
    <button type="button"> test</button>
  </div>
</form>
</div>


问:
How to fix the TypeError (list indices must be integers, not str) in this program?
In one of the program I am using, I am getting a TypeError when trying to mine/parse a value out of dict type data.

Below is a brief part of that python program:

```<code>for c in results:
        print('value of c : ', c, type(c)) # what I added to see the issue with dict data
        for ci, lr in c['chain_info'].iteritems():
            outfile = open(lr.output_file, 'a')
            write = outfile.write

            if lr.number_vcf_lines > 0:
                write(CHAIN_STRING.format(CHAIN_STRING,
                            from_chr=c['chrom'], from_length=lr.chromosome_length,
                            from_start=0, from_end=lr.chromosome_length,
                            to_chr=c['chrom'], to_length=lr.end_length,
                            to_start=0, to_end=lr.sums[0] + lr.last_fragment_size + lr.sums[2], id=c['chrom']))
                write("\n")
</code>```

Full traceback error message

Error Type: <type 'exceptions.TypeError'>
Error Value: list indices must be integers, not str
/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/vcf2chain.py:456
Traceback (most recent call last):
  File "/home/everestial007/anaconda3/envs/g2gtools/bin/g2gtools", line 4, in <module>
__import__('pkg_resources').run_script('g2gtools==0.1.31', 'g2gtools')
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/pkg_resources/__init__.py", line 744, in run_script
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/pkg_resources/__init__.py", line 1499, in run_script
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 117, in <module>
    G2GToolsApp()
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 75, in __init__
    getattr(self, args.command)()
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 90, in vcf2chain
    g2gtools.g2g_commands.command_vcf2chain(sys.argv[2:], self.script_name + ' vcf2chain')
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/g2g_commands.py", line 375, in command_vcf2chain
    vcf2chain(args.input, args.fasta, args.strain, args.output, args.keep, args.passed, args.quality, args.diploid)
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/vcf2chain.py", line 493, in vcf2chain
    raise G2GError("Execution halted")
g2gtools.exceptions.G2GError: Execution halted
```

<p>The github location of the file: https://github.com/churchill-lab/g2gtools/blob/master/g2gtools/vcf2chain.py</p>

<p>Looks like problem is with line:</p>

```from_chr=c['chrom'], from_length=lr.chromosome_length,
```

<p>And, the Chain_string is something Author created as:</p>

```CHAIN_STRING = "chain 1000 {from_chr} {from_length} + {from_start} {from_end} " + "{to_chr} {to_length} + {to_start} {to_end} {id}"
```

<p>I tried to print the values of that dict (by adding a print statement) to see what was the issue.</p>

```print('value of c : ', c, type(c)) # gave me
('value of c : ', {'chrom': '1', 'stats': OrderedDict([('ACCEPTED', 0)]), 'chain_info': {'right': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9de396dd0>, 'left': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9d9252d50>}}, <type 'dict'>)
```

So, what is the issue here?
What is the problem with this data/program??

答:
Problem was that, in the proceeding for-loop, the variable c was returning as list:

```<code>for c in lr.chain_entries:
   write("\t".join(map(str, c)))
   write("\n")
</code>```

which returned c as list when reading another line. I had to mine c['chrom'] expecting it to be an dict type. But, this variable was changed by proceeding forloop causing all the trouble.

Body:
In one of the program I am using, I am getting a TypeError when trying to mine/parse a value out of dict type data.

Below is a brief part of that python program:

for c in results:
        print('value of c : ', c, type(c)) # what I added to see the issue with dict data
        for ci, lr in c['chain_info'].iteritems():
            outfile = open(lr.output_file, 'a')
            write = outfile.write

            if lr.number_vcf_lines > 0:
                write(CHAIN_STRING.format(CHAIN_STRING,
                            from_chr=c['chrom'], from_length=lr.chromosome_length,
                            from_start=0, from_end=lr.chromosome_length,
                            to_chr=c['chrom'], to_length=lr.end_length,
                            to_start=0, to_end=lr.sums[0] + lr.last_fragment_size + lr.sums[2], id=c['chrom']))
                write("\n")

Full traceback error message

Error Type: <type 'exceptions.TypeError'>
Error Value: list indices must be integers, not str
/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/vcf2chain.py:456
Traceback (most recent call last):
  File "/home/everestial007/anaconda3/envs/g2gtools/bin/g2gtools", line 4, in <module>
__import__('pkg_resources').run_script('g2gtools==0.1.31', 'g2gtools')
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/pkg_resources/__init__.py", line 744, in run_script
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/pkg_resources/__init__.py", line 1499, in run_script
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 117, in <module>
    G2GToolsApp()
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 75, in __init__
    getattr(self, args.command)()
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools-0.1.31-py2.7.egg-info/scripts/g2gtools", line 90, in vcf2chain
    g2gtools.g2g_commands.command_vcf2chain(sys.argv[2:], self.script_name + ' vcf2chain')
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/g2g_commands.py", line 375, in command_vcf2chain
    vcf2chain(args.input, args.fasta, args.strain, args.output, args.keep, args.passed, args.quality, args.diploid)
  File "/home/everestial007/anaconda3/envs/g2gtools/lib/python2.7/site-packages/g2gtools/vcf2chain.py", line 493, in vcf2chain
    raise G2GError("Execution halted")
g2gtools.exceptions.G2GError: Execution halted

The github location of the file: https://github.com/churchill-lab/g2gtools/blob/master/g2gtools/vcf2chain.py

Looks like problem is with line:

from_chr=c['chrom'], from_length=lr.chromosome_length,

And, the Chain_string is something Author created as:

CHAIN_STRING = "chain 1000 {from_chr} {from_length} + {from_start} {from_end} " + "{to_chr} {to_length} + {to_start} {to_end} {id}"

I tried to print the values of that dict (by adding a print statement) to see what was the issue.

print('value of c : ', c, type(c)) # gave me
('value of c : ', {'chrom': '1', 'stats': OrderedDict([('ACCEPTED', 0)]), 'chain_info': {'right': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9de396dd0>, 'left': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9d9252d50>}}, <type 'dict'>)

So, what is the issue here?
What is the problem with this data/program??

Body:
Problem was that, in the proceeding for-loop, the variable c was returning as list:

for c in lr.chain_entries:
   write("\t".join(map(str, c)))
   write("\n")

which returned c as list when reading another line. I had to mine c['chrom'] expecting it to be an dict type. But, this variable was changed by proceeding forloop causing all the trouble.


问:
LINQ to Entities grouping
I have written the following SQL-query that illustrates what I'm trying to achieve:

```<code>SELECT
    K.id,
    SUM(BP.pris)
FROM Kunde K
JOIN Booking BO ON K.id = BO.Kunde_id
JOIN Bane_Booking BB ON BO.id = BB.Booking_id
JOIN Banepris BP ON BO.starttid = BP.time
WHERE BO.gratis = 0
GROUP BY K.id;
</code>```

Basically it's retrieving the total amount spend by customers. Now I'm trying to convert this query into LINQ, as I'm using LINQ to Entities in my application. This is what I have so far:

```<code>from kunde in context.Kunde
join booking in context.Booking on kunde equals booking.Kunde
join banepris in context.Banepris on booking.starttid equals banepris.time
from baneBooking in booking.Bane
select new { Kunde = kunde, Booking = booking, BaneBooking = baneBooking, Banepris = banepris };
</code>```

I would like however to be able to group these in the same LINQ-query so I dont have to group them manually afterwards. How would i go about achieving this?

I need to get the "kunde"-object and the sum of "banepris.pris".

答:
Without your database, I can't test this, but this should be close:</p>

```<code>from K in context.Kunde
join BO in context.Booking on K.id equals BO.Kunde_id
join BP  in context.Banepris on BO.starttid equals BP.time
where BO.gratis == 0
group new { Kunde = K, Pris = BP.pris } by K.id into g
select new { ID=g.Key, Kunde = g.First().Kunde, Sum = g.Sum(k=>k.Pris)}
</code>```

Title: LINQ to Entities grouping

Body:
I have written the following SQL-query that illustrates what I'm trying to achieve:

SELECT
    K.id,
    SUM(BP.pris)
FROM Kunde K
JOIN Booking BO ON K.id = BO.Kunde_id
JOIN Bane_Booking BB ON BO.id = BB.Booking_id
JOIN Banepris BP ON BO.starttid = BP.time
WHERE BO.gratis = 0
GROUP BY K.id;

Basically it's retrieving the total amount spend by customers. Now I'm trying to convert this query into LINQ, as I'm using LINQ to Entities in my application. This is what I have so far:

from kunde in context.Kunde
join booking in context.Booking on kunde equals booking.Kunde
join banepris in context.Banepris on booking.starttid equals banepris.time
from baneBooking in booking.Bane
select new { Kunde = kunde, Booking = booking, BaneBooking = baneBooking, Banepris = banepris };

I would like however to be able to group these in the same LINQ-query so I dont have to group them manually afterwards. How would i go about achieving this?

I need to get the "kunde"-object and the sum of "banepris.pris".

Body:
Without your database, I can't test this, but this should be close:

from K in context.Kunde
join BO in context.Booking on K.id equals BO.Kunde_id
join BP  in context.Banepris on BO.starttid equals BP.time
where BO.gratis == 0
group new { Kunde = K, Pris = BP.pris } by K.id into g
select new { ID=g.Key, Kunde = g.First().Kunde, Sum = g.Sum(k=>k.Pris)}


问:
Spring Data JPA Relationship Annotations
I'm learning Spring Data JPA and having some trouble establishing the relationship between these two tables:

product table with columns id, name, product_type_id

product_type table with columns id, name

A product can have only one type.  A type can be associated with many products.

Where would I use the @OnetoMany and @ManytoOne annotations in my entity classes?

答:
For the situation you mentioned in your question, your entities should be like:

@Entity
public class Product {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    private ProductType type;

    // Getters and setters
}
```

<pre class="lang-java prettyprint-override"><code>@Entity
public class ProductType {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "type")
    private List<Product> products;

    // Getters and setters
}
</code>```

Body:
For the situation you mentioned in your question, your entities should be like:

@Entity
public class Product {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    private ProductType type;

    // Getters and setters
}

@Entity
public class ProductType {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "type")
    private List<Product> products;

    // Getters and setters
}


问:
openh264 Repeating frame
I'm using the openh264 lib, in a c++ program, to convert a set of images into a h264 encoded mp4 file. These images represent updates to the screen during a session recording.

Lets say a set contains 2 images, one initial screen grab of the desktop and another one, 30 seconds later, when the clock changes.

Is there a way for the stream to represent a 30 seconds long video using only theses 2 images?

Right now, I'm brute forcing this by encoding multiple times the first frame to fill the gap. It there a more efficient and/or faster way of doing this.

答: Of course. Set a frame rate of 1/30 fps and you end up with 1 frame every 30 seconds. It doesn't even have to be in the H.264 stream - it can be done also when it gets muxed into an mp4 file afterwards for example.</p>

Title: openh264 Repeating frame


问:
Fast 2D graphics in WPF
I need to draw a large amount of 2D elements in WPF, such as lines and polygons. Their position also needs to be updated constantly.

I have looked at many of the answers here which mostly suggested using DrawingVisual or overriding the OnRender function. To test these methods I've implemented a simple particle system rendering 10000 ellipses and I find that the drawing performance is still really terrible using both of these approaches. On my PC I can't get much above 5-10 frames a second. which is totally unacceptable when you consider that I easily draw 1/2 million particles smoothly using other technologies.

So my question is, am I running against a technical limitation here of WPF or am I missing something? Is there something else I can use? any suggestions welcome.

Here the code I tried

content of MainWindow.xaml:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="500" Width="500" Loaded="Window_Loaded">
    <Grid Name="xamlGrid">

    </Grid>
</Window>
</code>```

content of MainWindow.xaml.cs:

```<code>using System.Windows.Threading;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        EllipseBounce[]     _particles;
        DispatcherTimer     _timer = new DispatcherTimer();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            //particles with Ellipse Geometry
            _particles = new EllipseBounce[10000];

            //define area particles can bounce around in
            Rect stage = new Rect(0, 0, 500, 500);

            //seed particles with random velocity and position
            Random rand = new Random();

            //populate
            for (int i = 0; i < _particles.Length; i++)
            {
               Point pos = new Point((float)(rand.NextDouble() * stage.Width + stage.X), (float)(rand.NextDouble() * stage.Height + stage.Y));
               Point vel = new Point((float)(rand.NextDouble() * 5 - 2.5), (float)(rand.NextDouble() * 5 - 2.5));
                _particles[i] = new EllipseBounce(stage, pos, vel, 2);
            }

            //add to particle system - this will draw particles via onrender method
            ParticleSystem ps = new ParticleSystem(_particles);

            //at this element to the grid (assumes we have a Grid in xaml named 'xmalGrid'
            xamlGrid.Children.Add(ps);

            //set up and update function for the particle position
            _timer.Tick += _timer_Tick;
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 1000 / 60); //update at 60 fps
            _timer.Start();

        }

        void _timer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < _particles.Length; i++)
            {
                _particles[i].Update();
            }
        }
    }

    /// <summary>
    /// Framework elements that draws particles
    /// </summary>
    public class ParticleSystem : FrameworkElement
    {
        private DrawingGroup _drawingGroup;

        public ParticleSystem(EllipseBounce[] particles)
        {
            _drawingGroup = new DrawingGroup();

            for (int i = 0; i < particles.Length; i++)
            {
                EllipseGeometry eg = particles[i].EllipseGeometry;

                Brush col = Brushes.Black;
                col.Freeze();

                GeometryDrawing gd = new GeometryDrawing(col, null, eg);

                _drawingGroup.Children.Add(gd);
            }

        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            drawingContext.DrawDrawing(_drawingGroup);
        }
    }

    /// <summary>
    /// simple class that implements 2d particle movements that bounce from walls
    /// </summary>
    public class SimpleBounce2D
    {
        protected Point     _position;
        protected Point     _velocity;
        protected Rect     _stage;

        public SimpleBounce2D(Rect stage, Point pos,Point vel)
        {
            _stage = stage;

            _position = pos;
            _velocity = vel;
        }

        public double X
        {
            get
            {
                return _position.X;
            }
        }

        public double Y
        {
            get
            {
                return _position.Y;
            }
        }

        public virtual void Update()
        {
            UpdatePosition();
            BoundaryCheck();
        }

        private void UpdatePosition()
        {
            _position.X += _velocity.X;
            _position.Y += _velocity.Y;
        }

        private void BoundaryCheck()
        {
            if (_position.X > _stage.Width + _stage.X)
            {
                _velocity.X = -_velocity.X;
                _position.X = _stage.Width + _stage.X;
            }

            if (_position.X < _stage.X)
            {
                _velocity.X = -_velocity.X;
                _position.X = _stage.X;
            }

            if (_position.Y > _stage.Height + _stage.Y)
            {
                _velocity.Y = -_velocity.Y;
                _position.Y = _stage.Height + _stage.Y;
            }

            if (_position.Y < _stage.Y)
            {
                _velocity.Y = -_velocity.Y;
                _position.Y = _stage.Y;
            }
        }
    }

    /// <summary>
    /// extend simplebounce2d to add ellipse geometry and update position in the WPF construct
    /// </summary>
    public class EllipseBounce : SimpleBounce2D
    {
        protected EllipseGeometry _ellipse;

        public EllipseBounce(Rect stage,Point pos, Point vel, float radius)
            : base(stage, pos, vel)
        {
            _ellipse = new EllipseGeometry(pos, radius, radius);
        }

        public EllipseGeometry EllipseGeometry
        {
            get
            {
                return _ellipse;
            }
        }

        public override void Update()
        {
            base.Update();
            _ellipse.Center = _position;
        }
    }
}
</code>```

答:
The fastest WPF drawing method I have found is to:

create a DrawingGroup "backingStore".

during OnRender(), draw my drawing group to the drawing context

anytime I want, backingStore.Open() and draw new graphics objects into it

The surprising thing about this for me, coming from Windows.Forms.. is that I can update my DrawingGroup after I've added it to the DrawingContext during OnRender(). This is updating the existing retained drawing commands in the WPF drawing tree and triggering an efficient repaint.

In a simple app I've coded in both Windows.Forms and WPF (SoundLevelMonitor), this method empirically feels pretty similar in performance to immediate OnPaint() GDI drawing.

I think WPF did a dis-service by calling the method OnRender(), it might be better termed AccumulateDrawingObjects()

This basically looks like:

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}
</code>```

I've also tried using RenderTargetBitmap and WriteableBitmap, both to an Image.Source, and written directly to a DrawingContext. The above method is faster.

Title: Fast 2D graphics in WPF

Body:
I need to draw a large amount of 2D elements in WPF, such as lines and polygons. Their position also needs to be updated constantly.

I have looked at many of the answers here which mostly suggested using DrawingVisual or overriding the OnRender function. To test these methods I've implemented a simple particle system rendering 10000 ellipses and I find that the drawing performance is still really terrible using both of these approaches. On my PC I can't get much above 5-10 frames a second. which is totally unacceptable when you consider that I easily draw 1/2 million particles smoothly using other technologies.

So my question is, am I running against a technical limitation here of WPF or am I missing something? Is there something else I can use? any suggestions welcome.

Here the code I tried

content of MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="500" Width="500" Loaded="Window_Loaded">
    <Grid Name="xamlGrid">

    </Grid>
</Window>

content of MainWindow.xaml.cs:

using System.Windows.Threading;

namespace WpfApplication1
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        EllipseBounce[]     _particles;
        DispatcherTimer     _timer = new DispatcherTimer();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            //particles with Ellipse Geometry
            _particles = new EllipseBounce[10000];

            //define area particles can bounce around in
            Rect stage = new Rect(0, 0, 500, 500);

            //seed particles with random velocity and position
            Random rand = new Random();

            //populate
            for (int i = 0; i < _particles.Length; i++)
            {
               Point pos = new Point((float)(rand.NextDouble() * stage.Width + stage.X), (float)(rand.NextDouble() * stage.Height + stage.Y));
               Point vel = new Point((float)(rand.NextDouble() * 5 - 2.5), (float)(rand.NextDouble() * 5 - 2.5));
                _particles[i] = new EllipseBounce(stage, pos, vel, 2);
            }

            //add to particle system - this will draw particles via onrender method
            ParticleSystem ps = new ParticleSystem(_particles);

            //at this element to the grid (assumes we have a Grid in xaml named 'xmalGrid'
            xamlGrid.Children.Add(ps);

            //set up and update function for the particle position
            _timer.Tick += _timer_Tick;
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 1000 / 60); //update at 60 fps
            _timer.Start();

        }

        void _timer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < _particles.Length; i++)
            {
                _particles[i].Update();
            }
        }
    }

    ///
    /// Framework elements that draws particles
    ///
    public class ParticleSystem : FrameworkElement
    {
        private DrawingGroup _drawingGroup;

        public ParticleSystem(EllipseBounce[] particles)
        {
            _drawingGroup = new DrawingGroup();

            for (int i = 0; i < particles.Length; i++)
            {
                EllipseGeometry eg = particles[i].EllipseGeometry;

                Brush col = Brushes.Black;
                col.Freeze();

                GeometryDrawing gd = new GeometryDrawing(col, null, eg);

                _drawingGroup.Children.Add(gd);
            }

        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            drawingContext.DrawDrawing(_drawingGroup);
        }
    }

    ///
    /// simple class that implements 2d particle movements that bounce from walls
    ///
    public class SimpleBounce2D
    {
        protected Point     _position;
        protected Point     _velocity;
        protected Rect     _stage;

        public SimpleBounce2D(Rect stage, Point pos,Point vel)
        {
            _stage = stage;

            _position = pos;
            _velocity = vel;
        }

        public double X
        {
            get
            {
                return _position.X;
            }
        }

        public double Y
        {
            get
            {
                return _position.Y;
            }
        }

        public virtual void Update()
        {
            UpdatePosition();
            BoundaryCheck();
        }

        private void UpdatePosition()
        {
            _position.X += _velocity.X;
            _position.Y += _velocity.Y;
        }

        private void BoundaryCheck()
        {
            if (_position.X > _stage.Width + _stage.X)
            {
                _velocity.X = -_velocity.X;
                _position.X = _stage.Width + _stage.X;
            }

            if (_position.X < _stage.X)
            {
                _velocity.X = -_velocity.X;
                _position.X = _stage.X;
            }

            if (_position.Y > _stage.Height + _stage.Y)
            {
                _velocity.Y = -_velocity.Y;
                _position.Y = _stage.Height + _stage.Y;
            }

            if (_position.Y < _stage.Y)
            {
                _velocity.Y = -_velocity.Y;
                _position.Y = _stage.Y;
            }
        }
    }

    ///
    /// extend simplebounce2d to add ellipse geometry and update position in the WPF construct
    ///
    public class EllipseBounce : SimpleBounce2D
    {
        protected EllipseGeometry _ellipse;

        public EllipseBounce(Rect stage,Point pos, Point vel, float radius)
            : base(stage, pos, vel)
        {
            _ellipse = new EllipseGeometry(pos, radius, radius);
        }

        public EllipseGeometry EllipseGeometry
        {
            get
            {
                return _ellipse;
            }
        }

        public override void Update()
        {
            base.Update();
            _ellipse.Center = _position;
        }
    }
}

Body:
The fastest WPF drawing method I have found is to:

create a DrawingGroup "backingStore".

during OnRender(), draw my drawing group to the drawing context

anytime I want, backingStore.Open() and draw new graphics objects into it

The surprising thing about this for me, coming from Windows.Forms.. is that I can update my DrawingGroup after I've added it to the DrawingContext during OnRender(). This is updating the existing retained drawing commands in the WPF drawing tree and triggering an efficient repaint.

In a simple app I've coded in both Windows.Forms and WPF (SoundLevelMonitor), this method empirically feels pretty similar in performance to immediate OnPaint() GDI drawing.

I think WPF did a dis-service by calling the method OnRender(), it might be better termed AccumulateDrawingObjects()

This basically looks like:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

I've also tried using RenderTargetBitmap and WriteableBitmap, both to an Image.Source, and written directly to a DrawingContext. The above method is faster.


问:
Coursera Scala week 3 filter method not working
I am doing coursera scala course, working on week 3 assignment. I have completed half of the functions. Stuck with filter method. I do not want an answer, what I want is understanding or hint of what I am missing.

Here is the requirement:

/**
    * This method takes a predicate and returns a subset of all the elements
    * in the original set for which the predicate is true.
    */

```<code>def filter(p: Tweet => Boolean): TweetSet = ???
</code>```

Here is my code:

```<code>override def filter(p: Tweet => Boolean): TweetSet =  filterAcc(p, new Empty)

 def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
  if(this.isEmpty)
    acc
  else if (p ( elem)) {
    left.filterAcc(p, acc incl elem)
    right.filterAcc(p, acc incl elem)
  }
  else
  {
    left.filterAcc(p, acc )
    right.filterAcc(p, acc )
  }
</code>```

Update:  Adding some more context to this problem. Here is the base class:

```<code>abstract class TweetSet {

def filter(p: Tweet => Boolean): TweetSet = ???

def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet

def union(that: TweetSet): TweetSet = ???

def isEmpty: Boolean = ???

def incl(tweet: Tweet): TweetSet

def contains(tweet: Tweet): Boolean

}
</code>```

I have two implementations Empty and NonEmpty representing sets with and without any elements.

Test Case:

```<code>val set1 = new Empty
val set2 = set1.incl(new Tweet("a", "a body", 20))
val set3 = set2.incl(new Tweet("b", "b body", 20))
val c = new Tweet("c", "c body", 7)
val d = new Tweet("d", "d body", 9)
val set4c = set3.incl(c)
val set4d = set3.incl(d)
val set5 = set4c.incl(d)

test("filter: a on set5") {
 new TestSets {
 assert(size(set5.filter(tw => tw.user == "a")) === 1) // this fails
 }
}
</code>```

Result:

[info] - filter: a on set5 * FAILED *
[info]   0 did not equal 1 (TweetSetSuite.scala:64)

答:
```<code> def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    val set = if(p(elem)) acc.incl(elem) else acc
    right.filterAcc(p, left.filterAcc(p, set))
  }
</code>```

basically you need to remember that you have to filter 3 'sets': elem, left, and right, and then combine them (join)

Body:
I am doing coursera scala course, working on week 3 assignment. I have completed half of the functions. Stuck with filter method. I do not want an answer, what I want is understanding or hint of what I am missing.

Here is the requirement:

/**
    * This method takes a predicate and returns a subset of all the elements
    * in the original set for which the predicate is true.
    */

def filter(p: Tweet => Boolean): TweetSet = ???

Here is my code:

override def filter(p: Tweet => Boolean): TweetSet =  filterAcc(p, new Empty)

 def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
  if(this.isEmpty)
    acc
  else if (p ( elem)) {
    left.filterAcc(p, acc incl elem)
    right.filterAcc(p, acc incl elem)
  }
  else
  {
    left.filterAcc(p, acc )
    right.filterAcc(p, acc )
  }

Update:  Adding some more context to this problem. Here is the base class:

abstract class TweetSet {

def filter(p: Tweet => Boolean): TweetSet = ???

def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet

def union(that: TweetSet): TweetSet = ???

def isEmpty: Boolean = ???

def incl(tweet: Tweet): TweetSet

def contains(tweet: Tweet): Boolean

}

I have two implementations Empty and NonEmpty representing sets with and without any elements.

Test Case:

val set1 = new Empty
val set2 = set1.incl(new Tweet("a", "a body", 20))
val set3 = set2.incl(new Tweet("b", "b body", 20))
val c = new Tweet("c", "c body", 7)
val d = new Tweet("d", "d body", 9)
val set4c = set3.incl(c)
val set4d = set3.incl(d)
val set5 = set4c.incl(d)

test("filter: a on set5") {
 new TestSets {
 assert(size(set5.filter(tw => tw.user == "a")) === 1) // this fails
 }
}

Result:

[info] - filter: a on set5 * FAILED *
[info]   0 did not equal 1 (TweetSetSuite.scala:64)

Body:
 def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    val set = if(p(elem)) acc.incl(elem) else acc
    right.filterAcc(p, left.filterAcc(p, set))
  }

basically you need to remember that you have to filter 3 'sets': elem, left, and right, and then combine them (join)


问:
Android: ArrayAdapter showing only one item even though the ListView isn't placed in a ScrollView
I am new to programming in Android. I encountered a problem where I need to print three items in a list View, yet getting only a single item. In many answers, I saw that ListView should't be placed in a ScrollView, I have rechecked my code, and that isn't actually the problem.

```<code>package com.apress.gerber.reminder;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class RemindersActivity extends AppCompatActivity {
private ListView mListView;
private String records[] = {"first record", "second record", "third record"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reminders);
    mListView = (ListView) findViewById(R.id.reminders_list_view);

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            R.layout.reminders_row,
            R.id.row_text,
            records);
    mListView.setAdapter(arrayAdapter);
}
}
</code>```

Xml files:-
Reminders_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:orientation="vertical">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="48dp">

    <view
        android:id="@+id/row_tab"
        class="android.view.View"
        android:layout_width="10dp"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_light"
        />

    <TextView
        android:id="@+id/row_text"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="@string/reminder"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:layout_gravity="center_vertical"
        android:padding="10dp"
        android:ellipsize="end"
        android:maxLines="1"/>

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

activity_reminders.xml

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

<ListView
    android:id="@+id/reminders_list_view"
    android:layout_width="373dp"
    android:layout_height="50dp"
    android:background="@color/dark_grey"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp"
    tools:listitem="@layout/reminders_row"/>

</RelativeLayout>
</code>```

What actually is the error occuring?

答:
If you are not going to extend your class with ArrayAdapter and customize getView method but you want to use your customized layout than your TextView must have id android:id="@android:id/text1" Or you can use android.R.layout.simple_list_item_1 in your ArrayAdapter like:

```<code>ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
        this,
        android.R.layout.simple_list_item_1,
        records);
mListView.setAdapter(arrayAdapter);
</code>```

Also for your ListView

```<code>android:layout_width="match_parent"
android:layout_height="wrap_content"
</code>```

Body:
I am new to programming in Android. I encountered a problem where I need to print three items in a list View, yet getting only a single item. In many answers, I saw that ListView should't be placed in a ScrollView, I have rechecked my code, and that isn't actually the problem.

package com.apress.gerber.reminder;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class RemindersActivity extends AppCompatActivity {
private ListView mListView;
private String records[] = {"first record", "second record", "third record"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reminders);
    mListView = (ListView) findViewById(R.id.reminders_list_view);

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            R.layout.reminders_row,
            R.id.row_text,
            records);
    mListView.setAdapter(arrayAdapter);
}
}

Xml files:-
Reminders_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:orientation="vertical">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="48dp">

    <view
        android:id="@+id/row_tab"
        class="android.view.View"
        android:layout_width="10dp"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_light"
        />

    <TextView
        android:id="@+id/row_text"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="@string/reminder"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:layout_gravity="center_vertical"
        android:padding="10dp"
        android:ellipsize="end"
        android:maxLines="1"/>

</LinearLayout>
</LinearLayout>

activity_reminders.xml

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

<ListView
    android:id="@+id/reminders_list_view"
    android:layout_width="373dp"
    android:layout_height="50dp"
    android:background="@color/dark_grey"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp"
    tools:listitem="@layout/reminders_row"/>

</RelativeLayout>

What actually is the error occuring?

Body:
If you are not going to extend your class with ArrayAdapter and customize getView method but you want to use your customized layout than your TextView must have id android:id="@android:id/text1" Or you can use android.R.layout.simple_list_item_1 in your ArrayAdapter like:

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
        this,
        android.R.layout.simple_list_item_1,
        records);
mListView.setAdapter(arrayAdapter);

Also for your ListView

android:layout_width="match_parent"
android:layout_height="wrap_content"


问:
Can I throw exception with java bean
I want to notify to class1 with exception that can or cannot change a variable. I have tried to put in propertyChange to throw a exception but i can't with this method. how can I notify class1??

class1 ->

```<code>public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla");
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}
</code>```

class2 ->

```<code>@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }
</code>```

答:
You need to use VetoableChangeListener.

See JavaDoc:

public interface VetoableChangeListener extends EventListener

A VetoableChange event gets fired whenever a bean changes a
  "constrained" property. You can register a VetoableChangeListener with
  a source bean so as to be notified of any constrained property
  updates.

void vetoableChange(PropertyChangeEvent evt)
                      throws PropertyVetoException

This method gets called when a constrained property is changed.

Parameters:
      evt - a PropertyChangeEvent object describing the event source and the property that has changed. Throws:
      PropertyVetoException - if the recipient wishes the property change to be rolled back.

Title: Can I throw exception with java bean

Body:
I want to notify to class1 with exception that can or cannot change a variable. I have tried to put in propertyChange to throw a exception but i can't with this method. how can I notify class1??

class1 ->

public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla");
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}

class2 ->

@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }


问:
React ES6 Scope of Function Declaration
I've looked around for several days and cannot seem to solve this. I have a form that handles a file upload via an XMLHTTPRequestUpload, I have an onProgress callback that I would like to call and update visually what's happening in the UI, but I can't seem to make any successful function calls from inside "onProgress".

I tried to use console.log to find the scope in which my function updateProgress is defined. 'this' inside of the uploadFile, onProgress call is the XMLHTTP request itself. So I tried it for 'AddShow', the class itself. It doesn't report an error, and lists that updateProgress is a member function of the class, but when trying to call it, I still get

```<code>AddShow.updateProgress is not a function
    at XMLHttpRequestUpload.onProgress
</code>```

So where's waldo? How do I call my function?

Here's my entire React Component Class:

```<code>export class AddShow extends React.Component {
  constructor(props) {
    super(props);

    this.handleTextChange = this.handleTextChange.bind(this);
    this.uploadFile = this.uploadFile.bind(this);
    this.updateProgress = this.updateProgress.bind(this);
  }

  // function that updates the state of the form input
  handleTextChange(evt) {
    this.props.dispatch(actions.changeShowTitleText(evt.target.value));
  }

  //function that show the progress of file upload
  updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));

    // this.props.complete = progress;
    // this.props.completeText = progress + '%';
    // this.props.ariaCompleteText = progress + ' percent';
  }

  // when 'add show' is pressed, validate form and upload
  onSubmit(e) {
    e.preventDefault();
    let titleText = this.props.showTitle;
    if (titleText < 1) {
      alert("Please provide a Show Title.");
    } else {
      // a title has been typed in, call upload with that info.
      this.uploadFile(titleText);
    }
  }

  //function that finally uploads the file given all the information
  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;
        AddShow.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }

  // set the global file variable if the input changes
  handleFileSelect(file) {
    console.log("These are the files retrieved", file.target.files[0]);
    selectedFile = file.target.files[0];
  }

  render() {
    var {dispatch, showTitle, complete, completeText, ariaCompleteText} = this.props;
    completeText = '0%';
    ariaCompleteText = "0 percent";

    return(
      <div className="row">
        <div className="column small-centered small-11 medium-8 large-6">
          <div className="container">
            <p>Drag the Video You Want to Upload to Screen</p>
            <form ref="form" onSubmit={this.onSubmit.bind(this)} className="add-show-form">
              <input type="file" placeholder="Select Video File" onChange={(evt) => this.handleFileSelect(evt)}/>
              <p ref="alertText"></p>
              <input type="text" value={this.props.showTitle} onChange={this.handleTextChange} placeholder="Show Title"/>
              <button className="button expanded">Add Show</button>
            </form>
            <div className="progress" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuetext={this.props.ariaCompleteText} aria-valuemax="100">
              <span className="progress-meter" style={{width: this.props.complete + '%'}}>
                <p className="progress-meter-text">{this.props.completeText}</p>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }
};
</code>```

答:
The easiest solution for you is to just use an arrow function which has lexical scoping and will be scoped to the context of uploadFile:

```<code>uploadFile(title) {
  var uploader = new VimeoUpload({
    // ...
    onProgress: (data) => { // <-- use arrow function
      var percent = data.loaded / data.total;
      this.updateProgress(percent);
    }
  // ...
}
</code>```

Alternatively, you can save the context in a variable and use that:

```<code>uploadFile(title) {
  var context = this; // save context
  var uploader = new VimeoUpload({
    // ...
    onProgress: function(data) {
      var percent = data.loaded / data.total;
      context.updateProgress(percent); // use context
    }
  // ...
}
</code>```

Do note that this line

```<code>AddShow.updateProgress(percent);
</code>```

attempts to access updateProgress on the function itself, not the prototype, which doesn't have this method.

If you wanted to call the function in a static manner like this, you'd need to call it on the prototype.

Title: React ES6 Scope of Function Declaration

Body:
I've looked around for several days and cannot seem to solve this. I have a form that handles a file upload via an XMLHTTPRequestUpload, I have an onProgress callback that I would like to call and update visually what's happening in the UI, but I can't seem to make any successful function calls from inside "onProgress".

I tried to use console.log to find the scope in which my function updateProgress is defined. 'this' inside of the uploadFile, onProgress call is the XMLHTTP request itself. So I tried it for 'AddShow', the class itself. It doesn't report an error, and lists that updateProgress is a member function of the class, but when trying to call it, I still get

AddShow.updateProgress is not a function
    at XMLHttpRequestUpload.onProgress

So where's waldo? How do I call my function?

Here's my entire React Component Class:

export class AddShow extends React.Component {
  constructor(props) {
    super(props);

    this.handleTextChange = this.handleTextChange.bind(this);
    this.uploadFile = this.uploadFile.bind(this);
    this.updateProgress = this.updateProgress.bind(this);
  }

  // function that updates the state of the form input
  handleTextChange(evt) {
    this.props.dispatch(actions.changeShowTitleText(evt.target.value));
  }

  //function that show the progress of file upload
  updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));

    // this.props.complete = progress;
    // this.props.completeText = progress + '%';
    // this.props.ariaCompleteText = progress + ' percent';
  }

  // when 'add show' is pressed, validate form and upload
  onSubmit(e) {
    e.preventDefault();
    let titleText = this.props.showTitle;
    if (titleText < 1) {
      alert("Please provide a Show Title.");
    } else {
      // a title has been typed in, call upload with that info.
      this.uploadFile(titleText);
    }
  }

  //function that finally uploads the file given all the information
  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;
        AddShow.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }

  // set the global file variable if the input changes
  handleFileSelect(file) {
    console.log("These are the files retrieved", file.target.files[0]);
    selectedFile = file.target.files[0];
  }

  render() {
    var {dispatch, showTitle, complete, completeText, ariaCompleteText} = this.props;
    completeText = '0%';
    ariaCompleteText = "0 percent";

    return(

Drag the Video You Want to Upload to Screen

            <form ref="form" onSubmit={this.onSubmit.bind(this)} className="add-show-form">
              <input type="file" placeholder="Select Video File" onChange={(evt) => this.handleFileSelect(evt)}/>

              <input type="text" value={this.props.showTitle} onChange={this.handleTextChange} placeholder="Show Title"/>
              <button className="button expanded">Add Show</button>
            </form>

{this.props.completeText}

    );
  }
};

Body:
The easiest solution for you is to just use an arrow function which has lexical scoping and will be scoped to the context of uploadFile:

uploadFile(title) {
  var uploader = new VimeoUpload({
    // ...
    onProgress: (data) => { // <-- use arrow function
      var percent = data.loaded / data.total;
      this.updateProgress(percent);
    }
  // ...
}

Alternatively, you can save the context in a variable and use that:

uploadFile(title) {
  var context = this; // save context
  var uploader = new VimeoUpload({
    // ...
    onProgress: function(data) {
      var percent = data.loaded / data.total;
      context.updateProgress(percent); // use context
    }
  // ...
}

Do note that this line

AddShow.updateProgress(percent);

attempts to access updateProgress on the function itself, not the prototype, which doesn't have this method.

If you wanted to call the function in a static manner like this, you'd need to call it on the prototype.


问:
C switch case with function
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

```<code>#include <stdio.h>

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}
</code>```

答:
This is a recursive implementation the Fibonacci sequence, where each number is the sum of the two preceding numbers.

The switch statement works as follows:

If i is 0, return 0

If i is 1 or 2, return 1

Otherwise, return the sum of f(i-2) and f(i-1) - this eventually boils down to the two base cases above.

Title: C switch case with function

Body:
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

#include <stdio.h>

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}


问:
Merge two object in java
I'm developping an application using spring-boot, I need to merge two object that mean that copy only the new values into another.

I tried this but it copy all the values frm obj1 to obj2:

```<code>public static void copyObj(User c1, User c2) {

        //String[] ignoredFields = { "legalForm", "email" };
        BeanUtils.copyProperties(c1, c2);
    }
</code>```

what I need is to copy only the diffrent value from c1 to c2.
This is a snippet:

```<code>**User c1**
{
    "name": "LALA",
    "email": "tst@tst.com"
}

**user c2**
{
    "name": "tata",
    "email": "email@tst.fr"
    "firsName": "toto"
    "city": "Paris"
}

**expected result:**
{
    "name": "LALA",
    "email": "tst@tst.com"
    "firsName": "toto",
    "city": "Paris"
}
</code>```

The method above return:

```<code>{
    "name": "LALA",
    "email": "tst@tst.com"
}
</code>```

Would you have any ideas ?

Best regards

答:
Here is one of ways to do:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonParser {

    JFileChooser chooser = new JFileChooser();
    File f;

    static String fn = "";
    static String js1 = "{\"name\": \"LALA\", \"email\": \"tst@tst.com\"}";
    static String js2 = "{\"name\": \"tata\", \"email\": \"email@tst.fr\", \"firsName\": \"toto\", \"city\": \"Paris\"}";
    String name = "name";
    String email = "email";
    String fName = "firsName";
    String city = "city";
    // ... other needed fields
    User u1 = null;
    User u2 = null;
    User nu = null;

    public JsonParser() {
        parseFile();
        nu = copyObj(u1, u2);
        System.out.println("\n" + nu.toShortString());
    }

    private String openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            f = chooser.getSelectedFile();
        }
        return f.getAbsolutePath();

    }

    // To parse JSON files with data
    //===========================================
    public void parseFile() {
        JSONParser parser = new JSONParser();

        try {
//            fn = openFchooser();
//            Object obj = parser.parse(new FileReader(fn));
            // To parse obj 1
            Object obj1 = parser.parse(js1);
            System.out.println("User 1: " + obj1.toString());
            System.out.println();

            JSONObject jobj1 = (JSONObject) obj1;
            String from_name = jobj1.get(name).toString();
            String from_email = jobj1.get(email).toString();
//            String from_fName = jobj1.get(fName).toString();
//            String from_city = jobj1.get(city).toString();
            u1 = new User(from_name, from_email, null, null);
//            System.out.println(u1.toString() + "\n");

            Object obj2 = parser.parse(js2);
            System.out.println("User 2: " + obj2.toString());
            JSONObject jobj2 = (JSONObject) obj2;
            from_name = jobj2.get(name).toString();
            from_email = jobj2.get(email).toString();
            String from_fName = jobj2.get(fName).toString();
            String from_city = jobj2.get(city).toString();
            u2 = new User(from_name, from_email, from_fName, from_city);
//            System.out.println(u2.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new JsonParser();
    }

    public User copyObj(User u1, User u2) {
        User nuser = new User(null, null, null, null);
        String fn1 = u1.getFirsName();
        String fn2 = u2.getFirsName();
        boolean hasUppercase1 = !fn1.equals(fn1.toLowerCase());
        boolean hasLowercase1 = !fn1.equals(fn1.toUpperCase());
        boolean hasUppercase2 = !fn2.equals(fn2.toLowerCase());
        boolean hasLowercase2 = !fn2.equals(fn2.toUpperCase());

        // To do something needed
        if (hasUppercase1 && hasLowercase2) {
            nuser.setFirsName(u1.name);
            nuser.setEmail(u1.email);
        }
        if (hasLowercase1 && hasUppercase2) {
            nuser.setFirsName(u2.name);
            nuser.setEmail(u2.email);
        }
        // also some conditions
        return nuser;
    }

    class User {

        String name = null;
        String email = null;
        String fName = null;
        String city = null;

        public User(String n, String e, String f, String c) {
            this.name = n;
            this.email = e;
            this.fName = f;
            this.city = c;
        }

        public String getFirsName() {
            return this.name;
        }

        public String setFirsName(String s) {
            return this.name = s;
        }

        public String getEmail() {
            return this.email;
        }

        public String setEmail(String s) {
            return this.email = s;
        }

        public String toString() {
            return "{\"name\":" + this.name + ", "
                    + "\"email\":" + this.email + ", "
                    + "\"firsName\":" + this.fName + ", "
                    + "\"city\":" + this.city + "\"}";
        }

        public String toShortString() {
            return "{\"name\": \"" + this.name + "\", "
                    + "\"email\": \"" + this.email + "\"}";
        }
    };
}
</code>```

OUTPUT:

```<code>User 1: {"name":"LALA","email":"tst@tst.com"}

User 2: {"city":"Paris","firsName":"toto","name":"tata","email":"email@tst.fr"}

{"name": "LALA", "email": "tst@tst.com"}
</code>```

When you want other conditions you can do it in the method copyObj(). Good Luck!

Title: Merge two object in java

Body:
I'm developping an application using spring-boot, I need to merge two object that mean that copy only the new values into another.

I tried this but it copy all the values frm obj1 to obj2:

public static void copyObj(User c1, User c2) {

        //String[] ignoredFields = { "legalForm", "email" };
        BeanUtils.copyProperties(c1, c2);
    }

what I need is to copy only the diffrent value from c1 to c2.
This is a snippet:

**User c1**
{
    "name": "LALA",
    "email": "tst@tst.com"
}

**user c2**
{
    "name": "tata",
    "email": "email@tst.fr"
    "firsName": "toto"
    "city": "Paris"
}

**expected result:**
{
    "name": "LALA",
    "email": "tst@tst.com"
    "firsName": "toto",
    "city": "Paris"
}

The method above return:

{
    "name": "LALA",
    "email": "tst@tst.com"
}

Would you have any ideas ?

Best regards

Body:
Here is one of ways to do:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonParser {

    JFileChooser chooser = new JFileChooser();
    File f;

    static String fn = "";
    static String js1 = "{\"name\": \"LALA\", \"email\": \"tst@tst.com\"}";
    static String js2 = "{\"name\": \"tata\", \"email\": \"email@tst.fr\", \"firsName\": \"toto\", \"city\": \"Paris\"}";
    String name = "name";
    String email = "email";
    String fName = "firsName";
    String city = "city";
    // ... other needed fields
    User u1 = null;
    User u2 = null;
    User nu = null;

    public JsonParser() {
        parseFile();
        nu = copyObj(u1, u2);
        System.out.println("\n" + nu.toShortString());
    }

    private String openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            f = chooser.getSelectedFile();
        }
        return f.getAbsolutePath();

    }

    // To parse JSON files with data
    //===========================================
    public void parseFile() {
        JSONParser parser = new JSONParser();

        try {
//            fn = openFchooser();
//            Object obj = parser.parse(new FileReader(fn));
            // To parse obj 1
            Object obj1 = parser.parse(js1);
            System.out.println("User 1: " + obj1.toString());
            System.out.println();

            JSONObject jobj1 = (JSONObject) obj1;
            String from_name = jobj1.get(name).toString();
            String from_email = jobj1.get(email).toString();
//            String from_fName = jobj1.get(fName).toString();
//            String from_city = jobj1.get(city).toString();
            u1 = new User(from_name, from_email, null, null);
//            System.out.println(u1.toString() + "\n");

            Object obj2 = parser.parse(js2);
            System.out.println("User 2: " + obj2.toString());
            JSONObject jobj2 = (JSONObject) obj2;
            from_name = jobj2.get(name).toString();
            from_email = jobj2.get(email).toString();
            String from_fName = jobj2.get(fName).toString();
            String from_city = jobj2.get(city).toString();
            u2 = new User(from_name, from_email, from_fName, from_city);
//            System.out.println(u2.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new JsonParser();
    }

    public User copyObj(User u1, User u2) {
        User nuser = new User(null, null, null, null);
        String fn1 = u1.getFirsName();
        String fn2 = u2.getFirsName();
        boolean hasUppercase1 = !fn1.equals(fn1.toLowerCase());
        boolean hasLowercase1 = !fn1.equals(fn1.toUpperCase());
        boolean hasUppercase2 = !fn2.equals(fn2.toLowerCase());
        boolean hasLowercase2 = !fn2.equals(fn2.toUpperCase());

        // To do something needed
        if (hasUppercase1 && hasLowercase2) {
            nuser.setFirsName(u1.name);
            nuser.setEmail(u1.email);
        }
        if (hasLowercase1 && hasUppercase2) {
            nuser.setFirsName(u2.name);
            nuser.setEmail(u2.email);
        }
        // also some conditions
        return nuser;
    }

    class User {

        String name = null;
        String email = null;
        String fName = null;
        String city = null;

        public User(String n, String e, String f, String c) {
            this.name = n;
            this.email = e;
            this.fName = f;
            this.city = c;
        }

        public String getFirsName() {
            return this.name;
        }

        public String setFirsName(String s) {
            return this.name = s;
        }

        public String getEmail() {
            return this.email;
        }

        public String setEmail(String s) {
            return this.email = s;
        }

        public String toString() {
            return "{\"name\":" + this.name + ", "
                    + "\"email\":" + this.email + ", "
                    + "\"firsName\":" + this.fName + ", "
                    + "\"city\":" + this.city + "\"}";
        }

        public String toShortString() {
            return "{\"name\": \"" + this.name + "\", "
                    + "\"email\": \"" + this.email + "\"}";
        }
    };
}

OUTPUT:

User 1: {"name":"LALA","email":"tst@tst.com"}

User 2: {"city":"Paris","firsName":"toto","name":"tata","email":"email@tst.fr"}

{"name": "LALA", "email": "tst@tst.com"}

When you want other conditions you can do it in the method copyObj(). Good Luck!


答:
Solution 1: Use static method

static updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));
}```
</div>
</div>
</p>

<p>Solution 2: Use arrow function in uploadFile method</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>uploadFile(title) {
  var uploader = new VimeoUpload({
    name: title,
    file: selectedFile,
    token: process.env.ACCESS_TOKEN,
    onProgress: function(data) => {
      var percent = data.loaded / data.total;
      // this now refers to your AddShow component
      this.updateProgress(percent);
    },
    onComplete: function(videoId, index) {
      var url = 'https://vimeo.com/' + videoId
    }
  });

  uploader.upload();
}</code>```

You cannot call addShow method directly from the Class as it is not a static method. To solve this issue I would suggest you either add a static keyword in your method so that you can invoke it from the the class directly without having to instantiate it or by using an arrow function in your uploadFile method.

Title: React ES6 Scope of Function Declaration

Body:
Solution 1: Use static method

static updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));
}

Solution 2: Use arrow function in uploadFile method

uploadFile(title) {
  var uploader = new VimeoUpload({
    name: title,
    file: selectedFile,
    token: process.env.ACCESS_TOKEN,
    onProgress: function(data) => {
      var percent = data.loaded / data.total;
      // this now refers to your AddShow component
      this.updateProgress(percent);
    },
    onComplete: function(videoId, index) {
      var url = 'https://vimeo.com/' + videoId
    }
  });

  uploader.upload();
}

You cannot call addShow method directly from the Class as it is not a static method. To solve this issue I would suggest you either add a static keyword in your method so that you can invoke it from the the class directly without having to instantiate it or by using an arrow function in your uploadFile method.


问:
Applying Data Annotations to sub properties of the View Model in MVC?
Putting simple Data Annotations on properties is great,

```<code>public class UnicornViewModel
{
   [Required]
   public string Name { get; set; }
</code>```

But lets say I'm have something like this:

```<code>public class SuperPower
{
   public class Name { get; set; }
}

public class UnicornViewModel
{
   [Required]
   public string Name { get; set; }

   public SuperPower PrimarySuperPower { get; set; }

   public SuperPower SecondarySuperPower { get; set; }
</code>```

How do I apply the Required attribute on PrimarySuperPower.Name while leaving it optional for SecondarySuperPower.Name? Preferably 1. something that ties into client side validation and 2. with out any special handling like checking the value of PrimarySuperPower.Name in the Action/Custom validator and add a ModelState error if it's empty. It would be great if there was something like:

```<code>   [Required(p => p.Name)]
   public SuperPower PrimarySuperPower { get; set; }

   public SuperPower SecondarySuperPower { get; set; }
</code>```

答:
This might be a late answer, but I found this question when searching for the same thing.
This is how I solved my particular situation:

Before I had this:

```<code>public class ProductVm
{
    //+ some other properties

    public Category Category {get; set;}
    public Category ParentCategory {get; set;}
}
</code>```

For which I wanted to have something in the likes of:

```<code>public class ProductVm
{
    //some other properties

    [DisplayName("Product Category", e => e.Description)]
    public Category Category {get; set;}
    [DisplayName("Parent Category", e => e.Description)]
    public Category ParentCategory {get; set;}
}
</code>```

I couldn't enter this in the model itself since both are the same object class.

I solved it like this (since I only needed to read the Description value in this case and not write it):

```<code>public class ProductVm
{
    //some other properties

    public Category Category {get; set;}
    public Category ParentCategory {get; set;}

    [DisplayName("Product Category")]
    public string Category => Category.Description;

    [DisplayName("Main Category")]
    public string ParentCategory => ParentCategory.Description;
}
</code>```

You could possible just rewrite it a bit more to keep the remaining private backing fields and remove the property encapsulation of the Category objects, but in my case I still needed them to be public for other uses.

Concerning the above question I would do the following:

```<code>public class UnicornViewModel
{
    [Required]
    public string Name { get; set; }

    public SuperPower PrimarySuperPower { get; set; }

    public SuperPower SecondarySuperPower { get; set; }

    [Required]
    public string PrimarySuperPowerName
    {
        get { return PrimarySuperPower.Name; }
        set { PrimarySuperPower.Name = value; }
    }

    public string SecondarySuperPowerName
    {
        get { return SecondarySuperPower.Name; }
        set { SecondarySuperPower.Name = value; }
    }
}
</code>```

And then I'd bind my View to the string properties and exclude the SuperPower properties.

Body:
Putting simple Data Annotations on properties is great,

public class UnicornViewModel
{
   [Required]
   public string Name { get; set; }

But lets say I'm have something like this:

public class SuperPower
{
   public class Name { get; set; }
}

public class UnicornViewModel
{
   [Required]
   public string Name { get; set; }

   public SuperPower PrimarySuperPower { get; set; }

   public SuperPower SecondarySuperPower { get; set; }

How do I apply the Required attribute on PrimarySuperPower.Name while leaving it optional for SecondarySuperPower.Name? Preferably 1. something that ties into client side validation and 2. with out any special handling like checking the value of PrimarySuperPower.Name in the Action/Custom validator and add a ModelState error if it's empty. It would be great if there was something like:

   [Required(p => p.Name)]
   public SuperPower PrimarySuperPower { get; set; }

   public SuperPower SecondarySuperPower { get; set; }

Body:
This might be a late answer, but I found this question when searching for the same thing.
This is how I solved my particular situation:

Before I had this:

public class ProductVm
{
    //+ some other properties

    public Category Category {get; set;}
    public Category ParentCategory {get; set;}
}

For which I wanted to have something in the likes of:

public class ProductVm
{
    //some other properties

    [DisplayName("Product Category", e => e.Description)]
    public Category Category {get; set;}
    [DisplayName("Parent Category", e => e.Description)]
    public Category ParentCategory {get; set;}
}

I couldn't enter this in the model itself since both are the same object class.

I solved it like this (since I only needed to read the Description value in this case and not write it):

public class ProductVm
{
    //some other properties

    public Category Category {get; set;}
    public Category ParentCategory {get; set;}

    [DisplayName("Product Category")]
    public string Category => Category.Description;

    [DisplayName("Main Category")]
    public string ParentCategory => ParentCategory.Description;
}

You could possible just rewrite it a bit more to keep the remaining private backing fields and remove the property encapsulation of the Category objects, but in my case I still needed them to be public for other uses.

Concerning the above question I would do the following:

public class UnicornViewModel
{
    [Required]
    public string Name { get; set; }

    public SuperPower PrimarySuperPower { get; set; }

    public SuperPower SecondarySuperPower { get; set; }

    [Required]
    public string PrimarySuperPowerName
    {
        get { return PrimarySuperPower.Name; }
        set { PrimarySuperPower.Name = value; }
    }

    public string SecondarySuperPowerName
    {
        get { return SecondarySuperPower.Name; }
        set { SecondarySuperPower.Name = value; }
    }
}

And then I'd bind my View to the string properties and exclude the SuperPower properties.