问:
ncurses: init_color() has no effect
Trying to define color pairs, I was getting strange results. All 256 colors are already defined, and attempt to change any color with init_color() has no affect.

I'm using Putty with 256-colors enabled and TERM=xterm-256color (also putty-256color), ncurses 6.0 compiled with --enable-widec and --enable-ext-colors. This shows all colors are defined and the init_color() doesn't change anything even though it succeeds:

```<code>init_scr();
start_color();
if (has_colors() && COLORS == 256 && can_change_color()) {
  NCURSES_COLOR_T f;
  for (f = 1; f < 256; f++) {
    if (init_pair(f, f, COLOR_BLACK) == ERR) break;
    attron(COLOR_PAIR(f));
    printw("(%d)", f);
    attroff(COLOR_PAIR(f));
    refresh();
  }
  getch();
  clear();
  for (f = 1; f < 256; f++) {
    if (init_color(f, 0, 0, f*3) == ERR) break;
    if (init_pair(f, f, COLOR_BLACK) == ERR) break;
    attron(COLOR_PAIR(f));
    printw("(%d)", f);
    attroff(COLOR_PAIR(f));
    refresh();
  }
  getch();
  clear();
}
</code>```

I've read that the default colors can't be changed, but only refers to COLOR_BLACK, etc (0-7).

Where are these 256 default colors defined and why can't I change them? If they can't be changed, I could make use of the colors defined, but only if I can rely on them being the same on any 256-color capable terminal.

答:
short: PuTTY doesn't do that, ncurses can't tell if PuTTY can...

long:

In ncurses, the init_color function checks its parameters (in the example given, those appear okay if your $TERM is "xterm-256color"), as well as checking if the terminal description has the initc (initialize_color) capability.  If that is missing or cancelled, ncurses returns an error.

However, that's only the terminal description.  ncurses cannot tell if you have chosen an incorrect or inappropriate terminal description.

In a quick check, PuTTY doesn't respond to the control sequence which is used in initc.  This is a known limitation, as indicated in the (more appropriate) terminal description putty-256color provided by ncurses:

```<code>putty-256color|PuTTY 0.58 with xterm 256-colors,
        use=xterm+256setaf, use=putty,
</code>```

That xterm+256setaf is used for terminals whose palette is hard-coded.  PuTTY is not the only terminal which both sets TERM=xterm` and lacks the ability to change its palette.  If you happen to be using an old version of the terminal database, you may be misled, since that error was fixed in 2014:

```<code># 2014-03-30
#       * cancel ccc in putty-256color and konsole-256color for consistency
#         with the cancelled initc capability (patch by Sven Zuhlsdorf).
#       * add xterm+256setaf building block for various terminals which only
#         get the 256-color feature half-implemented -TD
#       * updated "st" entry (leaving the 0.1.1 version as "simpleterm") to
#         0.4.1 -TD
#
</code>```

Like the other terminals whose developers set TERM=xterm (or TERM=xterm-256color), there are differences between those and xterm.

Further reading:

Why not just use TERM set to "xterm"?

Title: ncurses: init_color() has no effect

Body:
Trying to define color pairs, I was getting strange results. All 256 colors are already defined, and attempt to change any color with init_color() has no affect.

I'm using Putty with 256-colors enabled and TERM=xterm-256color (also putty-256color), ncurses 6.0 compiled with --enable-widec and --enable-ext-colors. This shows all colors are defined and the init_color() doesn't change anything even though it succeeds:

init_scr();
start_color();
if (has_colors() && COLORS == 256 && can_change_color()) {
  NCURSES_COLOR_T f;
  for (f = 1; f < 256; f++) {
    if (init_pair(f, f, COLOR_BLACK) == ERR) break;
    attron(COLOR_PAIR(f));
    printw("(%d)", f);
    attroff(COLOR_PAIR(f));
    refresh();
  }
  getch();
  clear();
  for (f = 1; f < 256; f++) {
    if (init_color(f, 0, 0, f*3) == ERR) break;
    if (init_pair(f, f, COLOR_BLACK) == ERR) break;
    attron(COLOR_PAIR(f));
    printw("(%d)", f);
    attroff(COLOR_PAIR(f));
    refresh();
  }
  getch();
  clear();
}

I've read that the default colors can't be changed, but only refers to COLOR_BLACK, etc (0-7).

Where are these 256 default colors defined and why can't I change them? If they can't be changed, I could make use of the colors defined, but only if I can rely on them being the same on any 256-color capable terminal.

Body:
short: PuTTY doesn't do that, ncurses can't tell if PuTTY can...

long:

In ncurses, the init_color function checks its parameters (in the example given, those appear okay if your $TERM is "xterm-256color"), as well as checking if the terminal description has the initc (initialize_color) capability.  If that is missing or cancelled, ncurses returns an error.

However, that's only the terminal description.  ncurses cannot tell if you have chosen an incorrect or inappropriate terminal description.

In a quick check, PuTTY doesn't respond to the control sequence which is used in initc.  This is a known limitation, as indicated in the (more appropriate) terminal description putty-256color provided by ncurses:

putty-256color|PuTTY 0.58 with xterm 256-colors,
        use=xterm+256setaf, use=putty,

That xterm+256setaf is used for terminals whose palette is hard-coded.  PuTTY is not the only terminal which both sets TERM=xterm` and lacks the ability to change its palette.  If you happen to be using an old version of the terminal database, you may be misled, since that error was fixed in 2014:

# 2014-03-30
#       * cancel ccc in putty-256color and konsole-256color for consistency
#         with the cancelled initc capability (patch by Sven Zuhlsdorf).
#       * add xterm+256setaf building block for various terminals which only
#         get the 256-color feature half-implemented -TD
#       * updated "st" entry (leaving the 0.1.1 version as "simpleterm") to
#         0.4.1 -TD
#

Like the other terminals whose developers set TERM=xterm (or TERM=xterm-256color), there are differences between those and xterm.

Further reading:

Why not just use TERM set to "xterm"?


来源: stackexchange

问:
swift3，my timer can't stop. why?
this is i seting a timer function, the code like this:

```<code>@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}
</code>```

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

答:
First you have to declare it as fileprivate as below:</p>

```<code>fileprivate var timer = Timer()

@IBAction func start(_ sender: UIButton) {

        self.timer = Timer.scheduledTimer(timeInterval: 4,
                                                      target: self,
                                                      selector: #selector(self.updateTimerForLocation),
                                                      userInfo: nil,
                                                      repeats: true)

}

@IBAction func stop(_ sender: UIButton) {

   timer.invalidate()

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: swift3，my timer can't stop. why?

Body:
this is i seting a timer function, the code like this:

@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

Body:
First you have to declare it as fileprivate as below:

fileprivate var timer = Timer()

@IBAction func start(_ sender: UIButton) {

        self.timer = Timer.scheduledTimer(timeInterval: 4,
                                                      target: self,
                                                      selector: #selector(self.updateTimerForLocation),
                                                      userInfo: nil,
                                                      repeats: true)

}

@IBAction func stop(_ sender: UIButton) {

   timer.invalidate()

}


问:
Java Tree to represent filesystem (files/dir) from list of paths
I've a list of paths like this

```<code>/mnt/sdcard/folder1/a/b/file1
/mnt/sdcard/folder1/a/b/file2
/mnt/sdcard/folder1/a/b/file3
/mnt/sdcard/folder1/a/b/file4
/mnt/sdcard/folder1/a/b/file5
/mnt/sdcard/folder1/e/c/file6
/mnt/sdcard/folder2/d/file7
/mnt/sdcard/folder2/d/file8
/mnt/sdcard/file9
</code>```

So from this list of paths (Stings) I need to crete a Java Tree structure that has folders as nodes and files as leaf (there wont be empty folders as leaf).

What I need I think is the add method where I pass to them a String (path of the file) and it add it to the correct place in the tree creating correct nodes (Folder) if they are not already there

This tree structure will need me to get list of nodes when I'm on node and list of leafs (but I think this will be a normal features for trees)

I will always have Strings as paths and not real file or folders.
Is there something ready to use or a source code to start?

Thank you very much.

答:
I implemented a solution to the challenge myself, it is available as a GitHubGist.

I am representing each node of a filesystem-hierarchy in a DirectoryNode. A helper-method createDirectoryTree(String[] filesystemList) creates a direcotry-tree.

Here is the usage example, which is included in the GitHubGist.

```<code>final String[] list = new String[]{
  "/mnt/sdcard/folder1/a/b/file1.file",
  "/mnt/sdcard/folder1/a/b/file2.file",
  "/mnt/sdcard/folder1/a/b/file3.file",
  "/mnt/sdcard/folder1/a/b/file4.file",
  "/mnt/sdcard/folder1/a/b/file5.file",
  "/mnt/sdcard/folder1/e/c/file6.file",
  "/mnt/sdcard/folder2/d/file7.file",
  "/mnt/sdcard/folder2/d/file8.file",
  "/mnt/sdcard/file9.file"
};

