问:
How to use a library from a CDN in a Webpack project in production
I'd like to use react.min.js from a CDN in production (e.g. https://unpkg.com/react@15.3.1/dist/react.min.js)

What is the best way to get Webpack to transform my import React from 'react' statements into const React = window.React instead of building node_modules/react into the bundle?

I've been doing it with resolve.alias like this:

In index.html:

```<code><head>
  <script type="text/javascript" src="https://unpkg.com/react@15.3.1/dist/react.min.js"></script>
  <script type="text/javascript" src="/assets/bundle.js"></script>
</head>
</code>```

In webpack.prod.config.js:

```<code>alias: {
  react$: './getWindowReact',
},
</code>```

getWindowReact.js:

```<code>module.exports = window.React;
</code>```

Note: In the old question I didn't realize that building React into a Webpack bundle with NODE_ENV=production would strip out the propTypes checks.  One of the answers focuses on that.

答:
I created https://github.com/mastilver/dynamic-cdn-webpack-plugin which is doing exactly that out of the box

```<code>const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const DynamicCDNWebpackPlugin = require('dynamic-cdn-webpack-plugin')

module.exports = {
  entry: './main.js',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new HTMLWebpackPlugin(),
    new DynamicCDNWebpackPlugin()
  ]
}
</code>```

Will dynamically add unpkg.org urls and add the appropriate code in your bundle to load librairies from global

Body:
I'd like to use react.min.js from a CDN in production (e.g. https://unpkg.com/react@15.3.1/dist/react.min.js)

What is the best way to get Webpack to transform my import React from 'react' statements into const React = window.React instead of building node_modules/react into the bundle?

I've been doing it with resolve.alias like this:

In index.html:

In webpack.prod.config.js:

alias: {
  react$: './getWindowReact',
},

getWindowReact.js:

module.exports = window.React;

Note: In the old question I didn't realize that building React into a Webpack bundle with NODE_ENV=production would strip out the propTypes checks.  One of the answers focuses on that.

Body:
I created https://github.com/mastilver/dynamic-cdn-webpack-plugin which is doing exactly that out of the box

const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const DynamicCDNWebpackPlugin = require('dynamic-cdn-webpack-plugin')

module.exports = {
  entry: './main.js',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new HTMLWebpackPlugin(),
    new DynamicCDNWebpackPlugin()
  ]
}

Will dynamically add unpkg.org urls and add the appropriate code in your bundle to load librairies from global


来源: stackexchange

问:
Travis CI simple bash broken with latest update any "n" character seen as "\n" line break
Travis CI seems to be misbehaving very oddly since yesterday. I know they pushed out an update on the 21st June 2017 to Travis but this issue only started happening yesterday to me causing a total mess of one of my repo's but luckily I reverted back to the last commit where everything was still OK and have done no more commits since then just been running tests on a different test repo all day today and it's still broken.

During my Travis build process I run a number of bash scripts that do various things like create files based on templates. But since yesterday the output of any echo or printf see's any "n" character as a line break \n

For example:

This simple printf in my bash script:

```<code>for line in $(cat $INPUT1); do
printf "\t\"~${line}\"\t\t$ACTION1\n" >> whateverfile.txt
</code>```

My inputs are defined earlier as:

```<code>ACTION1="0;"
INPUT1=$TRAVIS_BUILD_DIR/myfile.txt
</code>```

Travis breaks the output of any ${line} which contains an "n" in the output.

So for example a ${line} from the cat statement that contains the word bingbot for instance should output as follows:

```<code>"~bingbot" 0;
</code>```

but Travis is doing this because it see's any n character as a line break, this below is the output of running the script with sh -x ./scriptname

```<code>bi"\t\t0;\n

+ printf \t"~gbot
</code>```

and in the actual output file this is what travis prints with printf

```<code>bi"     0;
"~gbot
</code>```

Anyone else seeing this behavior? I have tweeted and emailed them but no response yet. Tried various things to fix it and in some cases capitalising all my variables, inputs, filenames and directories fixes it but that is not a solution. What has Travis done to simple bash? or am I missing something. This has worked perfectly for over a year.

Note: my default scripts all run using #!/bin/bash I have changed them to use #!/bin/sh but it is still happening.

答:
I solved this thanks to the help of a number of people in this question - Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters

It wasn't a Travis CI issue after all. It's all explained in the link above.

ContentLicense: CC BY-SA 3.0

Body:
Travis CI seems to be misbehaving very oddly since yesterday. I know they pushed out an update on the 21st June 2017 to Travis but this issue only started happening yesterday to me causing a total mess of one of my repo's but luckily I reverted back to the last commit where everything was still OK and have done no more commits since then just been running tests on a different test repo all day today and it's still broken.

During my Travis build process I run a number of bash scripts that do various things like create files based on templates. But since yesterday the output of any echo or printf see's any "n" character as a line break \n

For example:

This simple printf in my bash script:

for line in $(cat $INPUT1); do
printf "\t\"~${line}\"\t\t$ACTION1\n" >> whateverfile.txt

My inputs are defined earlier as:

ACTION1="0;"
INPUT1=$TRAVIS_BUILD_DIR/myfile.txt

Travis breaks the output of any ${line} which contains an "n" in the output.

So for example a ${line} from the cat statement that contains the word bingbot for instance should output as follows:

"~bingbot" 0;

but Travis is doing this because it see's any n character as a line break, this below is the output of running the script with sh -x ./scriptname

bi"\t\t0;\n

+ printf \t"~gbot

and in the actual output file this is what travis prints with printf

bi"     0;
"~gbot

Anyone else seeing this behavior? I have tweeted and emailed them but no response yet. Tried various things to fix it and in some cases capitalising all my variables, inputs, filenames and directories fixes it but that is not a solution. What has Travis done to simple bash? or am I missing something. This has worked perfectly for over a year.

Note: my default scripts all run using #!/bin/bash I have changed them to use #!/bin/sh but it is still happening.


问:
Pointer arithmetic using cast to "wrong" type
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

```<code>#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}
</code>```

Here's a test driver:

```<code>#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}
</code>```

Both approaches produce the expected results:

```<code>0 0 0 0
1 1 1 1
2 2 2 2
</code>```

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

```<code>vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax
</code>```

答:
Perhaps a more robust approach would involve changing the type signature to xyz::T* (T is a template argument so you can take xyz::x or xyz::y as needed) instead of float*

Then you can use offsetof(struct xyz,T) to confidently compute the location of the start of the struct in a way that should be more resilient to future changes in its definition.

Then the rest follows as you are currently doing: once you have a pointer to the start of the struct finding its offset in the array is a valid pointer subtraction.

There is some pointer nastiness involved. But this is an approach that is used. e.g. see the container_of() macro in the linux kernel.
https://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/067/6717/6717s2.html

Body:
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}

Here's a test driver:

#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}

Both approaches produce the expected results:

0 0 0 0
1 1 1 1
2 2 2 2

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax


问:
Doctrine queryBuilder: return object not array
I have this query created with doctrine querybuilder, the return i get is an array of arrays.
I would like to get a return that is an array of objects, is this possible?

I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.

Thanks in advance.

```<code>   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId);

    return $qb->getQuery()->getResult();
</code>```

答:
Just add \Doctrine\ORM\Query::HYDRATE_ARRAY on getResult() like this

```<code>$qb->select('u', 'h.name')
   ->from('AppBundle:UserHose', 'u')
   ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
   ->where('u.userId = :userId')
   ->orderBy('u.id', 'DESC')
   ->setParameter('userId', $userId);

return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
</code>```

Body:
I have this query created with doctrine querybuilder, the return i get is an array of arrays.
I would like to get a return that is an array of objects, is this possible?

I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.

Thanks in advance.

   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId);

    return $qb->getQuery()->getResult();

Body:
Just add \Doctrine\ORM\Query::HYDRATE_ARRAY on getResult() like this

$qb->select('u', 'h.name')
   ->from('AppBundle:UserHose', 'u')
   ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
   ->where('u.userId = :userId')
   ->orderBy('u.id', 'DESC')
   ->setParameter('userId', $userId);

return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);


问:
Use function to create a new column in a DataFrame based on DataFrame variables with pandas
Have a function to assign a hex color variable based on a scale from 0-1.

In one column I have pageviews that are being assigned a scale:

```<code>df1['pvScale'] = df1['GA Page Views']/max(df1['GA Page Views'])
</code>```

But when I go to create another column and have that be based off a function for assigning hex values:

```<code>df1['hex'] = colorscale("#00ff4c", df1['pvScale']) #(orginal hex, 0-1)
</code>```

Getting this return:

```<code>"ValueError: The truth value of a Series is ambiguous."
</code>```

What's the correct syntax to perform this operation?

答:
Try using df.apply():

```<code>df1['hex'] = df['pvScale'].apply(lambda x: colorscale("#00ff4c", x))
</code>```

It will apply the colorscale function on the values in one-by-one.

Body:
Have a function to assign a hex color variable based on a scale from 0-1.

In one column I have pageviews that are being assigned a scale:

df1['pvScale'] = df1['GA Page Views']/max(df1['GA Page Views'])

But when I go to create another column and have that be based off a function for assigning hex values:

df1['hex'] = colorscale("#00ff4c", df1['pvScale']) #(orginal hex, 0-1)

Getting this return:

"ValueError: The truth value of a Series is ambiguous."

What's the correct syntax to perform this operation?

Body:
Try using df.apply():

df1['hex'] = df['pvScale'].apply(lambda x: colorscale("#00ff4c", x))

It will apply the colorscale function on the values in one-by-one.


问:
build_exectuable in julia-0.45, linux, julia.h error
There are problms with build_exectuable:
  on linux ubuntu 16.04 LTS
the command build_executable did not work (julia version 0.4.5)

The command

```<code>build_executable("test","/media/ophir74/unix/rdf_files/rdf/main_exp_pdf.jl","/media/ophir74/unix/rdf_files/rdf/target","native",force=true)
</code>```

showed the error message

/tmp/tmpqG1ttJ/start_func.c:1:19: fatal error: julia.h: No such file
  or directory compilation terminated.

the julia.h is in a different folder (/julia/src/)
yet the file that call julia.h (start_func.c)
looked for that in the same folder (/tmp/tmpqG1ttJ)

that's just about the accurate path
*** how to solve the problem??

the full message

running: gcc -g `` -I/usr/include/julia -I/src -I/src/support
  -I/usr/include /tmp/tmpqG1ttJ/start_func.c -o /usr/bin/test -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia -L/usr/lib/x86_64-linux-gnu/julia -ljulia -ltest

/tmp/tmpqG1ttJ/start_func.c:1:19: fatal error: julia.h: No such file
  or directory compilation terminated.