final DirectoryNode directoryRootNode = createDirectoryTree(list);

System.out.println(directoryRootNode);
</code>```

The System.out.println -output is:

```<code>  {value='mnt', children=[{value='sdcard', children=[{value='folder1',
  children=[{value='a', children=[{value='b', children=[{value='file1.file',
  children=[]}, {value='file2.file', children=[]}, {value='file3.file',
  children=[]}, {value='file4.file', children=[]}, {value='file5.file',
  children=[]}]}]}, {value='e', children=[{value='c',
  children=[{value='file6.file', children=[]}]}]}]},
  {value='folder2', children=[{value='d', children=[{value='file7.file',
  children=[]}, {value='file8.file', children=[]}]}]},
  {value='file9.file', children=[]}]}]}
</code>```

Body:
I've a list of paths like this

/mnt/sdcard/folder1/a/b/file1
/mnt/sdcard/folder1/a/b/file2
/mnt/sdcard/folder1/a/b/file3
/mnt/sdcard/folder1/a/b/file4
/mnt/sdcard/folder1/a/b/file5
/mnt/sdcard/folder1/e/c/file6
/mnt/sdcard/folder2/d/file7
/mnt/sdcard/folder2/d/file8
/mnt/sdcard/file9

So from this list of paths (Stings) I need to crete a Java Tree structure that has folders as nodes and files as leaf (there wont be empty folders as leaf).

What I need I think is the add method where I pass to them a String (path of the file) and it add it to the correct place in the tree creating correct nodes (Folder) if they are not already there

This tree structure will need me to get list of nodes when I'm on node and list of leafs (but I think this will be a normal features for trees)

I will always have Strings as paths and not real file or folders.
Is there something ready to use or a source code to start?

Thank you very much.

Body:
I implemented a solution to the challenge myself, it is available as a GitHubGist.

I am representing each node of a filesystem-hierarchy in a DirectoryNode. A helper-method createDirectoryTree(String[] filesystemList) creates a direcotry-tree.

Here is the usage example, which is included in the GitHubGist.

final String[] list = new String[]{
  "/mnt/sdcard/folder1/a/b/file1.file",
  "/mnt/sdcard/folder1/a/b/file2.file",
  "/mnt/sdcard/folder1/a/b/file3.file",
  "/mnt/sdcard/folder1/a/b/file4.file",
  "/mnt/sdcard/folder1/a/b/file5.file",
  "/mnt/sdcard/folder1/e/c/file6.file",
  "/mnt/sdcard/folder2/d/file7.file",
  "/mnt/sdcard/folder2/d/file8.file",
  "/mnt/sdcard/file9.file"
};

final DirectoryNode directoryRootNode = createDirectoryTree(list);

System.out.println(directoryRootNode);

The System.out.println -output is:

  {value='mnt', children=[{value='sdcard', children=[{value='folder1',
  children=[{value='a', children=[{value='b', children=[{value='file1.file',
  children=[]}, {value='file2.file', children=[]}, {value='file3.file',
  children=[]}, {value='file4.file', children=[]}, {value='file5.file',
  children=[]}]}]}, {value='e', children=[{value='c',
  children=[{value='file6.file', children=[]}]}]}]},
  {value='folder2', children=[{value='d', children=[{value='file7.file',
  children=[]}, {value='file8.file', children=[]}]}]},
  {value='file9.file', children=[]}]}]}


问:
MySQL won't run when i am using XAMPP server
This is the error log for the MySQL when I run it on XAMPP. I don't know how to fix it, it's always stuck on attempting to start MySQL service..

I tried changing the port but the result is still the same.
also tried re-installing but the problem is still the same

thank you in advance.the error i get is as follows

```<code>    2015-11-10 15:26:56 10fc InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
    2015-11-10 15:26:56 4348 [Note] InnoDB: Using mutexes to ref count buffer pool pages
    2015-11-10 15:26:56 4348 [Note] InnoDB: The InnoDB memory heap is disabled
    2015-11-10 15:26:56 4348 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
    2015-11-10 15:26:56 4348 [Note] InnoDB: Memory barrier is not used
    2015-11-10 15:26:56 4348 [Note] InnoDB: Compressed tables use zlib 1.2.3
    2015-11-10 15:26:56 4348 [Note] InnoDB: Not using CPU crc32 instructions
    2015-11-10 15:26:56 4348 [Note] InnoDB: Initializing buffer pool, size = 16.0M
    2015-11-10 15:26:56 4348 [Note] InnoDB: Completed initialization of buffer pool
    2015-11-10 15:26:56 4348 [Note] InnoDB: Highest supported file format is Barracuda.
    2015-11-10 15:26:57 4348 [Note] InnoDB: 128 rollback segment(s) are active.
    2015-11-10 15:26:57 4348 [Note] InnoDB: Waiting for purge to start
    2015-11-10 15:26:57 4348 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.26-74.0 started; log sequence number 1835027
    2015-11-10 15:26:57 6140 [Note] InnoDB: Dumping buffer pool(s) not yet started
    2015-11-10 15:26:57 4348 [Note] Plugin 'FEEDBACK' is disabled.
    2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.
    2015-11-10 15:26:57 4348 [Note] Event Scheduler: Loaded 0 events
    2015-11-10 15:26:57 4348 [Note] C:\xampp\mysql\bin\mysqld.exe: ready for connections.
    Version: '10.1.8-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
    2015-11-10 15:27:11 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Normal shutdown

    2015-11-10 15:27:11 5152 [Note] Event Scheduler: Purging the queue. 0 events
    2015-11-10 15:27:11 5732 [Note] InnoDB: FTS optimize thread exiting.
    2015-11-10 15:27:11 5152 [Note] InnoDB: Starting shutdown...
    2015-11-10 15:27:13 5152 [Note] InnoDB: Shutdown completed; log sequence number 1835037
    2015-11-10 15:27:13 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Shutdown complete
</code>```

and this are the config for mySQL. Note: I didn't make any changes in it.

```<code># Example MySQL config file for small systems.
#
# This is for a system with little memory (<= 64M) where MySQL is only used
# from time to time and it's important that the mysqld daemon
# doesn't use much resources.
#
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
# password       = your_password
port            = 3306
socket          = "C:/xampp/mysql/mysql.sock"

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port= 3306
socket = "C:/xampp/mysql/mysql.sock"
basedir = "C:/xampp/mysql"
tmpdir = "C:/xampp/tmp"
datadir = "C:/xampp/mysql/data"
pid_file = "mysql.pid"
# enable-named-pipe
key_buffer = 16M
max_allowed_packet = 1M
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error = "mysql_error.log"

# Change here for bind listening
# bind-address="127.0.0.1"
# bind-address = ::1          # for ipv6

# Where do all the plugins live
plugin_dir = "C:/xampp/mysql/lib/plugin/"

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
# commented in by lampp security
#skip-networking
#skip-federated

# Replication Master Server (default)
# binary logging is required for replication
# log-bin deactivated by default since XAMPP 1.4.11
#log-bin=mysql-bin

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Point the following paths to different dedicated disks
#tmpdir = "C:/xampp/tmp"
#log-update = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using BDB tables
#bdb_cache_size = 4M
#bdb_max_lock = 10000

# Comment the following if you are using InnoDB tables
#skip-innodb
innodb_data_home_dir = "C:/xampp/mysql/data"
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = "C:/xampp/mysql/data"
#innodb_log_arch_dir = "C:/xampp/mysql/data"
## You can set .._buffer_pool_size up to 50 - 80 %
## of RAM but beware of setting memory usage too high
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
## Set .._log_file_size to 25 % of buffer pool size
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

## UTF 8 Settings
#init-connect=\'SET NAMES utf8\'
#collation_server=utf8_unicode_ci
#character_set_server=utf8
#skip-character-set-client-handshake
#character_sets-dir="C:/xampp/mysql/share/charsets"

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[myisamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout
</code>```

答:
To me, this looks like the offending line:

2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.

It looks like MySQL isn't binding to your localhost, and therefore can't bind to a port on said host, and won't start because of that.

Check your config file in MySQL to make sure it's set up correctly. Failing that, a fresh install of xampp to restore defaults should do the trick.

EDIT:

For more info here, as far as I can tell, if you're using IPv6 then ::1 should be the loopback address for localhost. I'm not entirely sure what just :: is.

Body:
This is the error log for the MySQL when I run it on XAMPP. I don't know how to fix it, it's always stuck on attempting to start MySQL service..

I tried changing the port but the result is still the same.
also tried re-installing but the problem is still the same

thank you in advance.the error i get is as follows

    2015-11-10 15:26:56 10fc InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
    2015-11-10 15:26:56 4348 [Note] InnoDB: Using mutexes to ref count buffer pool pages
    2015-11-10 15:26:56 4348 [Note] InnoDB: The InnoDB memory heap is disabled
    2015-11-10 15:26:56 4348 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
    2015-11-10 15:26:56 4348 [Note] InnoDB: Memory barrier is not used
    2015-11-10 15:26:56 4348 [Note] InnoDB: Compressed tables use zlib 1.2.3
    2015-11-10 15:26:56 4348 [Note] InnoDB: Not using CPU crc32 instructions
    2015-11-10 15:26:56 4348 [Note] InnoDB: Initializing buffer pool, size = 16.0M
    2015-11-10 15:26:56 4348 [Note] InnoDB: Completed initialization of buffer pool
    2015-11-10 15:26:56 4348 [Note] InnoDB: Highest supported file format is Barracuda.
    2015-11-10 15:26:57 4348 [Note] InnoDB: 128 rollback segment(s) are active.
    2015-11-10 15:26:57 4348 [Note] InnoDB: Waiting for purge to start
    2015-11-10 15:26:57 4348 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.26-74.0 started; log sequence number 1835027
    2015-11-10 15:26:57 6140 [Note] InnoDB: Dumping buffer pool(s) not yet started
    2015-11-10 15:26:57 4348 [Note] Plugin 'FEEDBACK' is disabled.
    2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.
    2015-11-10 15:26:57 4348 [Note] Event Scheduler: Loaded 0 events
    2015-11-10 15:26:57 4348 [Note] C:\xampp\mysql\bin\mysqld.exe: ready for connections.
    Version: '10.1.8-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
    2015-11-10 15:27:11 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Normal shutdown

    2015-11-10 15:27:11 5152 [Note] Event Scheduler: Purging the queue. 0 events
    2015-11-10 15:27:11 5732 [Note] InnoDB: FTS optimize thread exiting.
    2015-11-10 15:27:11 5152 [Note] InnoDB: Starting shutdown...
    2015-11-10 15:27:13 5152 [Note] InnoDB: Shutdown completed; log sequence number 1835037
    2015-11-10 15:27:13 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Shutdown complete

and this are the config for mySQL. Note: I didn't make any changes in it.

# Example MySQL config file for small systems.
#
# This is for a system with little memory (<= 64M) where MySQL is only used
# from time to time and it's important that the mysqld daemon
# doesn't use much resources.
#
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
# password       = your_password
port            = 3306
socket          = "C:/xampp/mysql/mysql.sock"

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port= 3306
socket = "C:/xampp/mysql/mysql.sock"
basedir = "C:/xampp/mysql"
tmpdir = "C:/xampp/tmp"
datadir = "C:/xampp/mysql/data"
pid_file = "mysql.pid"
# enable-named-pipe
key_buffer = 16M
max_allowed_packet = 1M
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error = "mysql_error.log"

# Change here for bind listening
# bind-address="127.0.0.1"
# bind-address = ::1          # for ipv6

# Where do all the plugins live
plugin_dir = "C:/xampp/mysql/lib/plugin/"

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
#
# commented in by lampp security
#skip-networking
#skip-federated

# Replication Master Server (default)
# binary logging is required for replication
# log-bin deactivated by default since XAMPP 1.4.11
#log-bin=mysql-bin

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Point the following paths to different dedicated disks
#tmpdir = "C:/xampp/tmp"
#log-update = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using BDB tables
#bdb_cache_size = 4M
#bdb_max_lock = 10000

# Comment the following if you are using InnoDB tables
#skip-innodb
innodb_data_home_dir = "C:/xampp/mysql/data"
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = "C:/xampp/mysql/data"
#innodb_log_arch_dir = "C:/xampp/mysql/data"
## You can set .._buffer_pool_size up to 50 - 80 %
## of RAM but beware of setting memory usage too high
innodb_buffer_pool_size = 16M
innodb_additional_mem_pool_size = 2M
## Set .._log_file_size to 25 % of buffer pool size
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

## UTF 8 Settings
#init-connect=\'SET NAMES utf8\'
#collation_server=utf8_unicode_ci
#character_set_server=utf8
#skip-character-set-client-handshake
#character_sets-dir="C:/xampp/mysql/share/charsets"

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[myisamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout


问:
Django: HttpResponseRedirect is not defined
I finally managed to POST data from a form to a database in django, however when I press the submit button on my form I get the error:

```<code>Request Method:     POST
Request URL:    http://127.0.0.1:8000/post_url/
Django Version:     1.11.2
Exception Type:     NameError
Exception Value:

name 'HttpResponseRedirect' is not defined

Exception Location:     /home/xxxx/Desktop/123/src/exercises/views.py in post_treasure, line 26
Python Executable:  /home/xxxx/Desktop/123/bin/python
</code>```

Relevant views.py:

```<code>def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                            value = form.cleaned_data['value'],
                            material = form.cleaned_data['material'],
                            location = form.cleaned_data['location'],
                            img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')
</code>```

Relevant urls.py:

```<code>urlpatterns = [
    url(r'^post_url/', post_treasure, name='post_treasure'),
    url(r'^admin/', admin.site.urls),
    url(r'^numbers/', numbers, name="numbers"),
    url(r'^about/', about, name="about")
]
</code>```

Other note:

The data is successfully posted if I press the back button to view the new updated data passed from the model to the template, or if I use the admin interface to simply view the data

答:
You need to import that first:</p>

```<code>from django.http import HttpResponseRedirect

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                        value = form.cleaned_data['value'],
                        material = form.cleaned_data['material'],
                        location = form.cleaned_data['location'],
                        img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')
</code>```

Body:
I finally managed to POST data from a form to a database in django, however when I press the submit button on my form I get the error:

Request Method:     POST
Request URL:    http://127.0.0.1:8000/post_url/
Django Version:     1.11.2
Exception Type:     NameError
Exception Value:

name 'HttpResponseRedirect' is not defined

Exception Location:     /home/xxxx/Desktop/123/src/exercises/views.py in post_treasure, line 26
Python Executable:  /home/xxxx/Desktop/123/bin/python

Relevant views.py:

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                            value = form.cleaned_data['value'],
                            material = form.cleaned_data['material'],
                            location = form.cleaned_data['location'],
                            img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')

Relevant urls.py:

urlpatterns = [
    url(r'^post_url/', post_treasure, name='post_treasure'),
    url(r'^admin/', admin.site.urls),
    url(r'^numbers/', numbers, name="numbers"),
    url(r'^about/', about, name="about")
]

Other note:

The data is successfully posted if I press the back button to view the new updated data passed from the model to the template, or if I use the admin interface to simply view the data

Body:
You need to import that first:

from django.http import HttpResponseRedirect

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                        value = form.cleaned_data['value'],
                        material = form.cleaned_data['material'],
                        location = form.cleaned_data['location'],
                        img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
You just need to toggle this class with some JavaScript:

var triangle = document.querySelector('.triangle');

triangle.addEventListener('click', function(){
triangle.classList.toggle('triangle-up')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.triangle {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 10px solid #cecece;
margin-left: -10px;
}

.triangle-up {
transform: rotate(180deg);
border-top: 10px solid #555;
}</code>```

```
</div>
</div>
</p>

<p>This toggles between up and down when the arrow is clicked.</p>

<p>If you've got multiple arrows then just change the JS to:</p>

```var triangle = document.querySelectorAll('.triangle');

Array.prototype.forEach.call(triangle, function(el, i){
  el.addEventListener('click', function(){
    el.classList.toggle('triangle-up');
  });
});
```

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
You just need to toggle this class with some JavaScript:

var triangle = document.querySelector('.triangle');

triangle.addEventListener('click', function(){
triangle.classList.toggle('triangle-up')
});

.triangle {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 10px solid #cecece;
margin-left: -10px;
}

.triangle-up {
transform: rotate(180deg);
border-top: 10px solid #555;
}

<div class="triangle"></div>

This toggles between up and down when the arrow is clicked.

If you've got multiple arrows then just change the JS to:

var triangle = document.querySelectorAll('.triangle');

Array.prototype.forEach.call(triangle, function(el, i){
  el.addEventListener('click', function(){
    el.classList.toggle('triangle-up');
  });
});


问:
Swagger 3.x : Query params act as readonly values
I tried swagger 3.2.2 by running a GET operation with few query params.
I find defaults values I set in REST API can't override in swagger UI.  All the text boxes are read only, and drop-down of Boolean query param always sends 'false' though I select it to 'true'.  It seems program default values are super hard-corded here.  I was playing with swagger @ApiPram(..) to fix this but it didn't help me.

Did anyone ran in to the same issue I describe above with Swagger 3.x?

答: I start using Swagger UI 3.5.0 and fixed the issue


问:
Remove left spacing in <Form> component in native base
I would like to ask, how can I remove the left spacing in the Form component, I'm using native base UI for my design. Here's my code below:

```<code><Form>
  <Item style={styles.loginInputItem}>
    <Input placeholder="Email address" style={styles.loginInput} placeholderTextColor="#FFFFFF" />
  </Item>
  <Item style={styles.loginInputItem}>
    <Input placeholder="Password" secureTextEntry={true} style={styles.loginInput} placeholderTextColor="#FFFFFF" />
  </Item>
  <Button block style={styles.loginButton}>
    <Text>Login</Text>
  </Button>
  <Button block style={styles.loginFacebookButton}>
    <Text>Connect with Facebook</Text>
  </Button>
  <Button block style={styles.loginGoogleButton}>
    <Text style={styles.loginGoogleButtonText}>Connect with Google</Text>
  </Button>
  <Button block transparent light>
    <Text>Forgot Password?</Text>
  </Button>
</Form>
</code>```

答:
just override the style of <Item/> and set marginLeft:0

```<code><Item style={{ marginLeft: 0 }}/>
</code>```

Body:
I would like to ask, how can I remove the left spacing in the Form component, I'm using native base UI for my design. Here's my code below:

<Form>
  <Item style={styles.loginInputItem}>
    <Input placeholder="Email address" style={styles.loginInput} placeholderTextColor="#FFFFFF" />
  </Item>
  <Item style={styles.loginInputItem}>
    <Input placeholder="Password" secureTextEntry={true} style={styles.loginInput} placeholderTextColor="#FFFFFF" />
  </Item>
  <Button block style={styles.loginButton}>
    <Text>Login</Text>
  </Button>
  <Button block style={styles.loginFacebookButton}>
    <Text>Connect with Facebook</Text>
  </Button>
  <Button block style={styles.loginGoogleButton}>
    <Text style={styles.loginGoogleButtonText}>Connect with Google</Text>
  </Button>
  <Button block transparent light>
    <Text>Forgot Password?</Text>
  </Button>
</Form>

Body:
just override the style of <Item/> and set marginLeft:0

<Item style={{ marginLeft: 0 }}/>


问:
Automatic Language detection from Images for OCR character Extraction
I am building a software using python in which the image is uploaded.The software will extract the text using tesseract ocr.

But I want my software to detect the languages in the images automatically and extract the detected text.

Please suggest me some ways to do that,I am ready to do Machine Learning also but i can't determine a perfect pipeline for the process.

Thanks In-advance.

答:
The process is complicated, what you need to do is

Extract text from image in lang=eng

Pass that text to langdetect it is google automatic language detection library

Again use that language in tesseract to extract text accurately

Or

you can use switch case with every language and pass sample text to langdetect to get probability which language is correct.

```<code>import pytesseract

pytesseract.pytesseract.tesseract_cmd =
'<full_path_to_your_tesseract_executable>'
# Include the above line, if you don't have tesseract executable in your path

# Example tesseract_cmd: 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'

print(pytesseract.image_to_string(Image.open('test.png')))
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='eng'))