ERROR: failed process: Process(setenv(gcc -g -I/usr/include/julia
  -I/src -I/src/support -I/usr/include /tmp/tmpqG1ttJ/start_func.c -o /usr/bin/test -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia
  -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia/julia -L/usr/lib/x86_64-linux-gnu/julia -ljulia -ltest,Union{ASCIIString,UTF8String}["LC_PAPER=he_IL.UTF-8","LC_ADDRESS=he_IL.UTF-8","LC_MONETARY=he_IL.UTF-8","SHELL=/bin/bash","TERM=xterm-256color","LC_NUMERIC=he_IL.UTF-8","USER=root","LC_TELEPHONE=he_IL.UTF-8","LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:.tar=01;31:.tgz=01;31:.arc=01;31:.arj=01;31:.taz=01;31:.lha=01;31:.lz4=01;31:.lzh=01;31:.lzma=01;31:.tlz=01;31:.txz=01;31:.tzo=01;31:.t7z=01;31:.zip=01;31:.z=01;31:.Z=01;31:.dz=01;31:.gz=01;31:.lrz=01;31:.lz=01;31:.lzo=01;31:.xz=01;31:.bz2=01;31:.bz=01;31:.tbz=01;31:.tbz2=01;31:.tz=01;31:.deb=01;31:.rpm=01;31:.jar=01;31:.war=01;31:.ear=01;31:.sar=01;31:.rar=01;31:.alz=01;31:.ace=01;31:.zoo=01;31:.cpio=01;31:.7z=01;31:.rz=01;31:.cab=01;31:.jpg=01;35:.jpeg=01;35:.gif=01;35:.bmp=01;35:.pbm=01;35:.pgm=01;35:.ppm=01;35:.tga=01;35:.xbm=01;35:.xpm=01;35:.tif=01;35:.tiff=01;35:.png=01;35:.svg=01;35:.svgz=01;35:.mng=01;35:.pcx=01;35:.mov=01;35:.mpg=01;35:.mpeg=01;35:.m2v=01;35:.mkv=01;35:.webm=01;35:.ogm=01;35:.mp4=01;35:.m4v=01;35:.mp4v=01;35:.vob=01;35:.qt=01;35:.nuv=01;35:.wmv=01;35:.asf=01;35:.rm=01;35:.rmvb=01;35:.flc=01;35:.avi=01;35:.fli=01;35:.flv=01;35:.gl=01;35:.dl=01;35:.xcf=01;35:.xwd=01;35:.yuv=01;35:.cgm=01;35:.emf=01;35:.ogv=01;35:.ogx=01;35:.aac=00;36:.au=00;36:.flac=00;36:.m4a=00;36:.mid=00;36:.midi=00;36:.mka=00;36:.mp3=00;36:.mpc=00;36:.ogg=00;36:.ra=00;36:.wav=00;36:.oga=00;36:.opus=00;36:.spx=00;36:.xspf=00;36:","SUDO_USER=ophir74","SUDO_UID=1000","USERNAME=root","MAIL=/var/mail/root","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin","LC_IDENTIFICATION=he_IL.UTF-8","PWD=/home/ophir74","LANG=en_US.UTF-8","LC_MEASUREMENT=he_IL.UTF-8","SHLVL=1","SUDO_COMMAND=/bin/bash","HOME=/home/ophir74","LANGUAGE=en_US","LOGNAME=root","LESSOPEN=|
  /usr/bin/lesspipe
  %s","SUDO_GID=1000","DISPLAY=:0","LESSCLOSE=/usr/bin/lesspipe %s
  %s","LC_TIME=he_IL.UTF-8","XAUTHORITY=/home/ophir74/.Xauthority","LC_NAME=he_IL.UTF-8","_=/usr/bin/julia","OPENBLAS_MAIN_FREE=1"]),
  ProcessExited(1)) [1]  in build_executable at
  /home/ophir74/.julia/v0.4/BuildExecutable/src/BuildExecutable.jl:143

答:
I solved the problem.
it was problem of permissions that got messier.
and it was problem that in ubuntu the julia version doesn't upgrade through the regular command:
   "sudo apt-get dist-upgrade julia"
and that build_executable   work just on recent  julia versions

The solution
(1) uninstall ubuntu
(2) re install ubutu
(3) download julia from the website , rather than through the terminal (that presented just the 0.4.5 julia version and doesn't upgrade)
(4) open terminal in the folder of the extracted julia,
enter the full path of the folder and then continue to the "bin/julia" and press enter to work with the 0.6.0 version
(5) Pkg.add("BuildExectuable")

Just what i tried from the list with many
(that misght help others, the valubale issues were)
(1) Pkg.checkout("BuildExecutable") showed that there is problem with paths
(2) Pkg.free("BuildExecutable") Pkg.rm("BuildExecutable") did progress a bit the issue showing that the problem is with the version of Julia
(3) after various steps the disk showed full.  all the clean commands including fsck -P in recovery mode after boot did not work, and I unistall ubuntu

ContentLicense: CC BY-SA 4.0

Body:
There are problms with build_exectuable:
  on linux ubuntu 16.04 LTS
the command build_executable did not work (julia version 0.4.5)

The command

build_executable("test","/media/ophir74/unix/rdf_files/rdf/main_exp_pdf.jl","/media/ophir74/unix/rdf_files/rdf/target","native",force=true)

showed the error message

/tmp/tmpqG1ttJ/start_func.c:1:19: fatal error: julia.h: No such file
  or directory compilation terminated.

the julia.h is in a different folder (/julia/src/)
yet the file that call julia.h (start_func.c)
looked for that in the same folder (/tmp/tmpqG1ttJ)

that's just about the accurate path
*** how to solve the problem??

the full message

running: gcc -g `` -I/usr/include/julia -I/src -I/src/support
  -I/usr/include /tmp/tmpqG1ttJ/start_func.c -o /usr/bin/test -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia -L/usr/lib/x86_64-linux-gnu/julia -ljulia -ltest

/tmp/tmpqG1ttJ/start_func.c:1:19: fatal error: julia.h: No such file
  or directory compilation terminated.

ERROR: failed process: Process(setenv(gcc -g -I/usr/include/julia
  -I/src -I/src/support -I/usr/include /tmp/tmpqG1ttJ/start_func.c -o /usr/bin/test -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia
  -Wl,-rpath,/usr/lib/x86_64-linux-gnu/julia/julia -L/usr/lib/x86_64-linux-gnu/julia -ljulia -ltest,Union{ASCIIString,UTF8String}["LC_PAPER=he_IL.UTF-8","LC_ADDRESS=he_IL.UTF-8","LC_MONETARY=he_IL.UTF-8","SHELL=/bin/bash","TERM=xterm-256color","LC_NUMERIC=he_IL.UTF-8","USER=root","LC_TELEPHONE=he_IL.UTF-8","LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:.tar=01;31:.tgz=01;31:.arc=01;31:.arj=01;31:.taz=01;31:.lha=01;31:.lz4=01;31:.lzh=01;31:.lzma=01;31:.tlz=01;31:.txz=01;31:.tzo=01;31:.t7z=01;31:.zip=01;31:.z=01;31:.Z=01;31:.dz=01;31:.gz=01;31:.lrz=01;31:.lz=01;31:.lzo=01;31:.xz=01;31:.bz2=01;31:.bz=01;31:.tbz=01;31:.tbz2=01;31:.tz=01;31:.deb=01;31:.rpm=01;31:.jar=01;31:.war=01;31:.ear=01;31:.sar=01;31:.rar=01;31:.alz=01;31:.ace=01;31:.zoo=01;31:.cpio=01;31:.7z=01;31:.rz=01;31:.cab=01;31:.jpg=01;35:.jpeg=01;35:.gif=01;35:.bmp=01;35:.pbm=01;35:.pgm=01;35:.ppm=01;35:.tga=01;35:.xbm=01;35:.xpm=01;35:.tif=01;35:.tiff=01;35:.png=01;35:.svg=01;35:.svgz=01;35:.mng=01;35:.pcx=01;35:.mov=01;35:.mpg=01;35:.mpeg=01;35:.m2v=01;35:.mkv=01;35:.webm=01;35:.ogm=01;35:.mp4=01;35:.m4v=01;35:.mp4v=01;35:.vob=01;35:.qt=01;35:.nuv=01;35:.wmv=01;35:.asf=01;35:.rm=01;35:.rmvb=01;35:.flc=01;35:.avi=01;35:.fli=01;35:.flv=01;35:.gl=01;35:.dl=01;35:.xcf=01;35:.xwd=01;35:.yuv=01;35:.cgm=01;35:.emf=01;35:.ogv=01;35:.ogx=01;35:.aac=00;36:.au=00;36:.flac=00;36:.m4a=00;36:.mid=00;36:.midi=00;36:.mka=00;36:.mp3=00;36:.mpc=00;36:.ogg=00;36:.ra=00;36:.wav=00;36:.oga=00;36:.opus=00;36:.spx=00;36:.xspf=00;36:","SUDO_USER=ophir74","SUDO_UID=1000","USERNAME=root","MAIL=/var/mail/root","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin","LC_IDENTIFICATION=he_IL.UTF-8","PWD=/home/ophir74","LANG=en_US.UTF-8","LC_MEASUREMENT=he_IL.UTF-8","SHLVL=1","SUDO_COMMAND=/bin/bash","HOME=/home/ophir74","LANGUAGE=en_US","LOGNAME=root","LESSOPEN=|
  /usr/bin/lesspipe
  %s","SUDO_GID=1000","DISPLAY=:0","LESSCLOSE=/usr/bin/lesspipe %s
  %s","LC_TIME=he_IL.UTF-8","XAUTHORITY=/home/ophir74/.Xauthority","LC_NAME=he_IL.UTF-8","_=/usr/bin/julia","OPENBLAS_MAIN_FREE=1"]),
  ProcessExited(1)) [1]  in build_executable at
  /home/ophir74/.julia/v0.4/BuildExecutable/src/BuildExecutable.jl:143


问:
Round corners of table
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

```

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

答:
You only need to apply the border radius property to the outer table element, not the individual rows / columns

See here

Title: Round corners of table

Body:
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners


问:
Custom ajax validation for text length doesn't work yii2
I am trying to check the length of the text entered but without success. It is working with the required rule because i get the field is empty error but not with mine validation. My custom rule works only on form submit. Also tried to enable ajax validation of the form but again nothing.

```<code>public function rules()
    {
        return [
            [['author_id', 'title', 'review'], 'required'],
            [['author_id'], 'integer'],
            [['review'], 'string'],
            [['review'], function($attribute, $params){
                if(strlen($this->$attribute) < 10){
                    $this->addError($attribute, 'The review is too short! Minimum 10 symbols!');
                }
            }],
            [['review'], 'trim'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 255],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => News::className(), 'targetAttribute' => ['post_id' => 'id']],
        ];
    }
</code>```

My form:

```<code><?php $form=\yii\bootstrap\ActiveForm::begin([
                                'method' => 'post',
                                'options' => [
                                    'id' => 'textarea_' . $model->id . '',
                                    'class' => "textarea_review"
                                ],

                            ]) ?>

                            <input type="hidden" name="flag" value="1"/>
                            <input type="hidden" name="model_id" value="<?= $model->id ?>"/>
                            <?= $form->field($model, 'review')->textarea(['id'=>'update_text_'.$model->id.''])->label(false) ?>
                            <?= $form->field($model, 'csrf_token')->hiddenInput(['value' => $session['token']])->label(false) ?>

                            <?= Html::button('Изпрати', ['onclick'=>'editComment('.$model->id.')', 'class'=>'btn btn-primary send-button']) ?>
                            <?php \yii\bootstrap\ActiveForm::end() ?>
</code>```

Thank you in advance!

答:
perhaps skipping the inline validator and defining the string rule as follows is the best solution for you:

```<code>[['review'], 'string', 'max' => 10, 'message' =>  'The review is too short! Minimum 10 symbols!']
</code>```

If you absolutelty need a custom validator, the second best option is to
use ajax validation.

If neither of the above suit you, the you won't get away with just writing php validation rules.
you need to provide client side script to implement the same validation logic in browser.

Either define a custom validator class and override clientValidateAttribute()
or you may specify clientValidate property to the inline validator you're using in your custom rule.

Make sure you  follow the distinction between yii\validators\InlineValidatorand yii\validators\Validator when reading trough the docs

Body:
I am trying to check the length of the text entered but without success. It is working with the required rule because i get the field is empty error but not with mine validation. My custom rule works only on form submit. Also tried to enable ajax validation of the form but again nothing.

public function rules()
    {
        return [
            [['author_id', 'title', 'review'], 'required'],
            [['author_id'], 'integer'],
            [['review'], 'string'],
            [['review'], function($attribute, $params){
                if(strlen($this->$attribute) < 10){
                    $this->addError($attribute, 'The review is too short! Minimum 10 symbols!');
                }
            }],
            [['review'], 'trim'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 255],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => News::className(), 'targetAttribute' => ['post_id' => 'id']],
        ];
    }

My form:

<?php $form=\yii\bootstrap\ActiveForm::begin([
                                'method' => 'post',
                                'options' => [
                                    'id' => 'textarea_' . $model->id . '',
                                    'class' => "textarea_review"
                                ],

                            ]) ?>

                            <input type="hidden" name="flag" value="1"/>
                            <input type="hidden" name="model_id" value="<?= $model->id ?>"/>
                            <?= $form->field($model, 'review')->textarea(['id'=>'update_text_'.$model->id.''])->label(false) ?>
                            <?= $form->field($model, 'csrf_token')->hiddenInput(['value' => $session['token']])->label(false) ?>

                            <?= Html::button('Изпрати', ['onclick'=>'editComment('.$model->id.')', 'class'=>'btn btn-primary send-button']) ?>
                            <?php \yii\bootstrap\ActiveForm::end() ?>

Thank you in advance!

Body:
perhaps skipping the inline validator and defining the string rule as follows is the best solution for you:

[['review'], 'string', 'max' => 10, 'message' =>  'The review is too short! Minimum 10 symbols!']

If you absolutelty need a custom validator, the second best option is to
use ajax validation.

If neither of the above suit you, the you won't get away with just writing php validation rules.
you need to provide client side script to implement the same validation logic in browser.

Either define a custom validator class and override clientValidateAttribute()
or you may specify clientValidate property to the inline validator you're using in your custom rule.

Make sure you  follow the distinction between yii\validators\InlineValidatorand yii\validators\Validator when reading trough the docs


问:
Problem when using JXL Formula like SUM() AVG() STDEV() returns #VALUE! when it refers values from another sheet
I want to populate some values in a sheet and then use jxl Formula to get the values from that sheet and write it to another sheet...

When I try to run this sample code

``` <code>
String filename = "C:\\input.xls";
      WorkbookSettings ws = new WorkbookSettings();
      ws.setLocale(new Locale("en", "EN"));
      WritableWorkbook workbook =
      Workbook.createWorkbook(new File(filename), ws);
      WritableSheet s = workbook.createSheet("Input", 0);
      WritableSheet s1 = workbook.createSheet("Output", 1);
      s1.addCell(new Number(3, 0, 5));
      s1.addCell(new Number(3, 1, 6));
      s1.addCell(new Number(3, 2, 1));
      s1.addCell(new Number(3, 3, 6));
      s1.addCell(new Number(3, 4, 1));
      Formula formula = new Formula(3,5,"AVERAGE(Output!D1:Output!D5)");
      s.addCell(formula);

</code> ```

I am getting the last value in the AVG list has the output

=AVERAGE(Output!D5)

JAR Used : jxl 1.0.jar....

Solution tried :

1) Instead of giving it has a formula I gave it has label

Label label = new Label
  (3,5,"AVERAGE(Output!D1:Output!D5)");

I got the entire text in the cell and gave '=' before the cell.. It worked like a charm. But I want this to be done with JXL API

2) Changed the JAR to jxl 2.6.jar

Now I am getting  #VALUE! when I try to run the same. The cell content is

=AVERAGE(Output!D1:Output!D5) but still I get #VALUE!.

JAR Used : jxl 2.6.jar

This error is getting solved only when I go to that cell and press tab key or F2 key.

Please provide some solution

Regards

N.S.Balaji

答:
It looks like excel is evaluating the formula in a strange way, hence why you are seeing #VALUE!. To see why the formula is failing, click on the formula cell and then go to Tools > Formula Auditing > Evaluate Formula. You will see that the steps are:

```<code>AVERAGE(Output!D1:Output!D5)
=AVERAGE(5:Output!D5)
=AVERAGE(5:1)
=AVERAGE(#VALUE!)
=#VALUE!
</code>```

But when you execute F2+Enter on the cell, you will see that Excel changes its execution plan and gets the right answer.

I'm afraid the only thing I can think of to fix this is to use a comma-separated list, instead of a range:

```<code>Formula formula = new Formula(3,5, "AVERAGE(Output!D1,Output!D2,Output!D3,Output!D4,Output!D5)");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to populate some values in a sheet and then use jxl Formula to get the values from that sheet and write it to another sheet...

When I try to run this sample code

String filename = "C:\\input.xls";
      WorkbookSettings ws = new WorkbookSettings();
      ws.setLocale(new Locale("en", "EN"));
      WritableWorkbook workbook =
      Workbook.createWorkbook(new File(filename), ws);
      WritableSheet s = workbook.createSheet("Input", 0);
      WritableSheet s1 = workbook.createSheet("Output", 1);
      s1.addCell(new Number(3, 0, 5));
      s1.addCell(new Number(3, 1, 6));
      s1.addCell(new Number(3, 2, 1));
      s1.addCell(new Number(3, 3, 6));
      s1.addCell(new Number(3, 4, 1));
      Formula formula = new Formula(3,5,"AVERAGE(Output!D1:Output!D5)");
      s.addCell(formula);

I am getting the last value in the AVG list has the output

=AVERAGE(Output!D5)

JAR Used : jxl 1.0.jar....

Solution tried :

1) Instead of giving it has a formula I gave it has label

Label label = new Label
  (3,5,"AVERAGE(Output!D1:Output!D5)");

I got the entire text in the cell and gave '=' before the cell.. It worked like a charm. But I want this to be done with JXL API

2) Changed the JAR to jxl 2.6.jar

Now I am getting  #VALUE! when I try to run the same. The cell content is

=AVERAGE(Output!D1:Output!D5) but still I get #VALUE!.

JAR Used : jxl 2.6.jar

This error is getting solved only when I go to that cell and press tab key or F2 key.

Please provide some solution

Regards

N.S.Balaji

Body:
It looks like excel is evaluating the formula in a strange way, hence why you are seeing #VALUE!. To see why the formula is failing, click on the formula cell and then go to Tools > Formula Auditing > Evaluate Formula. You will see that the steps are:

AVERAGE(Output!D1:Output!D5)
=AVERAGE(5:Output!D5)
=AVERAGE(5:1)
=AVERAGE(#VALUE!)
=#VALUE!

But when you execute F2+Enter on the cell, you will see that Excel changes its execution plan and gets the right answer.

I'm afraid the only thing I can think of to fix this is to use a comma-separated list, instead of a range:

Formula formula = new Formula(3,5, "AVERAGE(Output!D1,Output!D2,Output!D3,Output!D4,Output!D5)");


问:
Custom seeder in laravel 5.4
how can we make custom seeder in Laravel which can read the folder name and put into a specific column in database and the sub folder's name in the next column and finally the file name in the last?

答:
Create seeder by artisan command for Users table below command run

```<code>php artisan make:seeder UsersTableSeeder
</code>```

Now in database folder find UserTableSeeder.php in this

```<code><?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}
</code>```

in this str_random for random string generate
Now, run this seeder by below command

```<code>php artisan db:seed
</code>```

Title: Custom seeder in laravel 5.4

Body:
Create seeder by artisan command for Users table below command run

php artisan make:seeder UsersTableSeeder

Now in database folder find UserTableSeeder.php in this

<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

in this str_random for random string generate
Now, run this seeder by below command

php artisan db:seed


问:
How to avoid overfitting on a simple feed forward network
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

```<code># Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

```<code>model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))
</code>```

Here are the graphs for 500 epochs

答:
First, try adding some regularization (https://keras.io/regularizers/) like with this code:

```<code>model.add(Dense(12, input_dim=12,
            kernel_regularizer=regularizers.l2(0.01),
            activity_regularizer=regularizers.l1(0.01)))
</code>```

Also, make sure to decrease your network size i.e. you don't need a hidden layer of 500 neurons - try just taking that out to decrease the representation power and maybe even another layer if it's still overfitting. Also, only use relu activation. Maybe also try increasing your dropout rate to something like 0.75 (although it's already high). You probably also don't need to run it for so many epochs - it will just begin to overfit after long enough.

Body:
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

# Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

Here are the graphs for 500 epochs

Body:
First, try adding some regularization (https://keras.io/regularizers/) like with this code:

model.add(Dense(12, input_dim=12,
            kernel_regularizer=regularizers.l2(0.01),
            activity_regularizer=regularizers.l1(0.01)))

Also, make sure to decrease your network size i.e. you don't need a hidden layer of 500 neurons - try just taking that out to decrease the representation power and maybe even another layer if it's still overfitting. Also, only use relu activation. Maybe also try increasing your dropout rate to something like 0.75 (although it's already high). You probably also don't need to run it for so many epochs - it will just begin to overfit after long enough.


问:
How to grep last two characters after a number in unix shell scripting
I am using below in .txt file for my script

```<code>abc20cb1a
abc20cb1aa
abc20cb1b
abc20cb1bb
</code>```

I want to do a particular task for aa and bb and another particular task for a and b. To be more precise and clear, the task which I am doing for lines ending in aa and bb should not work for lines ending in a and b, and similarly the task which I am doing for endings a and b should not work for aa and bb endings.

For example:

For aa and bb side I want to go to one directory.

For a and b side I want to to multiple directories.

How can I do that?

答:
Your question shows your text file as "one line".  I'm guessing that's a mistake?

Regular expressions will dig you out of this hole.

You could parse a multiline file like so:

```<code>$ cat example.txt
abc20cb1a
abc20cb1aa
abc20cb1b
abc20cb1bb

$ while read LINE; do
     echo "$LINE" | egrep '[^ab][ab]{2}$' > /dev/null
     if [ $? -eq 0 ]; then
         # double letter
         echo "Double: $LINE"
     else
         # single letter
         echo "Single: $LINE"
     fi
  done < example.txt
</code>```

Body:
I am using below in .txt file for my script

abc20cb1a
abc20cb1aa
abc20cb1b
abc20cb1bb

I want to do a particular task for aa and bb and another particular task for a and b. To be more precise and clear, the task which I am doing for lines ending in aa and bb should not work for lines ending in a and b, and similarly the task which I am doing for endings a and b should not work for aa and bb endings.

For example:

For aa and bb side I want to go to one directory.

For a and b side I want to to multiple directories.

How can I do that?

Body:
Your question shows your text file as "one line".  I'm guessing that's a mistake?

Regular expressions will dig you out of this hole.

You could parse a multiline file like so:

$ cat example.txt
abc20cb1a
abc20cb1aa
abc20cb1b
abc20cb1bb

$ while read LINE; do
     echo "$LINE" | egrep '[^ab][ab]{2}$' > /dev/null
     if [ $? -eq 0 ]; then
         # double letter
         echo "Double: $LINE"
     else
         # single letter
         echo "Single: $LINE"
     fi
  done < example.txt


问:
Mybatis loop with AND
I have a sql query of this kind of structure:

```<code>......
......
where a.id=#{x} AND b.id!=#{x}
......
</code>```

Now I want to change this query to accept a list of values of x. How should I write foreach loop for this?

答:
I would change your WHERE to the form

 SELECT ... FROM ...  WHERE a.id IN (...x...) AND b.id NOT IN (...x...)

Then, your annotation or XML would contain:

```<code>  SELECT ...
  FROM ...
  WHERE a.id IN <foreach item="item" index="index" collection="x"
        open="(" separator="," close=")">
          #{item}
    </foreach>
  AND b.id NOT IN <foreach item="item" index="index" collection="x"
        open="(" separator="," close=")">
          #{item}
    </foreach>
</code>```

This will produce more efficient SQL.

Title: Mybatis loop with AND

Body:
I have a sql query of this kind of structure:

......
......
where a.id=#{x} AND b.id!=#{x}
......

Now I want to change this query to accept a list of values of x. How should I write foreach loop for this?

Body:
I would change your WHERE to the form

 SELECT ... FROM ...  WHERE a.id IN (...x...) AND b.id NOT IN (...x...)

Then, your annotation or XML would contain:

  SELECT ...
  FROM ...
  WHERE a.id IN <foreach item="item" index="index" collection="x"
        open="(" separator="," close=")">
          #{item}
    </foreach>
  AND b.id NOT IN <foreach item="item" index="index" collection="x"
        open="(" separator="," close=")">
          #{item}
    </foreach>

This will produce more efficient SQL.


问:
EF6 (code first) Multiple nav properties on single foreign key property
When migrating my data layer from Telerik to EF6 I had POCO naming issues.
The EF model is "code first" generated from an existing database. Because i do not want to change the business layer, all migration/configuration needs to be done in the data layer. I also try to keep EF code generation from the database unchanged for future maintenance while using partial classes for keeping the legacy code intact.

So EF generates poco's with a FK reference like this:

```<code>public partial class MyPoco
{
        public Guid? MyForeignKeyDatabasePocoId { get; set; } /* Foreign key database column */

        public virtual MyForeignKeyDatabasePoco { get; set; } /* Navigation property MyForeignKeyDatabasePocoId database column */
}
</code>```

This works out of the box since the naming convention is correct (generated)
But now I like to add a navigation property based on the same database FK Id (used in the business layer),

```<code>public partial class MyPoco
{

        [ForeignKey("MyForeignKeyApplicationPoco", "MyForeignKeyDatabasePocoId")]  /* <- not possible, no constructor accepts two parms */
        public Guid? MyForeignKeyDatabasePocoId { get; set; }   /* Foreign key database column */

        public virtual MyForeignKeyDatabasePoco {get; set; }    /* Navigation property FK MyForeignKeyDatabasePocoId database column */

        public virtual MyForeignKeyApplicationPoco {get; set; } /* Navigation property FK MyForeignKeyDatabasePocoId database column */
}
</code>```

I tried decorating the Id property with [ForeignKey("MyForeignKeyApplicationPoco")] but then it complains that "MyForeignKeyDatabasePoco" doesn't have a (foreign-)key. I can't set two foreignkey decorators to the id property either.

MyForeignKeyDatabasePoco and MyForeignKeyApplicationPoco are simular, they both exist in the model.

A) Is this possible?
B) Should I change something in OnModelCreating(DbModelBuilder modelBuilder) when entity MyPoco is defined (or either or both of the fk poco's)?
C) Should I just get rid of the generated nav property in favor of the legacy business property (not the preferred option btw)

Any help would be greatly appreciated.

Edit after bubi commented

Solved it with inheritance. First the database poco is abstracted and then the application poco inherits from then database poco

```<code>public abstract partial class MyForeignKeyDatabasePoco
{
    /* EF generated code */
}

public partial class MyForeignKeyApplicationPoco : MyForeignKeyDatabasePoco
{
    /* additional things todo */
}

public partial class MyPoco
{
        public Guid? MyForeignKeyDatabasePocoId { get; set; } /* Foreign key database column */

        public virtual MyForeignKeyApplicationPoco { get; set; } /* Navigation property to MyForeignKeyDatabasePocoId database column */
}
</code>```

In the fluent model a DbSet< MyForeignKeyApplicationPoco > is added and in the fluent OnModelCreating(DbModelBuilder modelBuilder) modelBuilder.Entity< MyForeignKeyApplicationPoco >(); is added.

答:
Actually I think that it is not possible using attributes if you don't add a property with the foreign key field name. In that case you can use ForeignKey attribute setting the property as the foreign key.

Otherwise you can use fluent configuration (usually I use this way).

```<code>modelBuilder.Entity<OfficeAssignment>()
        .HasRequired(t => t.PianoDiRientro)
        .WithMany(t => t.Rates)
        .Map(d => d.MapKey("IdPianoDiRientro"));
</code>```

In this case is one to many relationship (one PianoDiRientro many Rates) and the foreign key column name is IdPianoDiRientro.

Body:
When migrating my data layer from Telerik to EF6 I had POCO naming issues.
The EF model is "code first" generated from an existing database. Because i do not want to change the business layer, all migration/configuration needs to be done in the data layer. I also try to keep EF code generation from the database unchanged for future maintenance while using partial classes for keeping the legacy code intact.

So EF generates poco's with a FK reference like this:

public partial class MyPoco
{
        public Guid? MyForeignKeyDatabasePocoId { get; set; } /* Foreign key database column */

        public virtual MyForeignKeyDatabasePoco { get; set; } /* Navigation property MyForeignKeyDatabasePocoId database column */
}

This works out of the box since the naming convention is correct (generated)
But now I like to add a navigation property based on the same database FK Id (used in the business layer),

public partial class MyPoco
{

        [ForeignKey("MyForeignKeyApplicationPoco", "MyForeignKeyDatabasePocoId")]  /* <- not possible, no constructor accepts two parms */
        public Guid? MyForeignKeyDatabasePocoId { get; set; }   /* Foreign key database column */

        public virtual MyForeignKeyDatabasePoco {get; set; }    /* Navigation property FK MyForeignKeyDatabasePocoId database column */

        public virtual MyForeignKeyApplicationPoco {get; set; } /* Navigation property FK MyForeignKeyDatabasePocoId database column */
}

I tried decorating the Id property with [ForeignKey("MyForeignKeyApplicationPoco")] but then it complains that "MyForeignKeyDatabasePoco" doesn't have a (foreign-)key. I can't set two foreignkey decorators to the id property either.

MyForeignKeyDatabasePoco and MyForeignKeyApplicationPoco are simular, they both exist in the model.

A) Is this possible?
B) Should I change something in OnModelCreating(DbModelBuilder modelBuilder) when entity MyPoco is defined (or either or both of the fk poco's)?
C) Should I just get rid of the generated nav property in favor of the legacy business property (not the preferred option btw)

Any help would be greatly appreciated.

Edit after bubi commented

Solved it with inheritance. First the database poco is abstracted and then the application poco inherits from then database poco

public abstract partial class MyForeignKeyDatabasePoco
{
    /* EF generated code */
}

public partial class MyForeignKeyApplicationPoco : MyForeignKeyDatabasePoco
{
    /* additional things todo */
}

public partial class MyPoco
{
        public Guid? MyForeignKeyDatabasePocoId { get; set; } /* Foreign key database column */

        public virtual MyForeignKeyApplicationPoco { get; set; } /* Navigation property to MyForeignKeyDatabasePocoId database column */
}

In the fluent model a DbSet< MyForeignKeyApplicationPoco > is added and in the fluent OnModelCreating(DbModelBuilder modelBuilder) modelBuilder.Entity< MyForeignKeyApplicationPoco >(); is added.

Body:
Actually I think that it is not possible using attributes if you don't add a property with the foreign key field name. In that case you can use ForeignKey attribute setting the property as the foreign key.

Otherwise you can use fluent configuration (usually I use this way).

modelBuilder.Entity<OfficeAssignment>()
        .HasRequired(t => t.PianoDiRientro)
        .WithMany(t => t.Rates)
        .Map(d => d.MapKey("IdPianoDiRientro"));

In this case is one to many relationship (one PianoDiRientro many Rates) and the foreign key column name is IdPianoDiRientro.


问:
Deferred that extends Promise
How to implement a Deferred promise that extends Promise? It's important to extend Promise for type-safe usage where a typical Promise is expected.

Following implementation

```<code>export class Deferred<T> extends Promise<T> {
  public _resolveSelf;
  public _rejectSelf;
  constructor() {
    super(
      (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject
      }
    )
  }
  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }
}
</code>```

throws TypeError: _this is undefined.

In this Typescript playground, one can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

答:
How to implement a Deferred promise that extends Promise?

Better not at all. There is absolutely no good reason to use deferreds.

And even then, a deferred that is a promise is a bad idea, you should separate the capabilities:

```<code>function defer() {
    var deferred = {};
    deferred.promise = new Promise(resolve => {
        deferred.resolve = resolve;
    });
    return deferred;
}
</code>```

One can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

Yes, that's how super works: you cannot use this until the parent constructor call returned and intitialised it. The promise executor callback gets called before that however.

You'd have to write

```<code>export class Deferred<T> extends Promise<T> {
  public resolve: T=>void;
  public reject: any=>void;
  constructor() {
    var resolveSelf, rejectSelf
    super((resolve, reject) => {
      resolveSelf = resolve
      _rejectSelf = reject
    })
    this.resolve = resolveSelf;
    this.reject = rejectSelf;
  }
}
</code>```

Title: Deferred that extends Promise

Body:
How to implement a Deferred promise that extends Promise? It's important to extend Promise for type-safe usage where a typical Promise is expected.

Following implementation

export class Deferred<T> extends Promise<T> {
  public _resolveSelf;
  public _rejectSelf;
  constructor() {
    super(
      (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject
      }
    )
  }
  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }
}

throws TypeError: _this is undefined.

In <a href="https://www.typescriptlang.org/play/#src=class%20Deferred%3CT%3E%20extends%20Promise%3CT%3E%20%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20public%20_resolveSelf%3B%0D%0A%20%20public%20_rejectSelf%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20constructor()%20%7B%0D%0A%20%20%20%20super(%0D%0A%20%20%20%20%20%20(resolve%2C%20reject)%20%3D%3E%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20this._resolveSelf%20%3D%20resolve%0D%0A%20%20%20%20%20%20%20%20this._rejectSelf%20%3D%20reject%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20)%0D%0A%20%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%20%20public%20resolve(val%3AT)%20%7B%20this._resolveSelf(val)%20%7D%0D%0A%20%20public%20reject(reason%3Aany)%20%7B%20this._rejectSelf(reason)%20%7D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0D%0A%7D%0D%0A%0D%0Aconst%20d%20%3D%20new%20Deferred%0D%0A%0D%0Ad.then(console.log)%0D%0A%0D%0Ad.resolve(10)" rel="noreferrer">this Typescript playground, one can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

Body:
How to implement a Deferred promise that extends Promise?

Better not at all. There is absolutely no good reason to use deferreds.

And even then, a deferred that is a promise is a bad idea, you should separate the capabilities:

function defer() {
    var deferred = {};
    deferred.promise = new Promise(resolve => {
        deferred.resolve = resolve;
    });
    return deferred;
}

One can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

Yes, that's how super works: you cannot use this until the parent constructor call returned and intitialised it. The promise executor callback gets called before that however.

You'd have to write

export class Deferred<T> extends Promise<T> {
  public resolve: T=>void;
  public reject: any=>void;
  constructor() {
    var resolveSelf, rejectSelf
    super((resolve, reject) => {
      resolveSelf = resolve
      _rejectSelf = reject
    })
    this.resolve = resolveSelf;
    this.reject = rejectSelf;
  }
}


问:
Trying to redesign JMS configuration as Spring Integration: Redelivery policies
My legacy configuration exposes a ConnectionFactory @Bean of type ActiveMQConnectionFactory, with custom redelivery through  activeMQConnectionFactory.setRedeliveryPolicy(..).

I found out that Spring Integration DSL allows redeliveries on the handle operation as well by means of RequestHandlerRetryAdvice, which can be configured for instance with an ExponentialBackOffPolicy.

I am wondering if they are triggering the same code at the lower level (not sure its a client thing or a signaling thing to the broker), and if not, whether they are equivalent and whether can I safely replace the abstract version without missing any configuratbility

答:
No; it's completely different and has nothing to do with JMS and retrying incoming deliveries.

The retry advice is generally used to retry outgoing requests, e.g. an http request, or a send to JMS.


问:
Apache Drill unusably slow with S3 data source?
I am trying to use Apache Drill with an S3 bucket, but it is incredibly slow.

I have about 20,000 JSON files. I can get results from them locally in a few seconds, e.g.:

```<code>> select count(*) from dfs.`/path/to/my/files/*.json`;
</code>```

returns after less than 2 seconds.

Trying to run the exact same query on the exact same files in an S3 bucket is failing to complete even after 10 minutes:

```<code>> select count(*) from s3.`releases`;
</code>```

Why is this? I thought the whole point of Drill was that it was fast on big datasets.

My S3 connection itself is OK, e.g. SHOW files shows me my available folders just fine in a reasonable amount of time, and there's nothing wrong with my network connection either.

答: its not a direct answer to your question but you should look at athena if you want to query on s3 bucket and you have large dataset</p>

Body:
I am trying to use Apache Drill with an S3 bucket, but it is incredibly slow.

I have about 20,000 JSON files. I can get results from them locally in a few seconds, e.g.:

> select count(*) from dfs.`/path/to/my/files/*.json`;

returns after less than 2 seconds.

Trying to run the exact same query on the exact same files in an S3 bucket is failing to complete even after 10 minutes:

> select count(*) from s3.`releases`;

Why is this? I thought the whole point of Drill was that it was fast on big datasets.

My S3 connection itself is OK, e.g. SHOW files shows me my available folders just fine in a reasonable amount of time, and there's nothing wrong with my network connection either.


问:
Why does comparing a varchar to a numerical value always return True?
I've got the following table in MySQL (MySQL Server 5.7):

```<code>CREATE TABLE IF NOT EXISTS SIMCards (
SIMCardID INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
ICCID VARCHAR(50) UNIQUE NOT NULL,
MSISDN BIGINT UNSIGNED UNIQUE);

INSERT INTO SIMCards (ICCID, MSISDN) VALUES
(89441000154687982548, 905511528749),
(89441000154687982549, 905511528744),
(89441000154687982547, 905511528745);
</code>```

I then run the following query:

```<code>SELECT SIMCardID FROM SIMCards WHERE ICCID = 89441000154687982549;
</code>```

However, rather than returning just the relevant row, it returns all of them. If I surround the ICCID in quotes, it works fine, e.g.:

```<code>SELECT SIMCardID FROM SIMCards WHERE ICCID = '89441000154687982549';
</code>```

Why does the first SELECT query not work as I expected?

答:
An integer in MySQL has a maximum value (unsigned) of 4294967295.  Your IDs are substantially larger than that number.  As a result, if you select * from your database by integer, your behavior is going to be undefined because the number you are selecting by cannot be represented by an integer.

I'm not sure exactly why you are getting the results that you are getting, but I do know that trying to select by an integer when your data can't be represented by an integer will definitely not work.

Edit to add detail I forgot: even a bigint in MySQL is not large enough to represent your IDs.  So you need to make sure and just always use strings.

Body:
I've got the following table in MySQL (MySQL Server 5.7):

CREATE TABLE IF NOT EXISTS SIMCards (
SIMCardID INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
ICCID VARCHAR(50) UNIQUE NOT NULL,
MSISDN BIGINT UNSIGNED UNIQUE);

INSERT INTO SIMCards (ICCID, MSISDN) VALUES
(89441000154687982548, 905511528749),
(89441000154687982549, 905511528744),
(89441000154687982547, 905511528745);

I then run the following query:

SELECT SIMCardID FROM SIMCards WHERE ICCID = 89441000154687982549;

However, rather than returning just the relevant row, it returns all of them. If I surround the ICCID in quotes, it works fine, e.g.:

SELECT SIMCardID FROM SIMCards WHERE ICCID = '89441000154687982549';

Why does the first SELECT query not work as I expected?


问:
TypeError function SwaggerSchemaView not JSON serializable
TypeError at /docs/  is not JSON serializable

Here's my code which is leading to this,

def schema_view(request):

        schema_view = get_swagger_view(title='Docs API')
        return Response(schema_view)```
</div>
</div>
</p>

<p>Here's the traceback from error log </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-html lang-html prettyprint-override"><code>Environment:

Request Method: GET
Request URL: http://localhost:8000/test/docs/

Django Version: 1.10.1
Python Version: 2.7.9
Installed Applications:
['corsheaders',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'test_app',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_auth',
 'rest_auth.registration',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.twitter',
 'rest_framework_swagger']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/template/response.py" in render
  109.             self.content = self.rendered_content

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in render
  703.         context = self.get_context(data, accepted_media_type, renderer_context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in get_context
  661.             'content': self.get_content(renderer, data, accepted_media_type, renderer_context),

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in get_content
  411.         content = renderer.render(data, accepted_media_type, renderer_context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in render
  105.             separators=separators

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
  250.         sort_keys=sort_keys, **kw).encode(obj)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
  209.             chunks = list(chunks)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in _iterencode
  442.             o = _default(o)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/utils/encoders.py" in default
  70.         return super(JSONEncoder, self).default(obj)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
  184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /test/docs/
Exception Value: <function SwaggerSchemaView at 0x10ee8aa28> is not JSON serializable</code>```

PS: Why is stackoverflow not allowing me to post this , stating it is only code , please add more details? What else should I be adding?

答:
I asume you are using Response from restframework. The Response object needs a serializable object as data. You are passing a view as argument, that's not serializable. You can try pass a dictionary:

```<code>def schema_view(request):

    schema_view = get_swagger_view(title='Docs API')
    dic_data = {'schema_view': schema_view}
    return Response(dic_data)
</code>```

http://www.django-rest-framework.org/api-guide/responses/

Body:
TypeError at /docs/  is not JSON serializable

Here's my code which is leading to this,

def schema_view(request):

        schema_view = get_swagger_view(title='Docs API')
        return Response(schema_view)

Here's the traceback from error log

Environment:

Request Method: GET
Request URL: http://localhost:8000/test/docs/

Django Version: 1.10.1
Python Version: 2.7.9
Installed Applications:
['corsheaders',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'test_app',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_auth',
 'rest_auth.registration',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.twitter',
 'rest_framework_swagger']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/django/template/response.py" in render
  109.             self.content = self.rendered_content

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in render
  703.         context = self.get_context(data, accepted_media_type, renderer_context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in get_context
  661.             'content': self.get_content(renderer, data, accepted_media_type, renderer_context),

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in get_content
  411.         content = renderer.render(data, accepted_media_type, renderer_context)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/renderers.py" in render
  105.             separators=separators

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
  250.         sort_keys=sort_keys, **kw).encode(obj)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
  209.             chunks = list(chunks)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in _iterencode
  442.             o = _default(o)

File "/Users/user/projects/test/testx/lib/python2.7/site-packages/rest_framework/utils/encoders.py" in default
  70.         return super(JSONEncoder, self).default(obj)

File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
  184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /test/docs/
Exception Value: <function SwaggerSchemaView at 0x10ee8aa28> is not JSON serializable

PS: Why is stackoverflow not allowing me to post this , stating it is only code , please add more details? What else should I be adding?

Body:
I asume you are using Response from restframework. The Response object needs a serializable object as data. You are passing a view as argument, that's not serializable. You can try pass a dictionary:

def schema_view(request):

    schema_view = get_swagger_view(title='Docs API')
    dic_data = {'schema_view': schema_view}
    return Response(dic_data)

http://www.django-rest-framework.org/api-guide/responses/


问:
Amazon AWS connection error
I have just setup my first Redshift cluster and attempting to connect to it via SQL Workbench to be able to create tables.

I have followed the directions for installing and configuring SQL Workbench here: http://docs.aws.amazon.com/redshift/latest/mgmt/connecting-using-workbench.html

I have also downloaded and configured both the 4.0 and 4.1 version of the Redshift JDBC driver and attempted to use both.

When I configure a connection using the JDBC URL provided in the cluster configuration, the SQL Workbench attempts to connect and then I receive the following error:

Amazon(500150) Error setting/closing connection: Connection timed out:
  connect.

答: One workaround is to replace the hostname in the JDBC URL with the public IP of the cluster, that worked for me!</p>

Title: Amazon AWS connection error


问:
How to preserve formatting when using capture.output in R Shiny
I used capture.output to capture the printed output. However, the result displayed using renderPrint is very messy (see Image 1 attached). Is there a way to display it while preserving its original formatting (Image 2 attached)?

Any suggestion is greatly appreciated. Thank you!

Here are some lines of my codes:

in server.R

```<code>nway_result      <- reactiveValues()

nway_result$df <- capture.output(Nway(var_dd$selected, mynode$selected), file= NULL)

    output$nway <- renderPrint({
        if (input$dd_options == 6) {
            nway_result$df
        }
    })
</code>```

in ui.R

```<code>verbatimTextOutput('nway')
</code>```

image 1:

image 2:

答:
Here is some code I'm currently using for one of my projects. It displays the output of a lm call together with an echoed version of the call.

```<code>library(shiny)
library(evaluate)

shinyApp(
  fluidPage(verbatimTextOutput("text")),
  function(input, output)
    output$text <- renderText(
      paste(
        capture.output(replay(
          evaluate(function()
            lm(mpg ~ cyl, data = mtcars)
          )
        )),
        collapse = "\n")
    )
)
</code>```

Since you don't need the call to be echoed, this simplified version should do what you want.

```<code># context: server.R
output$nway <- renderText({
    if (input$dd_options == 6) {
        paste(nway_result$df, collapse = "\n")
    }
})

# context: ui.R
verbatimTextOutput("nway")
</code>```

Body:
I used capture.output to capture the printed output. However, the result displayed using renderPrint is very messy (see Image 1 attached). Is there a way to display it while preserving its original formatting (Image 2 attached)?

Any suggestion is greatly appreciated. Thank you!

Here are some lines of my codes:

in server.R

nway_result      <- reactiveValues()

nway_result$df <- capture.output(Nway(var_dd$selected, mynode$selected), file= NULL)

    output$nway <- renderPrint({
        if (input$dd_options == 6) {
            nway_result$df
        }
    })

in ui.R

verbatimTextOutput('nway')

image 1:

image 2:

Body:
Here is some code I'm currently using for one of my projects. It displays the output of a lm call together with an echoed version of the call.

library(shiny)
library(evaluate)

shinyApp(
  fluidPage(verbatimTextOutput("text")),
  function(input, output)
    output$text <- renderText(
      paste(
        capture.output(replay(
          evaluate(function()
            lm(mpg ~ cyl, data = mtcars)
          )
        )),
        collapse = "\n")
    )
)

Since you don't need the call to be echoed, this simplified version should do what you want.

# context: server.R
output$nway <- renderText({
    if (input$dd_options == 6) {
        paste(nway_result$df, collapse = "\n")
    }
})

# context: ui.R
verbatimTextOutput("nway")


问:
Could not find com.android.tools.build:gradle:3.2
After i installed Android Studio 2.3 and updated my SDK then the following  error occurs. What can be done to solve this issue?</p>

答:
use this in build.gradle.project

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

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'

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

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
</code>```

and this in build.gradle.module

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.madridistansit.mapapplication"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
}
</code>```

Body:
use this in build.gradle.project

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

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'

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

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir

and this in build.gradle.module

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.madridistansit.mapapplication"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
}


问:
Understanding GroupBY
I have a table in SQL Server where personal entries and exits are recorded.
There are multiple hours of entry or exit on the same day. What I need is to recover the first entry and the last exit of the day.

```<code>Date       hour   Clock
------------------------
01/01/2017 09:00  1
01/01/2017 11:30  2
01/01/2017 17:00  2
02/01/2017  7:59  1
02/01/2017 16:00  1
</code>```

I have this SQL query that works correctly.

```<code>SELECT
    d.Date,
    MIN(d.hour) as Entry,
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC
</code>```

BUT if I add 2 more columns to the query

```<code>SELECT
    d.Date,
    d.clock as ClockEntry,       -- Aggregated column to display
    MIN(d.hour) as Entry,
    dt.clock as ClockExit,       -- Aggregated column to display
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC
</code>```

I get this error:

Column '# temp1.clock' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I just need to group by the field "date", I do not want to add more conditions to the GROUP BY.. How could I solve it?

I want this result

```<code>DATE        ClockEntry     Entry    ClockExit    Exit
-------------------------------------------------------
01/01/2017     1           09:00        2        17:00
02/01/2017     1            7:59        1        16:00
</code>```

答:
GROUP BY Method

If you know that only a single value will get out the clock column,

just aggregate the values with a MAX or MIN aggregate function for example like this :

```<code>SELECT
d.Date,
MIN(d.clock) as ClockEntry,
MIN(d.hour) as Entry,
MAX(dt.clock) as ClockExit,
MAX(dt.hour) as Exit

FROM #temp1 AS d
LEFT JOIN #temp1 AS dt
ON d.Date= dt.Date
GROUP BY   d.Date
order by Date desc
</code>```

Or if you have multiple clock values and want to see them all,

add them to the GROUP BY statement :

```<code>SELECT
d.Date,
d.clock as ClockEntry,
MIN(d.hour) as Entry,
dt.clock as ClockExit,
MAX(dt.hour) as Exit

FROM #temp1 AS d
LEFT JOIN #temp1 AS dt
ON d.Date= dt.Date
GROUP BY   d.Date, d.clock, dt.clock
order by Date desc
</code>```

ORDER BY Method

Use a cursor or a Common Table Expression for each date to get both first entry and last exit.

First Entry for a given date

```<code>SELECT TOP 1 d.date, d.clock as ClockEntry, d.hour as Entry
FROM #temp1 AS d
WHERE d.date = @myDate
ORDER BY d.hour ASC
</code>```

Last Exit for a given date

```<code>SELECT TOP 1 d.date, d.clock as ClockExit, d.hour as Exit
FROM #temp1 AS d
WHERE d.date = @myDate
ORDER BY d.hour DESC
</code>```

Reference :

GROUP BY Documentation

AGGREGATE FUNCTIONS

Title: Understanding GroupBY

Body:
I have a table in SQL Server where personal entries and exits are recorded.
There are multiple hours of entry or exit on the same day. What I need is to recover the first entry and the last exit of the day.

Date       hour   Clock
------------------------
01/01/2017 09:00  1
01/01/2017 11:30  2
01/01/2017 17:00  2
02/01/2017  7:59  1
02/01/2017 16:00  1

I have this SQL query that works correctly.

SELECT
    d.Date,
    MIN(d.hour) as Entry,
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC

BUT if I add 2 more columns to the query

SELECT
    d.Date,
    d.clock as ClockEntry,       -- Aggregated column to display
    MIN(d.hour) as Entry,
    dt.clock as ClockExit,       -- Aggregated column to display
    MAX(dt.hour) as Exit
FROM
    #temp1 AS d
LEFT JOIN
    #temp1 AS dt ON d.Date = dt.Date
GROUP BY
    d.Date
ORDER BY
    Date DESC

I get this error:

Column '# temp1.clock' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I just need to group by the field "date", I do not want to add more conditions to the GROUP BY.. How could I solve it?

I want this result

DATE        ClockEntry     Entry    ClockExit    Exit
-------------------------------------------------------
01/01/2017     1           09:00        2        17:00
02/01/2017     1            7:59        1        16:00

Body:
GROUP BY Method

If you know that only a single value will get out the clock column,

just aggregate the values with a MAX or MIN aggregate function for example like this :

SELECT
d.Date,
MIN(d.clock) as ClockEntry,
MIN(d.hour) as Entry,
MAX(dt.clock) as ClockExit,
MAX(dt.hour) as Exit

FROM #temp1 AS d
LEFT JOIN #temp1 AS dt
ON d.Date= dt.Date
GROUP BY   d.Date
order by Date desc

Or if you have multiple clock values and want to see them all,

add them to the GROUP BY statement :

SELECT
d.Date,
d.clock as ClockEntry,
MIN(d.hour) as Entry,
dt.clock as ClockExit,
MAX(dt.hour) as Exit

FROM #temp1 AS d
LEFT JOIN #temp1 AS dt
ON d.Date= dt.Date
GROUP BY   d.Date, d.clock, dt.clock
order by Date desc

ORDER BY Method

Use a cursor or a Common Table Expression for each date to get both first entry and last exit.

First Entry for a given date

SELECT TOP 1 d.date, d.clock as ClockEntry, d.hour as Entry
FROM #temp1 AS d
WHERE d.date = @myDate
ORDER BY d.hour ASC

Last Exit for a given date

SELECT TOP 1 d.date, d.clock as ClockExit, d.hour as Exit
FROM #temp1 AS d
WHERE d.date = @myDate
ORDER BY d.hour DESC

Reference :

GROUP BY Documentation

AGGREGATE FUNCTIONS


问:
Open XML change fontsize of table
```<code>for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));

        tr.Append(tc);

    }
    table.Append(tr);
}
</code>```

I want to change fontsize in table cell. Can you help me with that? I don't know why they didn't add a property for cell fontsize.

答:
To change the fontsize of a table cell, you need to add a RunProperties to the  Run.  The fontsize is specified inside a FontSize element inside that RunProperties.

For example to change all of your entries to fontsize 18, your code would look like:

```<code>for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        var run = new DocumentFormat.OpenXml.Wordprocessing.Run();
        var text = new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]);

        // your old code for reference:  tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));

        RunProperties runProperties1 = new RunProperties();
        FontSize fontSize1 = new FontSize(){ Val = "36" };
        runProperties1.Append(fontSize1);

        run.Append(runProperties1);
        run.Append(text);

        paragraph.Append(run);
        tc.Append(paragraph);

        tr.Append(tc);

    }
    table.Append(tr);
}
</code>```

Title: Open XML change fontsize of table

Body:
for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));

        tr.Append(tc);

    }
    table.Append(tr);
}

I want to change fontsize in table cell. Can you help me with that? I don't know why they didn't add a property for cell fontsize.

Body:
To change the fontsize of a table cell, you need to add a RunProperties to the  Run.  The fontsize is specified inside a FontSize element inside that RunProperties.

For example to change all of your entries to fontsize 18, your code would look like:

for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        var run = new DocumentFormat.OpenXml.Wordprocessing.Run();
        var text = new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]);

        // your old code for reference:  tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));

        RunProperties runProperties1 = new RunProperties();
        FontSize fontSize1 = new FontSize(){ Val = "36" };
        runProperties1.Append(fontSize1);

        run.Append(runProperties1);
        run.Append(text);

        paragraph.Append(run);
        tc.Append(paragraph);

        tr.Append(tc);

    }
    table.Append(tr);
}


问:
help me wrap up a slider into a function I can call
A while ago I posted a question about a jquery slider here

This now works a treat but I now need to wrap it up in a function for each day of the week so I can pass in values as some of the values are hard coded. I've tried doing this and Firebugs telling me that slider is undefined.

All I want to do is call the function seven times for each day of the week and pass in the id for the slider, id for the div that holds the times, the id for the div that holds the generated table, the id for the table itself and an id for the button.

The current code is this:

```<code>var startTime;
var endTime;

$("#slider-range").slider({
    range: true, min: 0, max: 1439, values: [540, 1020], step:5, slide: slideTime, /*change: */});