sample_text = pytesseract.image_to_string(Image.open('image.jpg'), lang='eng')

from langdetect import detect_langs detect_langs(sample_text)
</code>```

Body:
The process is complicated, what you need to do is

Extract text from image in lang=eng

Pass that text to langdetect it is google automatic language detection library

Again use that language in tesseract to extract text accurately

Or

you can use switch case with every language and pass sample text to langdetect to get probability which language is correct.

import pytesseract

pytesseract.pytesseract.tesseract_cmd =
'<full_path_to_your_tesseract_executable>'
# Include the above line, if you don't have tesseract executable in your path

# Example tesseract_cmd: 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'

print(pytesseract.image_to_string(Image.open('test.png')))
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='eng'))

sample_text = pytesseract.image_to_string(Image.open('image.jpg'), lang='eng')

from langdetect import detect_langs detect_langs(sample_text)


问:
Adding elements in a list
I have a list named p. It contains some elements like this.

```<code>p = [['mon', '1006'], ['mon', '769']].
</code>```

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

答:
This should give you an idea.

```<code>p = [['mon', '1006'], ['mon', '769']]
sum = 0
for x in p:
    sum += int(x[1])
print sum
</code>```

Run:

```<code>$ python 2.py
1775
</code>```

Title: Adding elements in a list

Body:
I have a list named p. It contains some elements like this.

p = [['mon', '1006'], ['mon', '769']].

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

Body:
This should give you an idea.

p = [['mon', '1006'], ['mon', '769']]
sum = 0
for x in p:
    sum += int(x[1])
print sum

Run:

$ python 2.py
1775


答:
you need to import HttpResponseRedirect

so at the top

```<code>from django.http import HttpResponseRedirect
</code>```

Title: Django: HttpResponseRedirect is not defined

Body:
you need to import HttpResponseRedirect

so at the top

from django.http import HttpResponseRedirect


问:
How to aggregate an array data in mongodb
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

```<code>{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}
</code>```

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

```<code>db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})
</code>```

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

答:
you should first unwind the pools and then run the matches:</p>

```<code>db.getCollection('notification_collection').aggregate(
    { $unwind: '$pools'},
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}}
)
</code>```

Body:
I've some problems to make an aggregation query work fine in MongoDB.

I've this json schema:

{
    "_id" : 11,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "pools" : [
        {
            "score" : 2,
            "language" : "en",
            "option" : "Have problems to close!",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "en",
            "option" : "I can't close this door!",
            "time" : "2017-06-06"
        },
        {
            "score" : 4,
            "language" : "en",
            "option" : "After some time, I'm able to install this door. Works fine!",
            "time" : "2017-06-06"
        },
        {
            "score" : 5,
            "language" : "fr",
            "option" : "Très difficile à installer, mais ça marche quand même.",
            "time" : "2017-06-06"
        },
        {
            "score" : 1,
            "language" : "es",
            "option" : "Perdí mucho tiempo para instalar.",
            "time" : "2017-06-06"
        }
    ]
}

I would like to filter only the registries that have language in English ("en") and score equal or greater than 3. So, I try this:

db.test.aggregate(
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}},
    { $unwind: '$pools'})

However, I always get results in other languages and incoherent scores.

So, how to write this correctly?

Body:
you should first unwind the pools and then run the matches:

db.getCollection('notification_collection').aggregate(
    { $unwind: '$pools'},
    { $match: { "pools.language": "en" }},
    { $match: {"pools.score": { $gte : 3 }}}
)


问:
Cross-Platform iOS/Mac OS X Objective-C development?
I'll be starting  medium-sized iOS project soon, a document-centric app.

Later, the software might get ported to Mac OS X. Of course, the whole UI will need to change; that's not what I'm asking.

Is it possible to write the core logic in such a way that it's cross-platform (Mac/iOS only), or more easily ported? Has anybody done this before, or is the usual way to just write different code for both platforms?

I'm thankful for any tips regarding this, be they about Code, Frameworks, Version Control - anything. I'd hate to realize I've painted myself into a corner only after the fact, so I want to start as well as possible.

答: I don't know much about this, the other guys probably know more, but if you ever wanted to port the project from iOS over to Mac then maybe UMEKit might help you...</p>

ContentLicense: CC BY-SA 2.5


问:
MPAndroid Group bar chart is not showing
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

```<code>        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);
</code>```

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.

答:
This is not my answer, i have seen this ques before and impleneted in my app it worked like a charm. Couldn't find the link to the original answer so i am posting the code that i used.
You can use ActivityLifecycleCallbacks :

```<code>public class AppTransitionStatus implements Application.ActivityLifecycleCallbacks {

private static final long MAX_BACKGROUND_TIME = 2000;
private Timer timer;
private TimerTask task;
private boolean isBackground;

private final Transition transition;

private void goToForeground(Activity iActivity) {
    transition.appToForeground(iActivity);
}

private void goToBackground() {
    transition.appToBackground();
}

private void stopTimer() {
    if (task != null) task.cancel();
    if (timer != null) timer.cancel();
}

public AppTransitionStatus(@NonNull Transition transition) {
    this.transition = transition;
}

@Override
public void onActivityCreated(Activity activity, Bundle bundle) {

}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {
    if (isBackground) {
        goToForeground(activity);
    }
    stopTimer();
    isBackground = false;
}

@Override
public void onActivityPaused(Activity activity) {
    timer = new Timer();
    task = new TimerTask() {
        public void run() {
            isBackground = true;
            goToBackground();
        }
    };
    timer.schedule(task, MAX_BACKGROUND_TIME);
}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}

public interface Transition {
    void appToForeground(Activity iActivity);

    void appToBackground();
}
}
</code>```

And then you can register this in your application class

```<code> registerActivityLifecycleCallbacks(new AppTransitionStatus(new AppTransitionStatus.Transition() {
        @Override
        public void appToForeground(Activity iActivity) {

            Log.d("Transition", "App in Foreground");

        }

        @Override
        public void appToBackground() {
            Log.d("Transition", "App in Background");
        }
    }));
</code>```

Body:
Here is the code i used for group bar_chart using MPAndroid library version 3. I've tried group bar chart in lower version and it works fine but the BarData constructor is changed in latest version. And this code doesn't works. There is no crashes and error logs, still graph is loading and no data shows in it. Help me to find ma flaws

        List<BarEntry> entriesGroup1 = new ArrayList<>();
        List<BarEntry> entriesGroup2 = new ArrayList<>();
        List<BarEntry> entriesGroup3 = new ArrayList<>();

        entriesGroup1.add(new BarEntry(0, 8f));
        entriesGroup1.add(new BarEntry(1, 2f));
        entriesGroup1.add(new BarEntry(2, 5f));
        entriesGroup1.add(new BarEntry(3, 20f));
        entriesGroup1.add(new BarEntry(4, 15f));
        entriesGroup1.add(new BarEntry(5, 19f));

        entriesGroup2.add(new BarEntry(0, 6f));
        entriesGroup2.add(new BarEntry(1, 10f));
        entriesGroup2.add(new BarEntry(2, 5f));
        entriesGroup2.add(new BarEntry(3, 25f));
        entriesGroup2.add(new BarEntry(4, 4f));
        entriesGroup2.add(new BarEntry(5, 17f));

        entriesGroup3.add(new BarEntry(0, 9f));
        entriesGroup3.add(new BarEntry(1, 1f));
        entriesGroup3.add(new BarEntry(2, 15f));
        entriesGroup3.add(new BarEntry(3, 13f));
        entriesGroup3.add(new BarEntry(4, 40f));
        entriesGroup3.add(new BarEntry(5, 25f));

        BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
        BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
        BarDataSet set3 = new BarDataSet(entriesGroup3, "Group 3");

        final ArrayList<String> labels = new ArrayList<String>();
        labels.add("2016");
        labels.add("2015");
        labels.add("2014");
        labels.add("2013");
        labels.add("2012");
        labels.add("2011");
        IAxisValueFormatter formatter = new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                if((int) value < 0 || (int) value >= labels.size()){
                    return "";
                }else{
                    return labels.get((int) value);
                }
            }

            // we don't draw numbers, so no decimal digits needed
            @Override
            public int getDecimalDigits() {  return 0; }
        };

        set1.setColor(Color.parseColor("#cd5080"));
        set2.setColor(Color.parseColor("#0d5080"));
        set3.setColor(Color.parseColor("#fc5080"));;

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
// (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group"

        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);

        BarData data = new BarData(set1, set2, set3);
        data.setBarWidth(barWidth); // set the width of each bar
        barChart.setData(data);
        barChart.groupBars(2016, groupSpace, barSpace);
        barChart.invalidate(); // refresh

        barChart.animateY(5000);

Nb: I'm edited my current question since i'm banned to ask new questions. But its important for me. Thanks everyone.

Body:
This is not my answer, i have seen this ques before and impleneted in my app it worked like a charm. Couldn't find the link to the original answer so i am posting the code that i used.
You can use ActivityLifecycleCallbacks :

public class AppTransitionStatus implements Application.ActivityLifecycleCallbacks {

private static final long MAX_BACKGROUND_TIME = 2000;
private Timer timer;
private TimerTask task;
private boolean isBackground;

private final Transition transition;

private void goToForeground(Activity iActivity) {
    transition.appToForeground(iActivity);
}

private void goToBackground() {
    transition.appToBackground();
}

private void stopTimer() {
    if (task != null) task.cancel();
    if (timer != null) timer.cancel();
}

public AppTransitionStatus(@NonNull Transition transition) {
    this.transition = transition;
}

@Override
public void onActivityCreated(Activity activity, Bundle bundle) {

}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {
    if (isBackground) {
        goToForeground(activity);
    }
    stopTimer();
    isBackground = false;
}

@Override
public void onActivityPaused(Activity activity) {
    timer = new Timer();
    task = new TimerTask() {
        public void run() {
            isBackground = true;
            goToBackground();
        }
    };
    timer.schedule(task, MAX_BACKGROUND_TIME);
}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}

public interface Transition {
    void appToForeground(Activity iActivity);

    void appToBackground();
}
}

And then you can register this in your application class

 registerActivityLifecycleCallbacks(new AppTransitionStatus(new AppTransitionStatus.Transition() {
        @Override
        public void appToForeground(Activity iActivity) {

            Log.d("Transition", "App in Foreground");

        }

        @Override
        public void appToBackground() {
            Log.d("Transition", "App in Background");
        }
    }));


问:
How to detect desktop idle time from an Electron app?
I need my Electron app to respond to the user becoming idle (no mouse or keyboard inputs to any program on the OS) for a certain amount of time.

How can I trigger a function based on such idle time data?

答:
You can always detect idle times on Linux by using XScreenServer, GetLastInputInfo on Windows and CGEventSourceSecondsSinceLastEventType on Mac

I've published desktop-idle using these API's, you can check the source code https://github.com/bithavoc/node-desktop-idle

UPDATE:

Electron 3 users can use the power monitor API to achieve the same goal: https://electronjs.org/docs/api/power-monitor

ContentLicense: CC BY-SA 4.0


问:
date time format null values return default time in PHP
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

```<code>  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format
</code>```

. when i print this column it returns like this

```<code>payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40
</code>```

but i need to return as NULL not default time format.

答:
Modify your table payment_date and set the column payment_date datatype to NULL DEFAULT NULL.</p>

```<code>alter table payment_date modify column payment_date datetime null default null;
</code>```

Body:
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format

. when i print this column it returns like this

payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40

but i need to return as NULL not default time format.

Body:
Modify your table payment_date and set the column payment_date datatype to NULL DEFAULT NULL.

alter table payment_date modify column payment_date datetime null default null;


问:
Readline hanging after first input in terminal
Using Node version 8.1.0.

Was reading the documentation on readline: https://nodejs.org/docs/latest-v8.x/api/readline.html

States the the close method and it states:

The readline.Interface instance should be considered to be "finished"
  once the 'close' event is emitted.

So naturally I would open a new interface, like I've done in my example.

```<code>const readline = require('readline');

function question(question, defaultAnswer) {
    // Create the interface
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    return new Promise((resolve, reject) => {
        rl.question(question, (answer) => {
            // Relinquished control over the input and output streams
            rl.close();
            if (answer.length === 0) {
                resolve(defaultAnswer);
            } else {
                resolve(answer);
            }
        });
    });
}