function slideTime(event, ui){
    var minutes0 = parseInt($("#slider-range").slider("values", 0) % 60);
    var hours0 = parseInt($("#slider-range").slider("values", 0) / 60 % 24);
    var minutes1 = parseInt($("#slider-range").slider("values", 1) % 60);
    var hours1 = parseInt($("#slider-range").slider("values", 1) / 60 % 24);
    startTime = getTime(hours0, minutes0);
    endTime = getTime(hours1, minutes1);
    $("#time").html('<p>Opening time: ' + startTime + '</p><p>Closing time: ' + endTime + '</p>');
function getTime(hours, minutes) {
    minutes = minutes + "";
    if (hours == 12) {
    hours = 12;
}
if (hours > 12) {
    hours = hours;
}
if (minutes.length == 1) {
    minutes = "0" + minutes;
}
return hours + ":" + minutes ;

function getTimeloop(minutesloop) {
    minutesloop = minutesloop + "";
    if (minutesloop.length == 1) {
        minutesloop = "0" + minutesloop;
    }
returnminuetsloop;
}                                   }
                                        slideTime();
                                        $('#btnUpdatetable').click(function(){
var startLoop = parseInt($("#slider-range").slider("values", 0));
var endLoop = parseInt($("#slider-range").slider("values", 1));
$('#bookingTimesTable').remove();
$('<table id="bookingTimesTable">').appendTo('#generatedResultTable');
for(i = startLoop; i < endLoop; i+=5)
{
$('<tr><td style="width:145px; padding-left: 10px;">' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '</td><td style="padding-left: 10px;" ><input class="chx" name="' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '" type="checkbox" value="' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '" /></td></tr>').appendTo('#bookingTimesTable');
}
var i=0;
var period = $('#cboBooking').val();

$('.chx').each(function(){
  $(this).attr('checked',(i % period ==0));
  i++;
});
$('#bookingTimesTable tr:odd').css('background','#dedede');
});
</code>```

If you could help me on this that would be great! Its being implemented for seven days of the week on a tabbed interface and I really want to get it up and running fast

Dan

答:
Just a quick note of assistance... Wrap the entire thing in a constructor function, which will form a closure upon all of the contained variables and functions. Then pass in what you would like to redefine as function arguments:

```<code>function BookingSlider (sliderId, timesDivId, tableDivId, tableId, buttonId) {
    // your code
}
</code>```

Use this constructor to instantiate new instances of BookingSlider, passing in the appropriate values:

```<code>var bsMonday = new BookingSlider('slider-range', 'time', 'generatedResultTable', 'bookingTimesTable', 'btnUpdatetable');
</code>```

Make sure you substitute all string constants with the appropriate arguments in your function:

```<code>'#btnUpdatetable'
</code>```

becomes

```<code>'#' + buttonId
</code>```

Body:
A while ago I posted a question about a jquery slider here

This now works a treat but I now need to wrap it up in a function for each day of the week so I can pass in values as some of the values are hard coded. I've tried doing this and Firebugs telling me that slider is undefined.

All I want to do is call the function seven times for each day of the week and pass in the id for the slider, id for the div that holds the times, the id for the div that holds the generated table, the id for the table itself and an id for the button.

The current code is this:

var startTime;
var endTime;

$("#slider-range").slider({
    range: true, min: 0, max: 1439, values: [540, 1020], step:5, slide: slideTime, /*change: */});
function slideTime(event, ui){
    var minutes0 = parseInt($("#slider-range").slider("values", 0) % 60);
    var hours0 = parseInt($("#slider-range").slider("values", 0) / 60 % 24);
    var minutes1 = parseInt($("#slider-range").slider("values", 1) % 60);
    var hours1 = parseInt($("#slider-range").slider("values", 1) / 60 % 24);
    startTime = getTime(hours0, minutes0);
    endTime = getTime(hours1, minutes1);
    $("#time").html('
Opening time: ' + startTime + '

Closing time: ' + endTime + '
');
function getTime(hours, minutes) {
    minutes = minutes + "";
    if (hours == 12) {
    hours = 12;
}
if (hours > 12) {
    hours = hours;
}
if (minutes.length == 1) {
    minutes = "0" + minutes;
}
return hours + ":" + minutes ;

function getTimeloop(minutesloop) {
    minutesloop = minutesloop + "";
    if (minutesloop.length == 1) {
        minutesloop = "0" + minutesloop;
    }
returnminuetsloop;
}                                   }
                                        slideTime();
                                        $('#btnUpdatetable').click(function(){
var startLoop = parseInt($("#slider-range").slider("values", 0));
var endLoop = parseInt($("#slider-range").slider("values", 1));
$('#bookingTimesTable').remove();
$('
').appendTo('#generatedResultTable');
for(i = startLoop; i < endLoop; i+=5)
{
$('
' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '	<input class="chx" name="' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '" type="checkbox" value="' + parseInt(i/ 60 % 24) + ':' +  getTimeloop(parseInt(i % 60)) + '" />
').appendTo('#bookingTimesTable');
}
var i=0;
var period = $('#cboBooking').val();

$('.chx').each(function(){
  $(this).attr('checked',(i % period ==0));
  i++;
});
$('#bookingTimesTable tr:odd').css('background','#dedede');
});

If you could help me on this that would be great! Its being implemented for seven days of the week on a tabbed interface and I really want to get it up and running fast

Dan

Body:
Just a quick note of assistance... Wrap the entire thing in a constructor function, which will form a closure upon all of the contained variables and functions. Then pass in what you would like to redefine as function arguments:

function BookingSlider (sliderId, timesDivId, tableDivId, tableId, buttonId) {
    // your code
}

Use this constructor to instantiate new instances of BookingSlider, passing in the appropriate values:

var bsMonday = new BookingSlider('slider-range', 'time', 'generatedResultTable', 'bookingTimesTable', 'btnUpdatetable');

Make sure you substitute all string constants with the appropriate arguments in your function:

'#btnUpdatetable'

becomes

'#' + buttonId