(async () => {
    let answer;
    answer = await question('1? [y] ', 'y');
    console.log('answer', answer);
    answer = await question('2? [y] ', 'y');
    console.log('answer', answer);
    answer = await question('3? [y] ', 'y');
    console.log('answer', answer);
})();
</code>```

Output:

```<code>$ node test.js
1? [y] y
answer y
2? [y]
</code>```

It hangs however. I have no idea why? Currently sitting on a Mac unfortunately, I don't know if this might affect this.

答:
So I filed a bug report here: https://github.com/nodejs/node/issues/17495

This is a known issue with Node 8.1.0. Changing from 8.1.0 to any other version made it work.

Body:
Using Node version 8.1.0.

Was reading the documentation on readline: https://nodejs.org/docs/latest-v8.x/api/readline.html

States the the close method and it states:

The readline.Interface instance should be considered to be "finished"
  once the 'close' event is emitted.

So naturally I would open a new interface, like I've done in my example.

const readline = require('readline');

function question(question, defaultAnswer) {
    // Create the interface
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    return new Promise((resolve, reject) => {
        rl.question(question, (answer) => {
            // Relinquished control over the input and output streams
            rl.close();
            if (answer.length === 0) {
                resolve(defaultAnswer);
            } else {
                resolve(answer);
            }
        });
    });
}

(async () => {
    let answer;
    answer = await question('1? [y] ', 'y');
    console.log('answer', answer);
    answer = await question('2? [y] ', 'y');
    console.log('answer', answer);
    answer = await question('3? [y] ', 'y');
    console.log('answer', answer);
})();

Output:

$ node test.js
1? [y] y
answer y
2? [y]

It hangs however. I have no idea why? Currently sitting on a Mac unfortunately, I don't know if this might affect this.


问:
Imported project unable to run in Android studio
I imported Google's HelloAr project after downloading and decompiling the code. I followed the accepted answer in this SO question to create all necessary folders. Then I imported it into android studio. But now I am unable to run the project.

build.gradle:

Modules :

UnityPlayerActivity:

答:
I figured it out. I was missing

settings.gradle

file at the root of the project. Android studio will not automatically add it for you. You have to manually add it to your root before you import the project into AS.


问:
Tcl regexp expression to catch words outside brackets
I want to parse:
([(A touch B) over C] touch {D touch E}) is good.

Using:
( P1 touch P2) is good.

I want to replace P1 and P2 by regular expression to get
P1 = [(A touch B) over C]
P2 =  {D touch E}
My first idea is:
( (.*)  touch (.*)) is good.

But i got wrong matching:
P1 = [(A touch B) over C] touch  {D
P2 = E}

I want to break on the "touch" outside the brackets.
Note: A, B, C... are examples so we should use .*

答:
A regular expression matching can't handle arbitrary expressions of this kind, but most parsers can. In the Tcllib standard library for Tcl there is a PEG (parsing expression grammar) parser generator in the pt (parser tools) module. The following defines a grammar (as a simple string) that can parse your example text, and also text where brackets of the same kind are nested:

```<code>set grammar {
PEG Reader (Datum)
      Datum       <- '(' <space>* P1 'touch' <space>* P2 ') is good' ;
      Word        <- <alpha>+ ;
      BrackExpr   <- '[' Expression+ ']' ;
      BraceExpr   <- '{' Expression+ '}' ;
      ParenExpr   <- '(' Expression+ ')' ;
void: Expression  <- (Word / BrackExpr / BraceExpr / ParenExpr) <space>* ;
      P1          <- Expression ;
      P2          <- Expression ;
END;
}
</code>```

To use this, you need to follow some steps. First save the generated parser in a file:

```<code>package require fileutil
package require pt::pgen

fileutil::writeFile ./reader.tcl [pt::pgen peg $grammar oo -class Reader]
</code>```

This code creates a file, reader.tcl, that contains a TclOO class that perform the parsing specified in the grammar. You source up that file to make the class available:

```<code>source reader.tcl
</code>```

If you are going to do that multiple times from the console, you need to destroy the class in between:

```<code>catch {Reader destroy} ; source reader.tcl
</code>```

Then you make an instance of the class and put it to work:

```<code>Reader create reader
set str {([(A touch B) over C] touch {D touch E}) is good}
reader parset $str
</code>```

(If you use the parse method instead, you can parse an open channel.)

The result of the parsing is the AST (abstract syntax tree)

```<code>Datum 0 47 {P1 1 21} {P2 28 38}
</code>```

As you can see, it has found text for P1 at string indices 1 to 21, and for P2 at 28 to 38 (note that trailing whitespace is captured). You can use string range $str 1 21 to get the text for P1, or automate it:

```<code>proc Datum {from to args} {foreach arg $args {puts [uplevel 1 $arg]}}
proc P1 {from to} {string range $::str $from $to}
proc P2 {from to} {string range $::str $from $to}

% Datum 0 47 {P1 1 21} {P2 28 38}
[(A touch B) over C]
{D touch E}
</code>```

If you use this, you might want to experiment with the definition of the nonterminal Word. Currently it only allows alphabetic characters. A definition like

```<code>      Word        <- (<alnum> / [;:/&!?*+.\'\"#])+ ;
</code>```

allows digits and some punctuation too. There are more inclusive character sets, but <punct>, <graph>, and <print> all contain bracket characters. Even if the definition of Expression is changed

```<code>void: Expression  <- (BrackExpr / BraceExpr / ParenExpr / Word) <space>* ;
</code>```

so that Word comes last, which lets the parser choose one of the *Expr nonterminals on encountering an opening bracket, the closing bracket will still be consumed by Word and not by the correct nonterminal expression. AFAICT this is a limitation of PEG parsers, which do not backtrack. The grammar can be modified to deal with this, but it will very quickly become too complicated.

Documentation:
pt (package)

Body:
A regular expression matching can't handle arbitrary expressions of this kind, but most parsers can. In the Tcllib standard library for Tcl there is a PEG (parsing expression grammar) parser generator in the pt (parser tools) module. The following defines a grammar (as a simple string) that can parse your example text, and also text where brackets of the same kind are nested:

set grammar {
PEG Reader (Datum)
      Datum       <- '(' <space>* P1 'touch' <space>* P2 ') is good' ;
      Word        <- <alpha>+ ;
      BrackExpr   <- '[' Expression+ ']' ;
      BraceExpr   <- '{' Expression+ '}' ;
      ParenExpr   <- '(' Expression+ ')' ;
void: Expression  <- (Word / BrackExpr / BraceExpr / ParenExpr) <space>* ;
      P1          <- Expression ;
      P2          <- Expression ;
END;
}

To use this, you need to follow some steps. First save the generated parser in a file:

package require fileutil
package require pt::pgen

fileutil::writeFile ./reader.tcl [pt::pgen peg $grammar oo -class Reader]

This code creates a file, reader.tcl, that contains a TclOO class that perform the parsing specified in the grammar. You source up that file to make the class available:

source reader.tcl

If you are going to do that multiple times from the console, you need to destroy the class in between:

catch {Reader destroy} ; source reader.tcl

Then you make an instance of the class and put it to work:

Reader create reader
set str {([(A touch B) over C] touch {D touch E}) is good}
reader parset $str

(If you use the parse method instead, you can parse an open channel.)

The result of the parsing is the AST (abstract syntax tree)

Datum 0 47 {P1 1 21} {P2 28 38}

As you can see, it has found text for P1 at string indices 1 to 21, and for P2 at 28 to 38 (note that trailing whitespace is captured). You can use string range $str 1 21 to get the text for P1, or automate it:

proc Datum {from to args} {foreach arg $args {puts [uplevel 1 $arg]}}
proc P1 {from to} {string range $::str $from $to}
proc P2 {from to} {string range $::str $from $to}

% Datum 0 47 {P1 1 21} {P2 28 38}
[(A touch B) over C]
{D touch E}

If you use this, you might want to experiment with the definition of the nonterminal Word. Currently it only allows alphabetic characters. A definition like

      Word        <- (<alnum> / [;:/&!?*+.\'\"#])+ ;

allows digits and some punctuation too. There are more inclusive character sets, but <punct>, <graph>, and <print> all contain bracket characters. Even if the definition of Expression is changed

void: Expression  <- (BrackExpr / BraceExpr / ParenExpr / Word) <space>* ;

so that Word comes last, which lets the parser choose one of the *Expr nonterminals on encountering an opening bracket, the closing bracket will still be consumed by Word and not by the correct nonterminal expression. AFAICT this is a limitation of PEG parsers, which do not backtrack. The grammar can be modified to deal with this, but it will very quickly become too complicated.

Documentation:
pt (package)


问:
t-sql how to subtract two records from table
I have such a query:

```<code>SELECT Stamp_date , Stamp_Action FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)
</code>```

And I have such a results from query:

```<code>2017-12-04 12:56:37.293 5

2017-12-04 15:40:02.593 15
</code>```

What is the best way to subtract two records? Also how can I define them as a variables, if I would like to maintain with them easily?

答:
If you only want to subtract this two dates you can use DATEDIFF and MIN -MAX

```<code>SELECT DATEDIFF(MINUTE, MIN(Stamp_date) , MAX(Stamp_date)) FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)
</code>```

you can change MINUTE to SECOND or other datepart according to your need

Also if you want select MIN and MAX according to Stamp_Action you can use this.

```<code>SELECT DATEDIFF(MINUTE,
    MIN(CASE WHEN Stamp_Action = 5 THEN Stamp_date END)  ,
    MAX(CASE WHEN Stamp_Action = 15 THEN Stamp_date END ) )
FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)
</code>```

Body:
I have such a query:

SELECT Stamp_date , Stamp_Action FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)

And I have such a results from query:

2017-12-04 12:56:37.293 5

2017-12-04 15:40:02.593 15

What is the best way to subtract two records? Also how can I define them as a variables, if I would like to maintain with them easily?

Body:
If you only want to subtract this two dates you can use DATEDIFF and MIN -MAX

SELECT DATEDIFF(MINUTE, MIN(Stamp_date) , MAX(Stamp_date)) FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)

you can change MINUTE to SECOND or other datepart according to your need

Also if you want select MIN and MAX according to Stamp_Action you can use this.

SELECT DATEDIFF(MINUTE,
    MIN(CASE WHEN Stamp_Action = 5 THEN Stamp_date END)  ,
    MAX(CASE WHEN Stamp_Action = 15 THEN Stamp_date END ) )
FROM FILES_TIME_STAMPS
WHERE Stamp_File_Id = @FileID AND Stamp_Action IN (5,15)


问:
Joining two Models with the same name in Keras Tensorflow
I was trying to combine two models to concatenate outputs to a new model so that i could get prediction of both models like this

model_age = load_model('age.h5')
# model_age.get_layer(name= 'model').name='predictions_1'

model_gender = load_model('gender.h5')
# model_gender.get_layer(name='model_1').name='predictions_2'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data = cv2.imread(image)
p_age, p_gender = model.predict(data)

print(p_age)
print(p_gender)
```

<p>but this error keeps happening that says </p>

```RuntimeError: (u'The name "model_1" is used 2 times in the model. All
layer names should be unique. Layer names: ', ['input_1', u'model_1',
u'model_1'])
```

tried solving that using the code commented above but says those models don't have a layer named 'model_1'

答: It seems to me like the models themselves are both named model_1, not their layers.

Body:
I was trying to combine two models to concatenate outputs to a new model so that i could get prediction of both models like this

model_age = load_model('age.h5')
# model_age.get_layer(name= 'model').name='predictions_1'

model_gender = load_model('gender.h5')
# model_gender.get_layer(name='model_1').name='predictions_2'

x = Input(shape=[100, 100, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data = cv2.imread(image)
p_age, p_gender = model.predict(data)

print(p_age)
print(p_gender)

but this error keeps happening that says

RuntimeError: (u'The name "model_1" is used 2 times in the model. All
layer names should be unique. Layer names: ', ['input_1', u'model_1',
u'model_1'])

tried solving that using the code commented above but says those models don't have a layer named 'model_1'


答:
You can easily do this by using a list comprehension, _ is a throw away variable and you just use the second element n from the unpacking of the list items.

```<code>p = [['mon', '1006'], ['mon', '769']]
print sum(int(n) for _, n in p)
>1775
</code>```

Title: Adding elements in a list

Body:
You can easily do this by using a list comprehension, _ is a throw away variable and you just use the second element n from the unpacking of the list items.

p = [['mon', '1006'], ['mon', '769']]
print sum(int(n) for _, n in p)
>1775


问:
Raster in R: Create Zonal Count of specific cell values without reclassification
I would like to know if there is way to create zonal statistics for RasterLayerObjects, specifically the count of a given cell value (e.g. a land-use class) in R without having to reclassify the whole raster. The solution should be memory efficient in order to work on large raster files i.e. no extraction of the values into a matrix in R is desired.

Below an example of how I handle it until now. In this case I reclassify the original raster to hold only 1 for the value of interest and missings for all other values.

My proposed solution creates both, redundant data and additional processing steps to get me to my initial goal. I thought something like zonal(r1[r1==6],r2,"count") would work but obviously it does not (see below).

```<code># generate reproducible Raster
library("raster")

## RASTER 1 (e.g. land-use classes)
r1 <- raster( crs="+proj=utm +zone=31")
extent(r1) <- extent(0, 100, 0, 100)
res(r1) <- c(5, 5)
values(r1) <- sample(10, ncell(r1), replace=TRUE)
plot(r1)

## RASTER 2 (containing zones of interest)
r2 <- raster( crs="+proj=utm +zone=31")
extent(r2) <- extent(0, 100, 0, 100)
res(r2) <- c(5, 5)
values(r2) <- c(rep(1,100),rep(2,100),rep(3,100),rep(4,100))
plot(r2)

# (1) ZONAL STATISTICS
# a. how many cells per zone (independent of specific cell value)
zonal(r1,r2,"count")

# b. how many cells per zone of specific value 6
zonal(r1[r1==6],r2,"count")
# -> fails

# with reclassification
r1.reclass<-
  reclassify(r1,
             matrix(c(1,5,NA,
                    5.5,6.5,1, #class of interest
                    6.5,10,NA),
                    ncol=3,
                    byrow = T),
             include.lowest=T # include the lowest value from the table.
           )
zonal(r1.reclass,r2,"count")
</code>```

答:
you can use raster::match.

```<code>zonal(match(r1, 6),r2, "count")
</code>```

As you can see from plot(match(r1, 6)), it only returns raster cells which hold the desired value(s). All other cells are NA.

r1==6 as used in your try unfortunately returns a vector and therefore cannot be used in focal anymore.

Body:
I would like to know if there is way to create zonal statistics for RasterLayerObjects, specifically the count of a given cell value (e.g. a land-use class) in R without having to reclassify the whole raster. The solution should be memory efficient in order to work on large raster files i.e. no extraction of the values into a matrix in R is desired.

Below an example of how I handle it until now. In this case I reclassify the original raster to hold only 1 for the value of interest and missings for all other values.

My proposed solution creates both, redundant data and additional processing steps to get me to my initial goal. I thought something like zonal(r1[r1==6],r2,"count") would work but obviously it does not (see below).

# generate reproducible Raster
library("raster")

## RASTER 1 (e.g. land-use classes)
r1 <- raster( crs="+proj=utm +zone=31")
extent(r1) <- extent(0, 100, 0, 100)
res(r1) <- c(5, 5)
values(r1) <- sample(10, ncell(r1), replace=TRUE)
plot(r1)

## RASTER 2 (containing zones of interest)
r2 <- raster( crs="+proj=utm +zone=31")
extent(r2) <- extent(0, 100, 0, 100)
res(r2) <- c(5, 5)
values(r2) <- c(rep(1,100),rep(2,100),rep(3,100),rep(4,100))
plot(r2)

# (1) ZONAL STATISTICS
# a. how many cells per zone (independent of specific cell value)
zonal(r1,r2,"count")

# b. how many cells per zone of specific value 6
zonal(r1[r1==6],r2,"count")
# -> fails

# with reclassification
r1.reclass<-
  reclassify(r1,
             matrix(c(1,5,NA,
                    5.5,6.5,1, #class of interest
                    6.5,10,NA),
                    ncol=3,
                    byrow = T),
             include.lowest=T # include the lowest value from the table.
           )
zonal(r1.reclass,r2,"count")

Body:
you can use raster::match.

zonal(match(r1, 6),r2, "count")

As you can see from plot(match(r1, 6)), it only returns raster cells which hold the desired value(s). All other cells are NA.

r1==6 as used in your try unfortunately returns a vector and therefore cannot be used in focal anymore.


问:
Storm Trident Topology with Kafka: Received unexpected tuple error
We have a Trident topology that both consumes from and produces to kafka using the kafka-storm OpaqueTridentKafkaSpout and TridentKafkaState.  Everything works fine when running on our production storm cluster, but when run in local mode we very often receive the following error:

```<code>java.lang.RuntimeException: java.lang.RuntimeException: Received unexpected tuple source: $mastercoord-bg1:2, stream: $commit, id: {-4957901903366351898=6364388931843393707}, [1:0]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:128) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$fn__4606$fn__4619$fn__4670.invoke(executor.clj:806) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.util$async_loop$fn__543.invoke(util.clj:475) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at clojure.lang.AFn.run(AFn.java:22) [clojure-1.6.0.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_31]
Caused by: java.lang.RuntimeException: Received unexpected tuple source: $mastercoord-bg1:2, stream: $commit, id: {-4957901903366351898=6364388931843393707}, [1:0]
    at storm.trident.planner.SubtopologyBolt.execute(SubtopologyBolt.java:144) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at storm.trident.topology.TridentBoltExecutor.execute(TridentBoltExecutor.java:369) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$fn__4606$tuple_action_fn__4608.invoke(executor.clj:668) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$mk_task_receiver$fn__4529.invoke(executor.clj:424) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.disruptor$clojure_handler$reify__1229.onEvent(disruptor.clj:58) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    ... 6 common frames omitted
</code>```

We also see this error as part of the same error dump:

```<code>java.lang.RuntimeException: org.apache.storm.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /errors/<topology-name>/<bolt-name>-last-error
    at backtype.storm.util$wrap_in_runtime.invoke(util.clj:48) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.zookeeper$create_node.invoke(zookeeper.clj:92) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.cluster$mk_distributed_cluster_state$reify__2234.set_data(cluster.clj:104) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.cluster$mk_storm_cluster_state$reify__2774.report_error(cluster.clj:450) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$throttled_report_error_fn$fn__4385.invoke(executor.clj:191) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$mk_executor_data$fn__4439$fn__4440.invoke(executor.clj:253) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.util$async_loop$fn__543.invoke(util.clj:485) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at clojure.lang.AFn.run(AFn.java:22) ~[clojure-1.6.0.jar:na]
    at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_31]
Caused by: org.apache.storm.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /errors/<topology-name>/<bolt-name>-last-error
    at org.apache.storm.zookeeper.KeeperException.create(KeeperException.java:119) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.zookeeper.KeeperException.create(KeeperException.java:51) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.zookeeper.ZooKeeper.create(ZooKeeper.java:783) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:676) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:660) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.RetryLoop.callWithRetry(RetryLoop.java:107) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:656) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:441) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:431) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$3.forPath(CreateBuilderImpl.java:239) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$3.forPath(CreateBuilderImpl.java:193) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) ~[na:na]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
    at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) ~[clojure-1.6.0.jar:na]
    at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) ~[clojure-1.6.0.jar:na]
    at backtype.storm.zookeeper$create_node.invoke(zookeeper.clj:91) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    ... 7 common frames omitted
</code>```

Currently using the latest storm 0.10.0-SNAPSHOT built from github, but the same issue was occuring with the stable 0.9.3 release.  Any help would be greatly appreciated, thanks.

答: I just met the KeeperException$NodeExistsException because I inited 2 spouts and gave them the same ID. Change one of the IDs and the problem will be resolved.

Body:
We have a Trident topology that both consumes from and produces to kafka using the kafka-storm OpaqueTridentKafkaSpout and TridentKafkaState.  Everything works fine when running on our production storm cluster, but when run in local mode we very often receive the following error:

java.lang.RuntimeException: java.lang.RuntimeException: Received unexpected tuple source: $mastercoord-bg1:2, stream: $commit, id: {-4957901903366351898=6364388931843393707}, [1:0]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:128) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$fn__4606$fn__4619$fn__4670.invoke(executor.clj:806) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.util$async_loop$fn__543.invoke(util.clj:475) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at clojure.lang.AFn.run(AFn.java:22) [clojure-1.6.0.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_31]
Caused by: java.lang.RuntimeException: Received unexpected tuple source: $mastercoord-bg1:2, stream: $commit, id: {-4957901903366351898=6364388931843393707}, [1:0]
    at storm.trident.planner.SubtopologyBolt.execute(SubtopologyBolt.java:144) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at storm.trident.topology.TridentBoltExecutor.execute(TridentBoltExecutor.java:369) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$fn__4606$tuple_action_fn__4608.invoke(executor.clj:668) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$mk_task_receiver$fn__4529.invoke(executor.clj:424) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.disruptor$clojure_handler$reify__1229.onEvent(disruptor.clj:58) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    ... 6 common frames omitted

We also see this error as part of the same error dump:

java.lang.RuntimeException: org.apache.storm.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /errors/<topology-name>/<bolt-name>-last-error
    at backtype.storm.util$wrap_in_runtime.invoke(util.clj:48) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.zookeeper$create_node.invoke(zookeeper.clj:92) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.cluster$mk_distributed_cluster_state$reify__2234.set_data(cluster.clj:104) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.cluster$mk_storm_cluster_state$reify__2774.report_error(cluster.clj:450) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$throttled_report_error_fn$fn__4385.invoke(executor.clj:191) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.daemon.executor$mk_executor_data$fn__4439$fn__4440.invoke(executor.clj:253) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at backtype.storm.util$async_loop$fn__543.invoke(util.clj:485) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at clojure.lang.AFn.run(AFn.java:22) ~[clojure-1.6.0.jar:na]
    at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_31]
Caused by: org.apache.storm.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /errors/<topology-name>/<bolt-name>-last-error
    at org.apache.storm.zookeeper.KeeperException.create(KeeperException.java:119) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.zookeeper.KeeperException.create(KeeperException.java:51) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.zookeeper.ZooKeeper.create(ZooKeeper.java:783) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:676) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$11.call(CreateBuilderImpl.java:660) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.RetryLoop.callWithRetry(RetryLoop.java:107) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.pathInForeground(CreateBuilderImpl.java:656) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.protectedPathInForeground(CreateBuilderImpl.java:441) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl.forPath(CreateBuilderImpl.java:431) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$3.forPath(CreateBuilderImpl.java:239) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at org.apache.storm.curator.framework.imps.CreateBuilderImpl$3.forPath(CreateBuilderImpl.java:193) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) ~[na:na]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
    at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) ~[clojure-1.6.0.jar:na]
    at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) ~[clojure-1.6.0.jar:na]
    at backtype.storm.zookeeper$create_node.invoke(zookeeper.clj:91) ~[storm-core-0.10.0-SNAPSHOT.jar:0.10.0-SNAPSHOT]
    ... 7 common frames omitted

Currently using the latest storm 0.10.0-SNAPSHOT built from github, but the same issue was occuring with the stable 0.9.3 release.  Any help would be greatly appreciated, thanks.


问:
Not able to register Snapshot repository for AWS es domain
I am trying to register a snapshot repository. I have used the below role and policy:

{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "",
        "Effect": "Allow",
        "Principal": {
            "Service": "es.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
    }]
}
```

<p>And policy as below: </p>

<pre class="lang-py prettyprint-override"><code>{
    "Version": "2012-10-17",
    "Statement": [{
        "Action": ["s3:ListBucket"],
        "Effect": "Allow",
        "Resource": ["arn:aws:s3:::es-backuptest"]
    }, {
        "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "iam:PassRole"],
        "Effect": "Allow",
        "Resource": ["arn:aws:s3:::es-backuptest/*"]
    }]
}
</code>```

And I am using the below python script:

from boto.connection import AWSAuthConnection

class ESConnection(AWSAuthConnection):

    def __init__(self, region, **kwargs):
        super(ESConnection, self).__init__(**kwargs)
        self._set_auth_region_name(region)
        self._set_auth_service_name("es")

    def _required_auth_capability(self):
        return ['hmac-v4']

    if __name__ == "__main__":

    client = ESConnection(
            region='ap-south-1',
            host='es.domain.com',
            aws_access_key_id='test_id',
            aws_secret_access_key='test_secret_id', is_secure=False)

    print 'Registering Snapshot Repository'
    resp = client.make_request(method='POST',
            path='/_snapshot/snapshot-backup',
            data='{"type": "s3","settings": { "bucket": "es-backuptest","region": "ap-south-1","role_arn": "arn:aws:iam::arn:aws:iam::arn:aws:iam::rolename"}}')
    body = resp.read()
    print body
```

After having all this in place I am running the python script to register, but I am getting the below error:

{"Message":"Cross-account pass role is not allowed."}

Could anyone please let me know what I am missing here.

答:
there was mistake in the bucket configuration so changed it as below

```<code> data='{"type": "s3","settings": { "bucket": "S3-test-bucket","region": "us-east-1","base_path":"es-backuptest/","role_arn": "arn:aws:iam::rolename"}}')
</code>```

Which solved the issue.

Body:
I am trying to register a snapshot repository. I have used the below role and policy:

{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "",
        "Effect": "Allow",
        "Principal": {
            "Service": "es.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
    }]
}

And policy as below:

{
    "Version": "2012-10-17",
    "Statement": [{
        "Action": ["s3:ListBucket"],
        "Effect": "Allow",
        "Resource": ["arn:aws:s3:::es-backuptest"]
    }, {
        "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "iam:PassRole"],
        "Effect": "Allow",
        "Resource": ["arn:aws:s3:::es-backuptest/*"]
    }]
}

And I am using the below python script:

from boto.connection import AWSAuthConnection

class ESConnection(AWSAuthConnection):

    def __init__(self, region, **kwargs):
        super(ESConnection, self).__init__(**kwargs)
        self._set_auth_region_name(region)
        self._set_auth_service_name("es")

    def _required_auth_capability(self):
        return ['hmac-v4']

    if __name__ == "__main__":

    client = ESConnection(
            region='ap-south-1',
            host='es.domain.com',
            aws_access_key_id='test_id',
            aws_secret_access_key='test_secret_id', is_secure=False)

    print 'Registering Snapshot Repository'
    resp = client.make_request(method='POST',
            path='/_snapshot/snapshot-backup',
            data='{"type": "s3","settings": { "bucket": "es-backuptest","region": "ap-south-1","role_arn": "arn:aws:iam::arn:aws:iam::arn:aws:iam::rolename"}}')
    body = resp.read()
    print body

After having all this in place I am running the python script to register, but I am getting the below error:

{"Message":"Cross-account pass role is not allowed."}

Could anyone please let me know what I am missing here.

Body:
there was mistake in the bucket configuration so changed it as below

 data='{"type": "s3","settings": { "bucket": "S3-test-bucket","region": "us-east-1","base_path":"es-backuptest/","role_arn": "arn:aws:iam::rolename"}}')

Which solved the issue.