问:
Looking for non-destructive counterpart of `splice ARRAY,OFFSET,LENGTH,LIST`
splice is "destructive"; i.e. it modifies its first argument "in place".

For example:

```<code>  DB<63> @a = (0, 1, 2, 3, 4, 5)

  DB<64> @b = (20, 30, 40)

  DB<65> splice( @a, 2, 3, @b )

  DB<66> x \@a
0  ARRAY(0x1daf6e0)
   0  0
   1  1
   2  20
   3  30
   4  40
   5  5
</code>```

(The splice expression above returns the elements spliced out, but in this question I'm interested only in slice's side effects.)

Q: Is there a "non-destructive" counterpart function of splice?

E.g. if @a and @b are as originally defined above, then the desired non_destructive_splice function would be such that after

```<code>@new_a = non_destructive_splice( @a, 2, 3, @b );
</code>```

...the variable @new_a would hold (0, 1, 20, 30, 40, 5), and @a would be left unchanged.

答:
Just make a copy:

```<code>my @new_a = @a;
splice( @new_a, 2, 3, @b );
</code>```

Or if you want the same interface (incl negative offsets and optional arguments):

```<code>sub splice_r(\@;$$@) {
   my $num_args = @_;
   my $a      = shift;
   my $offset = shift;
   my $len    = shift;

   my @new_a = @$a;
   if    ($num_args == 1) { splice(@new_a)                    }
   elsif ($num_args == 2) { splice(@new_a, $offset)           }
   elsif ($num_args >= 3) { splice(@new_a, $offset, $len, @_) }
   return @new_a;
}

my @new_a = splice_r(@a, 2, 3, @b);
</code>```

Or use a slice to avoid needless copying:

```<code>my @new_a = ( @a[0..1], @b, @a[5..$#a] );
</code>```

Or if you want the same interface (incl negative offsets and optional arguments):

```<code>sub splice_r(\@;$$@) {
   my $num_args = @_;
   my $a   = shift;
   my $i   = shift;
   my $len = shift;

   $i //= 0;
   if ($i < 0) {
      $i += @$a;
      carp("Invalid argument") if $i < 0;
   }
   elsif ($i > @$a) {
      $i = @$a;
   }

   my $j;
   if ($num_args >= 3) {
      if ($len >= 0) {
         $j = $i + $len;
      } else {
         $j = @$a + $len;
         $j = 0 if $j < 0;
      }
   } else {
      $e = $#$a;
   }

   return ( @$a[0..$i-1], @_, @$a[$j..$#$a] );
}

my @new_a = splice_r(@a, 2, 3, @b);
</code>```

Body:
splice is "destructive"; i.e. it modifies its first argument "in place".

For example:

  DB<63> @a = (0, 1, 2, 3, 4, 5)

  DB<64> @b = (20, 30, 40)

  DB<65> splice( @a, 2, 3, @b )

  DB<66> x \@a
0  ARRAY(0x1daf6e0)
   0  0
   1  1
   2  20
   3  30
   4  40
   5  5

(The splice expression above returns the elements spliced out, but in this question I'm interested only in slice's side effects.)

Q: Is there a "non-destructive" counterpart function of splice?

E.g. if @a and @b are as originally defined above, then the desired non_destructive_splice function would be such that after

@new_a = non_destructive_splice( @a, 2, 3, @b );

...the variable @new_a would hold (0, 1, 20, 30, 40, 5), and @a would be left unchanged.

Body:
Just make a copy:

my @new_a = @a;
splice( @new_a, 2, 3, @b );

Or if you want the same interface (incl negative offsets and optional arguments):

sub splice_r(\@;$$@) {
   my $num_args = @_;
   my $a      = shift;
   my $offset = shift;
   my $len    = shift;

   my @new_a = @$a;
   if    ($num_args == 1) { splice(@new_a)                    }
   elsif ($num_args == 2) { splice(@new_a, $offset)           }
   elsif ($num_args >= 3) { splice(@new_a, $offset, $len, @_) }
   return @new_a;
}

my @new_a = splice_r(@a, 2, 3, @b);

Or use a slice to avoid needless copying:

my @new_a = ( @a[0..1], @b, @a[5..$#a] );

Or if you want the same interface (incl negative offsets and optional arguments):

sub splice_r(\@;$$@) {
   my $num_args = @_;
   my $a   = shift;
   my $i   = shift;
   my $len = shift;

   $i //= 0;
   if ($i < 0) {
      $i += @$a;
      carp("Invalid argument") if $i < 0;
   }
   elsif ($i > @$a) {
      $i = @$a;
   }

   my $j;
   if ($num_args >= 3) {
      if ($len >= 0) {
         $j = $i + $len;
      } else {
         $j = @$a + $len;
         $j = 0 if $j < 0;
      }
   } else {
      $e = $#$a;
   }

   return ( @$a[0..$i-1], @_, @$a[$j..$#$a] );
}

my @new_a = splice_r(@a, 2, 3, @b);


来源: stackexchange

问:
How to properly make a object file from header file (using an I2C board with a debian linux machine)
I have some source files that previously have been compiled for X86 architecture. Now I need to compile them for ARM architecture. When I try to use something like

g++ -c -x c++ foo.h

gcc -c -x c foo.h

it only gives me few instructions. I believe it doesn't link my header file to other included files. I only get "Disassembly of section .comment:".
Please note it does prompt me for other files, for example if foo includes foo1.h and foo2.h, if I don't include foo1 and foo2 headers in the same directory the compiler doesn't work.

Another thing which I don't understand is that both gcc and g++ produce the same assembly code, maybe because they only generate the comment section they look the same.

A little bit more details about my problem:
I'm using a USB-I2C converter board. The board provides only support for x86/x64 architecture. I managed to access the source file and to get the driver setup. Now I need to test everything together. In order to do so I need to be able to compile a sample code. When I want to do so, it calls on static libraries that need to be in .a extension. I need to create my own library.a file. In order to do so, I have found the source c files (.h header). Now I need to link them together during compilation and make object files, and eventually archive them together in a .a file.
Thank you for your help.

Edit (update):

A quick summary of what I have achieved so far:
- I was able to find a driver from a github repo.
- I was able to make the module
- I also compiled a new fresh kernel from a raspbian source code (I'm doing this for a Raspberry PI3):

```<code>uname -a
Linux raspberrypi 4.9.35-v7+ #1 SMP Tue Jul 4 22:40:25 BST 2017 armv7l GNU/Linux
</code>```

I was able to load the module properly:

lsmod
Module                  Size  Used by
spi_diolan_u2c          3247  0
i2c_diolan_u2c          3373  0
diolan_u2c_core         4268  2 i2c_diolan_u2c,spi_diolan_u2c

lsusb
Bus 001 Device 010: ID a257:2014

dmesg
[  126.758990] i2c_diolan_u2c: loading out-of-tree module taints kernel.
[  126.759241] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  130.651475] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  154.671532] usbcore: registered new interface driver diolan-u2c-core
[ 5915.799739] usb 1-1.2: USB disconnect, device number 4
[10591.295014] usb 1-1.2: new full-speed USB device number 6 using dwc_otg
[10591.425984] usb 1-1.2: New USB device found, idVendor=a257, idProduct=2014
[10591.425997] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[10591.426005] usb 1-1.2: Product: Diolan DLN1
[10591.426012] usb 1-1.2: Manufacturer: Diolan

What I'm not sure:
If the kernel space is properly mapped to physical hardware (if the loaded module can get ahold of my diolan-board)!!!
progress: based on my research, I think a hot-plug protocol would take care of that, but not sure!
confusion: why the lsusb still only shows the device ID. I know the manufacturer and kernel driver can determine what info to be shown, but only showing ID doesn't seem right to me

What I want to do now:
I would like to write a simple c source or python code to interact with my device. Basically I don't know how I can make connection between user space and kernel space. The manufacturer has provided some source code examples, libraries, etc. . However, I have given up on using them because they are for another architecture , based on qt, and I find it near impossible to find replacement for libraries they use in their static libraries ( I figured those libraries by restoring their .a archived file provided for x86)

I just need to know exactly what the next step should be for me to move on towards getting the board working with the PI.
Thank you :)

答:
You don't make any object file from a header file. On Linux object files (and executables) are ELF files. Use file(1) (or objdump(1) ...) to check.

Instead, a header file should be included (by #include preprocessor directive) in some *.cc file (technically a translation unit).

(You could precompile headers, but this is only useful to improve compilation time, which it does not always, and is an advanced and GCC specific usage; see this)

You do compile a C++ source file (some *.cc file) into an object file suffixed .o (or a C source file *.c compiled into an object file suffixed .o)

Read more about the preprocessor, and do spend several days reading about C or C++ (which are different programming languages). Read also more about compiling and linking.

I recommend to compile your C++ code with g++ -Wall -Wextra -g to get all warnings (with -Wall -Wextra ) and debug information (with -g).

A minimal compilation command to compile some yourfile.cc in C++ into an object file yourfile.o should probably be

```<code>g++ -c -Wall -Wextra -g yourfile.cc
</code>```

(you could remove -Wall -Wextra -g but I strongly recommend to keep them)

You may need to add other arguments to g++. They order matters a lot. Read the chapter about Invoking GCC

Notice that yourfile.cc contains very likely some (and often several) #include directives (usually near its start)

You very rarely need the -x c++ option to g++ (or -x c with gcc). I used it only once in my lifetime. In your case it surely is a mistake.

Very often, you use some build automation tool like GNU make. So you just use make to compile (but you need to write a Makefile - where tabs are significant)

Notice that some libraries can be header only (but this is not very usual), then you don't build any shared or static ELF libraries from them, but you just include headers in your own C or C++ code.

addenda

Regarding your http://dlnware.com/sites/dlnware.com/files/downloads/linux_setup.2.0.0.zip package (which indeed is poorly documented), you should look at the several examples given in the linux_setup/examples/ directory. Such code all have a #include "../common/dln_generic.h" (for instance, 4th line of examples/leds_gui/main.cpp) which itself have other includes. All the examples are Qt applications and provide a *.pro file for qmake (which itself generates  a Makefile for make from that .pro file). And passing -x c++ to g++ is rightly not mentioned at all.

ContentLicense: CC BY-SA 3.0

Body:
I have some source files that previously have been compiled for X86 architecture. Now I need to compile them for ARM architecture. When I try to use something like

g++ -c -x c++ foo.h

gcc -c -x c foo.h

it only gives me few instructions. I believe it doesn't link my header file to other included files. I only get "Disassembly of section .comment:".
Please note it does prompt me for other files, for example if foo includes foo1.h and foo2.h, if I don't include foo1 and foo2 headers in the same directory the compiler doesn't work.

Another thing which I don't understand is that both gcc and g++ produce the same assembly code, maybe because they only generate the comment section they look the same.

A little bit more details about my problem:
I'm using a USB-I2C converter board. The board provides only support for x86/x64 architecture. I managed to access the source file and to get the driver setup. Now I need to test everything together. In order to do so I need to be able to compile a sample code. When I want to do so, it calls on static libraries that need to be in .a extension. I need to create my own library.a file. In order to do so, I have found the source c files (.h header). Now I need to link them together during compilation and make object files, and eventually archive them together in a .a file.
Thank you for your help.

Edit (update):

A quick summary of what I have achieved so far:
- I was able to find a driver from a github repo.
- I was able to make the module
- I also compiled a new fresh kernel from a raspbian source code (I'm doing this for a Raspberry PI3):

uname -a
Linux raspberrypi 4.9.35-v7+ #1 SMP Tue Jul 4 22:40:25 BST 2017 armv7l GNU/Linux

I was able to load the module properly:

lsmod
Module                  Size  Used by
spi_diolan_u2c          3247  0
i2c_diolan_u2c          3373  0
diolan_u2c_core         4268  2 i2c_diolan_u2c,spi_diolan_u2c

lsusb
Bus 001 Device 010: ID a257:2014

dmesg
[  126.758990] i2c_diolan_u2c: loading out-of-tree module taints kernel.
[  126.759241] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  130.651475] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  154.671532] usbcore: registered new interface driver diolan-u2c-core
[ 5915.799739] usb 1-1.2: USB disconnect, device number 4
[10591.295014] usb 1-1.2: new full-speed USB device number 6 using dwc_otg
[10591.425984] usb 1-1.2: New USB device found, idVendor=a257, idProduct=2014
[10591.425997] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[10591.426005] usb 1-1.2: Product: Diolan DLN1
[10591.426012] usb 1-1.2: Manufacturer: Diolan

What I'm not sure:
If the kernel space is properly mapped to physical hardware (if the loaded module can get ahold of my diolan-board)!!!
progress: based on my research, I think a hot-plug protocol would take care of that, but not sure!
confusion: why the lsusb still only shows the device ID. I know the manufacturer and kernel driver can determine what info to be shown, but only showing ID doesn't seem right to me

What I want to do now:
I would like to write a simple c source or python code to interact with my device. Basically I don't know how I can make connection between user space and kernel space. The manufacturer has provided some source code examples, libraries, etc. . However, I have given up on using them because they are for another architecture , based on qt, and I find it near impossible to find replacement for libraries they use in their static libraries ( I figured those libraries by restoring their .a archived file provided for x86)

I just need to know exactly what the next step should be for me to move on towards getting the board working with the PI.
Thank you :)

Body:
You don't make any object file from a header file. On Linux object files (and executables) are ELF files. Use file(1) (or objdump(1) ...) to check.

Instead, a header file should be included (by #include preprocessor directive) in some *.cc file (technically a translation unit).

(You could precompile headers, but this is only useful to improve compilation time, which it does not always, and is an advanced and GCC specific usage; see this)

You do compile a C++ source file (some *.cc file) into an object file suffixed .o (or a C source file *.c compiled into an object file suffixed .o)

Read more about the preprocessor, and do spend several days reading about C or C++ (which are different programming languages). Read also more about compiling and linking.

I recommend to compile your C++ code with g++ -Wall -Wextra -g to get all warnings (with -Wall -Wextra ) and debug information (with -g).

A minimal compilation command to compile some yourfile.cc in C++ into an object file yourfile.o should probably be

g++ -c -Wall -Wextra -g yourfile.cc

(you could remove -Wall -Wextra -g but I strongly recommend to keep them)

You may need to add other arguments to g++. They order matters a lot. Read the chapter about Invoking GCC

Notice that yourfile.cc contains very likely some (and often several) #include directives (usually near its start)

You very rarely need the -x c++ option to g++ (or -x c with gcc). I used it only once in my lifetime. In your case it surely is a mistake.

Very often, you use some build automation tool like GNU make. So you just use make to compile (but you need to write a Makefile - where tabs are significant)

Notice that some libraries can be header only (but this is not very usual), then you don't build any shared or static ELF libraries from them, but you just include headers in your own C or C++ code.

addenda

Regarding your http://dlnware.com/sites/dlnware.com/files/downloads/linux_setup.2.0.0.zip package (which indeed is poorly documented), you should look at the several examples given in the linux_setup/examples/ directory. Such code all have a #include "../common/dln_generic.h" (for instance, 4th line of examples/leds_gui/main.cpp) which itself have other includes. All the examples are Qt applications and provide a *.pro file for qmake (which itself generates  a Makefile for make from that .pro file). And passing -x c++ to g++ is rightly not mentioned at all.


问:
Blob download_as_string SSL error on Google Container Engine
I'm running a container on Google Container Engine. Inside this container, I have some python code that is trying to read a blob from a bucket hosted o Google Cloud Storage.

The code is as simple as:

```<code>from google.cloud import storage

gs = storage.Client(project="my-shiny-project")
gc_bucket = gs.get_bucket("my-bucket")
blob = gc_bucket.get_blob("my-blob")
print blob.download_as_string()
</code>```

The code above works just fine on my local machine. However, when I run this in a Docker container on GKE, the part upto creation of the blob object works just fine. However, the call to download_as_string fails with:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 453, in download_as_string
    self.download_to_file(string_buffer, client=client)
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 412, in download_to_file
    self._do_download(transport, file_obj, download_url, headers)
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 363, in _do_download
    response = download.consume(transport)
  File "/usr/lib/python2.7/site-packages/google/resumable_media/download.py", line 136, in consume
    transport, u'GET', self.media_url, headers=headers)
  File "/usr/lib/python2.7/site-packages/google/resumable_media/_helpers.py", line 134, in http_request
    return transport.request(method, url, data=data, headers=headers)
  File "/usr/lib/python2.7/site-packages/google/auth/transport/requests.py", line 179, in request
    method, url, data=data, headers=request_headers, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)
</code>```

Any ideas why this failure happens?

FWIW, I tried other operations on the blob object such as getting the id, content_type, size, etc. These operations worked just fine. Even the exists() method of that object worked just fine (which presumably did an actual HEAD request on the object).

I'm using an 'alpine 3.5' container image. Python version is "Python 2.7.13 (default, Dec 22 2016, 09:22:15)"

[EDIT]

I changed the image to 'debian:jessie' and the code worked just fine. The openssl packages in these images have different versions. Looks like that has some effect. Would still be good to know exactly what the problem was.

答:
I figure out myself, I had to add to Dockerfile:

```<code># Base Stuff
RUN apk add --update \
openjdk8-jre \
ca-certificates \
java-cacerts \
libre2 \
libre2-dev \
gcc \
build-base \
linux-headers \
musl-dev \
python3-dev \
make \
openssl \
openssl-dev \
py3-openssl \
libffi \
libffi-dev \
openssh \
openssh-client \
python3-dev

RUN update-ca-certificates && gcloud -q components install gsutil
</code>```

And that made the trick.

Body:
I'm running a container on Google Container Engine. Inside this container, I have some python code that is trying to read a blob from a bucket hosted o Google Cloud Storage.

The code is as simple as:

from google.cloud import storage

gs = storage.Client(project="my-shiny-project")
gc_bucket = gs.get_bucket("my-bucket")
blob = gc_bucket.get_blob("my-blob")
print blob.download_as_string()

The code above works just fine on my local machine. However, when I run this in a Docker container on GKE, the part upto creation of the blob object works just fine. However, the call to download_as_string fails with:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 453, in download_as_string
    self.download_to_file(string_buffer, client=client)
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 412, in download_to_file
    self._do_download(transport, file_obj, download_url, headers)
  File "/usr/lib/python2.7/site-packages/google/cloud/storage/blob.py", line 363, in _do_download
    response = download.consume(transport)
  File "/usr/lib/python2.7/site-packages/google/resumable_media/download.py", line 136, in consume
    transport, u'GET', self.media_url, headers=headers)
  File "/usr/lib/python2.7/site-packages/google/resumable_media/_helpers.py", line 134, in http_request
    return transport.request(method, url, data=data, headers=headers)
  File "/usr/lib/python2.7/site-packages/google/auth/transport/requests.py", line 179, in request
    method, url, data=data, headers=request_headers, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 447, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)

Any ideas why this failure happens?

FWIW, I tried other operations on the blob object such as getting the id, content_type, size, etc. These operations worked just fine. Even the exists() method of that object worked just fine (which presumably did an actual HEAD request on the object).

I'm using an 'alpine 3.5' container image. Python version is "Python 2.7.13 (default, Dec 22 2016, 09:22:15)"

[EDIT]

I changed the image to 'debian:jessie' and the code worked just fine. The openssl packages in these images have different versions. Looks like that has some effect. Would still be good to know exactly what the problem was.

Body:
I figure out myself, I had to add to Dockerfile:

# Base Stuff
RUN apk add --update \
openjdk8-jre \
ca-certificates \
java-cacerts \
libre2 \
libre2-dev \
gcc \
build-base \
linux-headers \
musl-dev \
python3-dev \
make \
openssl \
openssl-dev \
py3-openssl \
libffi \
libffi-dev \
openssh \
openssh-client \
python3-dev

RUN update-ca-certificates && gcloud -q components install gsutil

And that made the trick.


问:
Library to Integrate Facebook login with Play Framework?
I'm learning using Play Framework and doing a demo app for it.

For this app I want also to integrate with the Facebook API, allowing users to log using Facebook Ids. Knowing that Play is a stateless framework and the way it works, there is some library or module recommended?

I've not been able to find any but I ask just in case.

答: There is also now a fbconnect module listed on Play's site.</p>

ContentLicense: CC BY-SA 2.5


问:
Pylons routing, what is the location attribute?
I'm looking at the reddit source code and ran into a route that looks like the following:

mc('/prefs/:location', controller='forms', action='prefs', location='options')

Searching the documentation here, I can't find anything related to the location attribute:

https://thejimmyg.github.io/pylonsbook/en/1.0/urls-routing-and-dispatch.html

What is location='options' supposed to do for this route?

答:
routes.Mapper.connect() takes *args and **kwargs as arguments.  Since locations='options' is a valid **kwargs entry and in a valid location, it will be accepted as a valid passed variable.  I don't have the source code available, so I don't know what connect() will do with this variable.  I'm guessing it simply attaches the extra name=value pairs to the created URLs.

You can find more documentation here: http://routes.readthedocs.io/en/latest/modules/mapper.html#routes.mapper.Mapper.connect


问:
subset a data frame by row names of different rows
I need to subset lines of data frame according their name. I have tried the following code but it is not working.</p>

```<code>Name  plot
12     25
22     23
14     12
16     22
23     54

DF.new <- subset(DF, rownames== c("12" , "16"))
</code>```

答:
Using dplyr:

```<code>library(dplyr)
DF <- data.frame(row.names=c("12a", "22a", "13a"), Name=c("12","22","13"), plot=c(25,18,9))
</code>```

If you want to filter by the data frame column "Name", then:

```<code>DF.new -> DF %>% filter(Name %in% c("12", "16"))
</code>```

If you want to filter by actual row.names of the df, then:

```<code>DF.new -> DF %>% filter(row.names(DF) %in% c("12a","13a"))
</code>```

Or, using base R:

DF.new -> DF[DF$Name %in% c("12","13"), ] or

DF.new ->  DF[row.names(DF) %in% c("12a","13a"),]

Body:
I need to subset lines of data frame according their name. I have tried the following code but it is not working.

Name  plot
12     25
22     23
14     12
16     22
23     54

DF.new <- subset(DF, rownames== c("12" , "16"))

Body:
Using dplyr:

library(dplyr)
DF <- data.frame(row.names=c("12a", "22a", "13a"), Name=c("12","22","13"), plot=c(25,18,9))

If you want to filter by the data frame column "Name", then:

DF.new -> DF %>% filter(Name %in% c("12", "16"))

If you want to filter by actual row.names of the df, then:

DF.new -> DF %>% filter(row.names(DF) %in% c("12a","13a"))

Or, using base R:

DF.new -> DF[DF$Name %in% c("12","13"), ] or

DF.new ->  DF[row.names(DF) %in% c("12a","13a"),]


问:
uploading eclipse project into Github account first time
See I am doing it for the first time meaning the project was never added to GitHub repository... so when I right click the project->Team->Commit .. I see files under Unstaged Section and cant commit as I see that message "There are no staged files" so does this mean I have to do this step before Right click the project->Team->Add to Index?</p>

答:
Yes, you have to stage files before you can commit them. This is just the normal git workflow, regardless if you're using the git CLI or eGit.

https://wiki.eclipse.org/WTP_Git_Migration_Home lists some learning materials you can use, and eGit itself has a good user guide at https://wiki.eclipse.org/EGit/User_Guide .


问:
Check if Assembly Exists by name before loading it
I want to take this:

```<code>try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}
</code>```

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

答: You can use Assembly.ReflectionOnlyLoad to try to get the Assembly. See http://msdn.microsoft.com/de-de/library/0et80c7k(v=vs.110).aspx . If the assembly won't be found and an exception is raised, but if it was found then the assembly is not loaded to your AppDomain. You can see it as "TryLoadAssembly". ;)</p>

Body:
I want to take this:

try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?


问:
Android - Geofence disappearing when app is killed
At the risk of being marked as duplicate, I ask this question once more. I've tried every proposed solution here in stackoverflow (except using a third party library because I want to use GoogleAPIClient instead) and still, I cannot make it work. I used IntentService and BroadcastReceiver; geofences still keep disappearing after I close the app. If it's in foreground or background, it works perfectly but completely killing the app also completely kills the geofences.

I've only tested it in Nougat and Marshmallow. Does the new Doze function of Android affect it? My GPS is always on, my device doesn't restart, although I've turned off my wifi/data because I want the geofencing to depend purely on the GPS. Oh, and I'm using a fake gps app to test it.

Below are the relevant parts of my code:

Home.java

```<code>public class Home extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    if (db.isEmpty()) {
        getData(); //get geofences from the server. at this point, the wifi is still on
    } else {
        startGeofencing();
    }

}

 private void startGeofencing(){
    //Set up geofence
    GeofencingMethods gM = new GeofencingMethods(getApplicationContext(), prefs);
    RealmResults<ServerGeofence> geofenceList = realm.where(ServerGeofence.class).findAll();
    for (ServerGeofence g : geofenceList) {
        Geofence geofence = gM.createGeofence(g.getGeof_name(), g.getGeof_lat(), g.getGeof_long(), g.getGeof_rad()*1000);
        gM.addToGeofencingRequest(geofence);
    }

    //Build googleApiClient and connect to service
    gM.buildGoogleApiClient();
}
</code>```

GeofencingMethods.java

```<code>public class GeofencingMethods {
private GeofencingRequest.Builder geofencingRequestBuilder;
private PendingIntent geofencePendingIntent;
private Context c;
private GoogleApiClient googleApiClient;
private SharedPreferences prefs;

public GeofencingMethods(Context c, SharedPreferences prefs) {
    this.c = c;
    this.prefs = prefs;
    geofencingRequestBuilder = new GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL);
}

public Geofence createGeofence(String name, double lat, double lng, float radius) {
    return new Geofence.Builder()
            .setRequestId(name)
            .setCircularRegion(lat, lng, radius)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER
                    | Geofence.GEOFENCE_TRANSITION_DWELL
                    | Geofence.GEOFENCE_TRANSITION_EXIT)
            .setLoiteringDelay(Constants.LOITERING_DELAY) //10 minutes dwelling
            .build();
}

public void addToGeofencingRequest(Geofence g) {
           prefs.edit().putInt(Constants.GEOFENCE_NUM, prefs.getInt(Constants.GEOFENCE_NUM, 0)+1).commit();
    geofencingRequestBuilder.addGeofence(g);
}

public PendingIntent createPendingIntent() {
    if (geofencePendingIntent != null) return geofencePendingIntent;

 //   Intent intent = new Intent(c, GeofenceTriggeredService.class);
 //   geofencePendingIntent = PendingIntent.getService(c, Constants.PENDING_INTENT_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intent = new Intent(Constants.ACTION_GEOFENCE_RECEIVED);
    geofencePendingIntent = PendingIntent.getBroadcast(c, Constants.PENDING_INTENT_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    return geofencePendingIntent;
}

public void addToGeofencingApi(){
    if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    }

    LocationServices.GeofencingApi.addGeofences(
            googleApiClient, geofencingRequestBuilder.build(), createPendingIntent())
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Toast.makeText(
                                c,
                                "Geofences added",
                                Toast.LENGTH_SHORT
                        ).show();

                    } else if (status.getStatusCode() == 1000) {
                        Toast.makeText(
                                c,
                                "Please turn on Google Location services in Settings. Switch to \"High Accuracy\" mode",
                                Toast.LENGTH_LONG
                        ).show();

                        prefs.edit().putInt(Constants.GEOFENCE_NUM, 0).commit();
                    }

                }
            });
}
//Building googleAPI client
public synchronized void buildGoogleApiClient() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(c)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        System.out.println("GOOGLE API CLIENT CONNECTED");
                        addToGeofencingApi();
                        //Go to service when triggered

                    }
                    @Override
                    public void onConnectionSuspended(int i) {
                        if(googleApiClient!=null){
                            googleApiClient.connect();
                        }
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Toast.makeText(c, "Failed to connect to GoogleApiClient. Please restart application.", Toast.LENGTH_LONG).show();
                    }
                })
                .addApi(LocationServices.API).build();

    }
    if(!googleApiClient.isConnected() && !googleApiClient.isConnecting()){
        googleApiClient.connect();
    }
}
</code>```

GeofenceReceiver.java

```<code>public class GeofenceReceiver extends BroadcastReceiver {
private Context c;
private SharedPreferences prefs;

@Override
public void onReceive(Context context, Intent intent) {
    this.c = context;
    prefs = c.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            context.registerReceiver(this, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

        }
    }

    if ("android.location.PROVIDERS_CHANGED".equals(intent.getAction())) {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (realm.where(ServerGeofence.class).count() <= 0) {
                getData();
            } else {
                startGeofencing();
            }
        } else {
            // go to settings and do it!!
        }
    }

    if(Constants.ACTION_GEOFENCE_RECEIVED.equals(intent.getAction())) {
        Toast.makeText(context, "Geofence Spotted", Toast.LENGTH_LONG).show();
        new NotificationMaker(context).geofenceEvent(intent);
    }
}
</code>```

NotificationMaker.java

```<code>public class NotificationMaker {
private Context c;
private int s;

public NotificationMaker(Context c){
    this.c = c;
}

public void geofenceEvent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

    if (geofencingEvent.hasError()) {
        Toast.makeText(c, "ERROR: " + getErrorString(geofencingEvent.getErrorCode()), Toast.LENGTH_LONG).show();
        return;
    }

    int geoFenceTransition = geofencingEvent.getGeofenceTransition();

    if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geoFenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL
            || geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(geoFenceTransition, triggeringGeofences);

        sendNotification(geofenceTransitionDetails);

    }
}

private String getGeofenceTransitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
    ArrayList<String> triggeringGeofencesList = new ArrayList<>();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesList.add(geofence.getRequestId());
    }
    String status = null;
    s = 0;
    if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
        status = "Entering ";
        s = 0;
    } else if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
        status = "Dwelling ";
        s = 1;
    } else if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        status = "Exiting ";
        s = 2;
    }

    //log event

    return status + TextUtils.join(", ", triggeringGeofencesList);
}

private String getErrorString(int errorCode) {
    switch (errorCode) {
        case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
            return "GeoFence not available";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
            return "Too many GeoFences";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
            return "Too many pending intents";
        default:
            return "Unknown error.";
    }
}

private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {

    System.out.println("Creating notification");
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(c);
    notificationBuilder
            .setSmallIcon(com.google.android.gms.R.drawable.common_full_open_on_phone)
            .setColor(ContextCompat.getColor(c, R.color.colorPrimary))
            .setContentTitle(msg)
            .setContentText("Geofence Spotted")
            .setContentIntent(notificationPendingIntent)
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
            .setAutoCancel(true);
    return notificationBuilder.build();

}

private void sendNotification(String msg) {

    System.out.println("Sending notification");
    Intent notificationIntent = new Intent(c, Home.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(c);
    stackBuilder.addParentStack(Home.class);
    stackBuilder.addNextIntent(notificationIntent);

    int id = (int) System.currentTimeMillis();
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(id, createNotification(msg, notificationPendingIntent));
}
</code>```

}

AndroidManifest

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SplashScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Home"/>

    <service android:name="com.example.GeofenceTriggeredService"
        android:enabled="true"
        android:directBootAware="true"
        android:exported="false"/>

    <receiver android:name="com.example.GeofenceReceiver"
        android:enabled="true"
        android:exported="false"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.location.PROVIDERS_CHANGED" />
            <action android:name="android.location.MODE_CHANGED" />
            <action android:name="com.example.ACTION_GEOFENCE_RECEIVED"/>
        </intent-filter>
    </receiver>

</application>
</code>```

Any help would be appreciated! :D

答:
Upon boot and starting the app I would start an IntentService that then registers a Geofence:

```<code>public class RegisterGeoIntentService extends IntentService {
...
    Intent intent = new Intent("com.xyz.app.ACTION_RECEIVE_GEOFENCE");
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
...
</code>```

And then in the registered Intent:

```<code>public class GeofenceReceiver extends BroadcastReceiver {
...

   @Override
   public void onReceive(Context context, Intent intent) {
    this.context = context;

    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if(geofencingEvent.hasError()) {
        String errorMessage = GeoErrorMessages.getErrorString(context, geofencingEvent.getErrorCode());
        Log.e(TAG, errorMessage);
        return;
    }

    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
...
</code>```

Body:
At the risk of being marked as duplicate, I ask this question once more. I've tried every proposed solution here in stackoverflow (except using a third party library because I want to use GoogleAPIClient instead) and still, I cannot make it work. I used IntentService and BroadcastReceiver; geofences still keep disappearing after I close the app. If it's in foreground or background, it works perfectly but completely killing the app also completely kills the geofences.

I've only tested it in Nougat and Marshmallow. Does the new Doze function of Android affect it? My GPS is always on, my device doesn't restart, although I've turned off my wifi/data because I want the geofencing to depend purely on the GPS. Oh, and I'm using a fake gps app to test it.

Below are the relevant parts of my code:

Home.java

public class Home extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    if (db.isEmpty()) {
        getData(); //get geofences from the server. at this point, the wifi is still on
    } else {
        startGeofencing();
    }

}

 private void startGeofencing(){
    //Set up geofence
    GeofencingMethods gM = new GeofencingMethods(getApplicationContext(), prefs);
    RealmResults<ServerGeofence> geofenceList = realm.where(ServerGeofence.class).findAll();
    for (ServerGeofence g : geofenceList) {
        Geofence geofence = gM.createGeofence(g.getGeof_name(), g.getGeof_lat(), g.getGeof_long(), g.getGeof_rad()*1000);
        gM.addToGeofencingRequest(geofence);
    }

    //Build googleApiClient and connect to service
    gM.buildGoogleApiClient();
}

GeofencingMethods.java

public class GeofencingMethods {
private GeofencingRequest.Builder geofencingRequestBuilder;
private PendingIntent geofencePendingIntent;
private Context c;
private GoogleApiClient googleApiClient;
private SharedPreferences prefs;

public GeofencingMethods(Context c, SharedPreferences prefs) {
    this.c = c;
    this.prefs = prefs;
    geofencingRequestBuilder = new GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL);
}

public Geofence createGeofence(String name, double lat, double lng, float radius) {
    return new Geofence.Builder()
            .setRequestId(name)
            .setCircularRegion(lat, lng, radius)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER
                    | Geofence.GEOFENCE_TRANSITION_DWELL
                    | Geofence.GEOFENCE_TRANSITION_EXIT)
            .setLoiteringDelay(Constants.LOITERING_DELAY) //10 minutes dwelling
            .build();
}

public void addToGeofencingRequest(Geofence g) {
           prefs.edit().putInt(Constants.GEOFENCE_NUM, prefs.getInt(Constants.GEOFENCE_NUM, 0)+1).commit();
    geofencingRequestBuilder.addGeofence(g);
}

public PendingIntent createPendingIntent() {
    if (geofencePendingIntent != null) return geofencePendingIntent;

 //   Intent intent = new Intent(c, GeofenceTriggeredService.class);
 //   geofencePendingIntent = PendingIntent.getService(c, Constants.PENDING_INTENT_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intent = new Intent(Constants.ACTION_GEOFENCE_RECEIVED);
    geofencePendingIntent = PendingIntent.getBroadcast(c, Constants.PENDING_INTENT_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    return geofencePendingIntent;
}

public void addToGeofencingApi(){
    if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    }

    LocationServices.GeofencingApi.addGeofences(
            googleApiClient, geofencingRequestBuilder.build(), createPendingIntent())
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Toast.makeText(
                                c,
                                "Geofences added",
                                Toast.LENGTH_SHORT
                        ).show();

                    } else if (status.getStatusCode() == 1000) {
                        Toast.makeText(
                                c,
                                "Please turn on Google Location services in Settings. Switch to \"High Accuracy\" mode",
                                Toast.LENGTH_LONG
                        ).show();

                        prefs.edit().putInt(Constants.GEOFENCE_NUM, 0).commit();
                    }

                }
            });
}
//Building googleAPI client
public synchronized void buildGoogleApiClient() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(c)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        System.out.println("GOOGLE API CLIENT CONNECTED");
                        addToGeofencingApi();
                        //Go to service when triggered

                    }
                    @Override
                    public void onConnectionSuspended(int i) {
                        if(googleApiClient!=null){
                            googleApiClient.connect();
                        }
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Toast.makeText(c, "Failed to connect to GoogleApiClient. Please restart application.", Toast.LENGTH_LONG).show();
                    }
                })
                .addApi(LocationServices.API).build();

    }
    if(!googleApiClient.isConnected() && !googleApiClient.isConnecting()){
        googleApiClient.connect();
    }
}

GeofenceReceiver.java

public class GeofenceReceiver extends BroadcastReceiver {
private Context c;
private SharedPreferences prefs;

@Override
public void onReceive(Context context, Intent intent) {
    this.c = context;
    prefs = c.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            context.registerReceiver(this, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

        }
    }

    if ("android.location.PROVIDERS_CHANGED".equals(intent.getAction())) {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (realm.where(ServerGeofence.class).count() <= 0) {
                getData();
            } else {
                startGeofencing();
            }
        } else {
            // go to settings and do it!!
        }
    }

    if(Constants.ACTION_GEOFENCE_RECEIVED.equals(intent.getAction())) {
        Toast.makeText(context, "Geofence Spotted", Toast.LENGTH_LONG).show();
        new NotificationMaker(context).geofenceEvent(intent);
    }
}

NotificationMaker.java

public class NotificationMaker {
private Context c;
private int s;

public NotificationMaker(Context c){
    this.c = c;
}

public void geofenceEvent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

    if (geofencingEvent.hasError()) {
        Toast.makeText(c, "ERROR: " + getErrorString(geofencingEvent.getErrorCode()), Toast.LENGTH_LONG).show();
        return;
    }

    int geoFenceTransition = geofencingEvent.getGeofenceTransition();

    if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geoFenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL
            || geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        String geofenceTransitionDetails = getGeofenceTransitionDetails(geoFenceTransition, triggeringGeofences);

        sendNotification(geofenceTransitionDetails);

    }
}

private String getGeofenceTransitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
    ArrayList<String> triggeringGeofencesList = new ArrayList<>();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesList.add(geofence.getRequestId());
    }
    String status = null;
    s = 0;
    if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
        status = "Entering ";
        s = 0;
    } else if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
        status = "Dwelling ";
        s = 1;
    } else if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        status = "Exiting ";
        s = 2;
    }

    //log event

    return status + TextUtils.join(", ", triggeringGeofencesList);
}

private String getErrorString(int errorCode) {
    switch (errorCode) {
        case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
            return "GeoFence not available";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
            return "Too many GeoFences";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
            return "Too many pending intents";
        default:
            return "Unknown error.";
    }
}

private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {

    System.out.println("Creating notification");
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(c);
    notificationBuilder
            .setSmallIcon(com.google.android.gms.R.drawable.common_full_open_on_phone)
            .setColor(ContextCompat.getColor(c, R.color.colorPrimary))
            .setContentTitle(msg)
            .setContentText("Geofence Spotted")
            .setContentIntent(notificationPendingIntent)
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
            .setAutoCancel(true);
    return notificationBuilder.build();

}

private void sendNotification(String msg) {

    System.out.println("Sending notification");
    Intent notificationIntent = new Intent(c, Home.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(c);
    stackBuilder.addParentStack(Home.class);
    stackBuilder.addNextIntent(notificationIntent);

    int id = (int) System.currentTimeMillis();
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(id, createNotification(msg, notificationPendingIntent));
}

}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SplashScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Home"/>

    <service android:name="com.example.GeofenceTriggeredService"
        android:enabled="true"
        android:directBootAware="true"
        android:exported="false"/>

    <receiver android:name="com.example.GeofenceReceiver"
        android:enabled="true"
        android:exported="false"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.location.PROVIDERS_CHANGED" />
            <action android:name="android.location.MODE_CHANGED" />
            <action android:name="com.example.ACTION_GEOFENCE_RECEIVED"/>
        </intent-filter>
    </receiver>

</application>

Any help would be appreciated! :D

Body:
Upon boot and starting the app I would start an IntentService that then registers a Geofence:

public class RegisterGeoIntentService extends IntentService {
...
    Intent intent = new Intent("com.xyz.app.ACTION_RECEIVE_GEOFENCE");
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
...

And then in the registered Intent:

public class GeofenceReceiver extends BroadcastReceiver {
...

   @Override
   public void onReceive(Context context, Intent intent) {
    this.context = context;

    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if(geofencingEvent.hasError()) {
        String errorMessage = GeoErrorMessages.getErrorString(context, geofencingEvent.getErrorCode());
        Log.e(TAG, errorMessage);
        return;
    }

    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
...


问:
How to automatically handle DialogBoxShowing event in Python(Revit Dynamo)?
How do I subscribe to Revit events in Python (Dynamo)?

Specifically DialogBoxShowing so I can see if it is "Export with Temporary Hide/Isolate" warning and select "Leave the Temporary Isolate Mode on and Export"?

It is done in C# here:

http://thebuildingcoder.typepad.com/blog/2013/03/export-wall-parts-individually-to-dxf.html

See sub-heading: Handling and Dismissing a Warning Message

Thanks!

答:
To make it more simple than in the tutorial :

Inside Revit, with RevitPythonShell, the event subscribing part can be very easy.

An event handler is just a callable with two arguments : senderand event. Then the event, or the sender gives parameters to play with, DialogId and OverrideResultin our case.

To keep the Building Coder example, let's go with :

```<code>def on_dialog_open(sender, event):
    try:
        if event.DialogId == 'TaskDialog_Really_Print_Or_Export_Temp_View_Modes':
            event.OverrideResult(1002)
            # 1001 call TaskDialogResult.CommandLink1
            # 1002 call TaskDialogResult.CommandLink2
            # int(TaskDialogResult.CommandLink2) to check the result
    except Exception as e:
        pass #print(e) # uncomment this to debug
</code>```

You only need to plug this function to an event with the following syntax :

__uiControlledApplication__.DialogBoxShowing += on_dialog_open

This can be done in the startup file of RevitPythonShell :

C:\Users\USERNAME\AppData\Roaming\RevitPythonShell2017\startup.py

(Or in the startup part of your addin)

The better way is to unregister the handler if you don't need it anymore, i.e. when Revit is closing (check the tutorial for more details) :

__uiControlledApplication__.DialogBoxShowing -= on_dialog_open

If you want to try this within the console, you can use :

```<code>def on_dialog_open(sender, event):
    # [...]

__revit__.DialogBoxShowing += on_dialog_open
</code>```

And after you try an export:

__revit__.DialogBoxShowing -= on_dialog_open

EDIT : shortcuts for result commands  (thanks Callum !)

```<code>('Cancel', 2)
('Close', 8)
('CommandLink1', 1001)
('CommandLink2', 1002)
('CommandLink3', 1003)
('CommandLink4', 1004)
('No', 7)
('None', 0)
('Ok', 1)
('Retry', 4)
('Yes', 6)
</code>```

Body:
To make it more simple than in the tutorial :

Inside Revit, with RevitPythonShell, the event subscribing part can be very easy.

An event handler is just a callable with two arguments : senderand event. Then the event, or the sender gives parameters to play with, DialogId and OverrideResultin our case.

To keep the Building Coder example, let's go with :

def on_dialog_open(sender, event):
    try:
        if event.DialogId == 'TaskDialog_Really_Print_Or_Export_Temp_View_Modes':
            event.OverrideResult(1002)
            # 1001 call TaskDialogResult.CommandLink1
            # 1002 call TaskDialogResult.CommandLink2
            # int(TaskDialogResult.CommandLink2) to check the result
    except Exception as e:
        pass #print(e) # uncomment this to debug

You only need to plug this function to an event with the following syntax :

__uiControlledApplication__.DialogBoxShowing += on_dialog_open

This can be done in the startup file of RevitPythonShell :

C:\Users\USERNAME\AppData\Roaming\RevitPythonShell2017\startup.py

(Or in the startup part of your addin)

The better way is to unregister the handler if you don't need it anymore, i.e. when Revit is closing (check the tutorial for more details) :

__uiControlledApplication__.DialogBoxShowing -= on_dialog_open

If you want to try this within the console, you can use :

def on_dialog_open(sender, event):
    # [...]

__revit__.DialogBoxShowing += on_dialog_open

And after you try an export:

__revit__.DialogBoxShowing -= on_dialog_open

EDIT : shortcuts for result commands  (thanks Callum !)

('Cancel', 2)
('Close', 8)
('CommandLink1', 1001)
('CommandLink2', 1002)
('CommandLink3', 1003)
('CommandLink4', 1004)
('No', 7)
('None', 0)
('Ok', 1)
('Retry', 4)
('Yes', 6)


问:
Petapoco with Datatable
I am new in Petapoco,Can I retrieve table data as Datatable using stored procedure in petapoco ORM ? I tried in google but I didn't get any answer from google.Any one know that? </p>

答:
Yes, you can execute stored procedures using Petapoco.

Example:

```<code>var result = db.Fetch<dynamic>(";EXEC GetSomething @@Year = @0", 2017);
</code>```

Petapoco returns a List<T> and I recommend you to use List instead of  Datatable, but if you want you can convert your list to a Datatable

Title: Petapoco with Datatable

Body:
Yes, you can execute stored procedures using Petapoco.

Example:

var result = db.Fetch<dynamic>(";EXEC GetSomething @@Year = @0", 2017);

Petapoco returns a List<T> and I recommend you to use List instead of  Datatable, but if you want you can convert your list to a Datatable


问:
Embedded Google calendar : how to set range of hours to display?
Given the following embedding code:

```<code><iframe src="https://www.google.com/calendar/embed?
title=2014 PLIDAM International Symposium (Paris)&
dates=20140611/20140615&
mode=WEEK&
showNav=1&
showDate=1&
showPrint=1&
showTabs=1&
showCalendars=0&
showTz=1;
height=600&
wkst=2&
bgcolor=%23666666&
src=vdfmfbp0msroletduigs2qtkoc%40group.calendar.google.com&
color=%232952A3&
ctz=Europe%2FParis"
style=" border:solid 1px #777 " width="800" height="600" frameborder="0" scrolling="no"></iframe>
</code>```

Is there a parameter to set the hours to display/focus_on from 09:00 to 18:00 (6pm), aka the working hours ? Same for days, is there someways to just display/focus_on the rights 4 days only.

Fiddle here

答:
There doesn't appear to be a way to do this through the API, currently. I would use javascript/jQuery to remove the elements you don't want to show in the DOM after the iframe has finished loading.

So, you could delete the Wednesday column, if you know the column index, by something like this:

```<code>$("tr").each(function() {
    $(this).filter("td:eq(3)").remove();
});
</code>```

You can also scroll a specific div into view:

https://stackoverflow.com/a/4884904/5129424

```<code>$("#myImage")[0].scrollIntoView();
</code>```

Body:
Given the following embedding code:

Is there a parameter to set the hours to display/focus_on from 09:00 to 18:00 (6pm), aka the working hours ? Same for days, is there someways to just display/focus_on the rights 4 days only.

Fiddle here

Body:
There doesn't appear to be a way to do this through the API, currently. I would use javascript/jQuery to remove the elements you don't want to show in the DOM after the iframe has finished loading.

So, you could delete the Wednesday column, if you know the column index, by something like this:

$("tr").each(function() {
    $(this).filter("td:eq(3)").remove();
});

You can also scroll a specific div into view:

https://stackoverflow.com/a/4884904/5129424

$("#myImage")[0].scrollIntoView();


问:
Twilio Programmable Chat - Push notifications not arriving
I'm working on an app that uses the Twilio Programmable Chat API. I've created an APNS development cert for the app and verified that notifications are landing using Pusher. I've created a new push credential in the Programmable Chat console using this cert and checked the "use this credential for sending to a sandbox APN" checkbox. I've updated our IpMessagingGrant call to use this credential's Sid. Lastly, I'm registering our device token successfully with the TwilioChatClient.

I'm not receiving push notifications for received messages, etc. and not sure what other levers I have at my disposal. If anyone on the team sees this message I'd love to know how I can try to debug this.

答:
It looks like your credentials are in good shape but notifications are not yet enabled for your chat instance.  This step only needs to be done once per chat instance per notification type:

```<code>curl -X POST https://chat.twilio.com/v2/Services/{service sid} \
-d 'Notifications.NewMessage.Enabled=true' \
-d 'Notifications.NewMessage.Template=A New message in ${CHANNEL} from ${USER}: ${MESSAGE}' \
-d 'Notifications.NewMessage.Sound=default' \
-u '{twilio account sid}:{twilio auth token}'
</code>```

This should solve the issue you're seeing.  Docs for this can be found here: https://www.twilio.com/docs/api/chat/guides/push-notification-configuration#push-configuring

Please let us know if you have any questions or this does not get pushes flowing for you.

Body:
It looks like your credentials are in good shape but notifications are not yet enabled for your chat instance.  This step only needs to be done once per chat instance per notification type:

curl -X POST https://chat.twilio.com/v2/Services/{service sid} \
-d 'Notifications.NewMessage.Enabled=true' \
-d 'Notifications.NewMessage.Template=A New message in ${CHANNEL} from ${USER}: ${MESSAGE}' \
-d 'Notifications.NewMessage.Sound=default' \
-u '{twilio account sid}:{twilio auth token}'

This should solve the issue you're seeing.  Docs for this can be found here: https://www.twilio.com/docs/api/chat/guides/push-notification-configuration#push-configuring

Please let us know if you have any questions or this does not get pushes flowing for you.


问:
Test prices on shop findelements?
I have little problem with my school project.

It's a shop test in Selenium / Java. This is the shopping query: https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=nothing+car&rh=i%3Aaps%2Ck%3Anothing+car

And I tried get all products prices in test.

Is there any other way than this?

```<code>String string = findelement(by.xpath("//[@id='result_0']/div/div/div/div[2]/div[2]/div[1]/div[1]/a/span/span"))
System.out.println(string);
</code>```

After printing that value, I need to check if the value < 20$, and return a failure if so.

答:
You can try to use

```<code>//li[starts-with(@id,"result_")]//span[@class="sx-price-whole" and position()=last()]
</code>```

to get all the highest prices (dollars only, no cents)

or

```<code>//li[starts-with(@id,"result_")]//span[@class="sx-price-whole" and position()=last() and .<20]
</code>```

to get prices that are lower than 20

Title: Test prices on shop findelements?

Body:
I have little problem with my school project.

It's a shop test in Selenium / Java. This is the shopping query: https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=nothing+car&rh=i%3Aaps%2Ck%3Anothing+car

And I tried get all products prices in test.

Is there any other way than this?

String string = findelement(by.xpath("//[@id='result_0']/div/div/div/div[2]/div[2]/div[1]/div[1]/a/span/span"))
System.out.println(string);

After printing that value, I need to check if the value < 20$, and return a failure if so.

Body:
You can try to use

//li[starts-with(@id,"result_")]//span[@class="sx-price-whole" and position()=last()]

to get all the highest prices (dollars only, no cents)

or

//li[starts-with(@id,"result_")]//span[@class="sx-price-whole" and position()=last() and .<20]

to get prices that are lower than 20


问:
To use or not to use SSL? Why use SSL always?
The argument for using SSL is to prevent some malicious user who has gone through the pains of snooping your traffic being able to read your traffic. So while it may make sense if you are using an unsecured wireless (non WPA2) network to use SSL when logging on to your bank account or giving your credit card number, I find it difficult to see it's neccessaity in more common business cases.

Why even bother with SSL?  (when your client is not going to be on an unsecured wireless network)

The only way someone can snoop your particular HTTP connections and data therein is if they have admin access to your router (and then only if there is some facility to monitor/copy traffic), installed some tool on your machine (a key logger of course would by pass SSL anyway) or they monitor you at the ISP (for which a warrant is required in most jurisdictions).

Update Warning Some jurisdictions are not as free as you may think, particularly the 1st and 2nd world, e.g. in the UK, government may soon not require a warrant: http://en.wikipedia.org/wiki/Communications_Data_Bill_2008 which will probably entail the ability to read websites as they were historically (i.e. decrypt SSL) and the US's "Patriot Act" http://en.wikipedia.org/wiki/US_Patriot_Act#Title_II:_Surveillance_procedures

Furthermore:

Accepting SSL connections server side adds significant load as the establishing of a connection is processor intensive (during the generation of secret keys).

Publicly trusted SSL certificates have to be purchased from a 3rd Party periodically

UPDATE: I am actually using SSL, though I thought it worthwhile to ask the question anyway. Certainly I think there are time SSL is not necessary. Maybe this could be turned into a community wiki of the pros and cons of SSL? If so how?

There seems to be commonly occurring myth in the answers below: "anyone between you and the server can eavesdrop on you"...

This is not not possible on the Internet as the low level TCP routers only forward packets where they have to go and even in the same session can be routed through different routes, and no one can look at these packets except in extreme cases - technically or lawfully.

As for someone at the ISP looking at your traffic I wonder why they would signal you out and look at the 'so important data' which no doubt is boring to them, this is also illegal without a warrant.

On your LAN (except wireless) unless you are using a dinosaur Hub which broadcasts every packet there is no way listen on someone else's traffic - this is not possible because the hardware simply does not send the packets to you even if you have your network card in promiscuous mode and are using a sniffing tool such as Snort or Wireshark.

Passive ARP poisoning is one way to  listen in but has to be done internally and should be picked up as name conflicts etc. start occuring and often the default gateway would be static so would be v. difficult cause the default gateway will be on before you.

答:
SSL provides authentication and encryption.

It is somewhat difficult to MITM an unencrypted connection, but not so hard on the unencrypted wireless network you gave as an example. Any network that allows you to ARP spoof (many switched wired networks) allows you to MITM as well. But you're forgetting about every router along the way. Remember a few months back when a (hopefully) poorly configured router in China routed a significant, though small in relative terms, portion of Internet traffic? They could've seen your plaintext. So can other customers on a cable network, and so on.

But SSL also provides authentication. If I get the private key to a valid SSL cert from you, I'm damn confident that you are who you say you are - doubly so if it's a competent CA.

But the bigger concern is - you don't quite seem to understand SSL, so I'd advise you against making a decision one way or the other by yourself - at least until you read more. SSL does not require you to generate a new key every request, and in fact would not work if it did. Furthermore, any reasonably-recent computer can handle thousands of SSL requests simultaneously - the algorithms are very fast. Furthermore you can use encryption accelerators that offload the work to a dedicated piece of hardware.

If you think you might need to use SSL to secure some data, and often if you don't, there are almost no reasons to avoid it. Yes there is some expenditure involved but any data of consequence is worth the $300/yr.

EDIT I read your comment - this is a client app? The solution in your case is probably to use self-signed keys, and you can distribute the public key with the app. This allows you to encrypt and verify that you're talking to who you should be.

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
Alamofire Uploads PNG to Flask with White Background
I am trying to implement a Flask backend endpoint where two images can be uploaded, a background and a foreground (the foreground has a transparent background), and it will paste the foreground on top of the background. I have the following Python code that I have tested with local files and works:

```<code>background_name = request.args.get("background")
overlay_name = request.args.get("overlay")
output_name = request.args.get("output")

background_data = request.files["background"].read()
overlay_data = request.files["overlay"].read()

background = Image.open(BytesIO(background_data))
overlay = Image.open(BytesIO(overlay_data))

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

overlay = resize_image(overlay, background.size)
background.paste(overlay, (0, 0, background.size[0], background.size[1],), overlay)
background.save(output_name, "PNG")
</code>```

However, when I try to upload the same images through Alamofire and the following code:

```<code>Alamofire.upload(multipartFormData: { formData in
        formData.append(bgData, withName: "background", fileName: "background.jpg", mimeType: "image/jpeg")
        formData.append(fgData, withName: "foreground", fileName: "foreground.png", mimeType: "image/png")
    }, to: "http://localhost:8080/image_overlay?background=background%2Ejpg&overlay=overlay%2Epng&output=result%2Epng", encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):
            upload.validate().responseJSON(completionHandler: { response in
                switch response.result {
                case .success(let value): print("success: \(value)")
                case .failure((let error)): print("response error \(error)")
                }
            })
        case .failure(let error):
            print("encoding error \(error)")
        }
    })
</code>```

The foreground appears with a white background instead of a transparent background and the resulting image is just the foreground with a white background. How can I get Alamofire to send the transparency?

EDIT:
I tried translating this to a cURL request and it works as expected. I used nc-l localhost 8080 to view the full request, and it seems that with the foreground picture, even though the Content-Type was set to "application/octet-stream", the next line was "?PNG". This line was no present from the Alamofire request. How can I get the request to recognize the image as a PNG?

答:
I can't believe I was doing this, but when I was obtaining to image data, I was using

```<code>let fgData = UIImageJPEGRepresentation(UIImage(named: "overlay.png"), 0.75)
</code>```

This was the only way I had ever obtained data from an image in Swift, even though obviously it should be what I changed it to:

```<code>let fgData = UIImagePNGRepresentation(UIImage(named: "overlay.png"))
</code>```

Body:
I am trying to implement a Flask backend endpoint where two images can be uploaded, a background and a foreground (the foreground has a transparent background), and it will paste the foreground on top of the background. I have the following Python code that I have tested with local files and works:

background_name = request.args.get("background")
overlay_name = request.args.get("overlay")
output_name = request.args.get("output")

background_data = request.files["background"].read()
overlay_data = request.files["overlay"].read()

background = Image.open(BytesIO(background_data))
overlay = Image.open(BytesIO(overlay_data))

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

overlay = resize_image(overlay, background.size)
background.paste(overlay, (0, 0, background.size[0], background.size[1],), overlay)
background.save(output_name, "PNG")

However, when I try to upload the same images through Alamofire and the following code:

Alamofire.upload(multipartFormData: { formData in
        formData.append(bgData, withName: "background", fileName: "background.jpg", mimeType: "image/jpeg")
        formData.append(fgData, withName: "foreground", fileName: "foreground.png", mimeType: "image/png")
    }, to: "http://localhost:8080/image_overlay?background=background%2Ejpg&overlay=overlay%2Epng&output=result%2Epng", encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):
            upload.validate().responseJSON(completionHandler: { response in
                switch response.result {
                case .success(let value): print("success: \(value)")
                case .failure((let error)): print("response error \(error)")
                }
            })
        case .failure(let error):
            print("encoding error \(error)")
        }
    })

The foreground appears with a white background instead of a transparent background and the resulting image is just the foreground with a white background. How can I get Alamofire to send the transparency?

EDIT:
I tried translating this to a cURL request and it works as expected. I used nc-l localhost 8080 to view the full request, and it seems that with the foreground picture, even though the Content-Type was set to "application/octet-stream", the next line was "?PNG". This line was no present from the Alamofire request. How can I get the request to recognize the image as a PNG?

Body:
I can't believe I was doing this, but when I was obtaining to image data, I was using

let fgData = UIImageJPEGRepresentation(UIImage(named: "overlay.png"), 0.75)

This was the only way I had ever obtained data from an image in Swift, even though obviously it should be what I changed it to:

let fgData = UIImagePNGRepresentation(UIImage(named: "overlay.png"))


问:
juMP - use variable defined in sum range
I am trying to define a constraint containing summation over two indices, k and t.

```<code>for i in data.I
    for j in 1:length(data.P[i])
        @constraint(m, w[i, j, length(data.T[data.P[i][j]])]/(1+sum(data.A[i][k][t] for k in 1:length(data.P[i]), t in data.T[data.P[i][k]])) <= s[i, j])
    end
end
</code>```

I get the following error in running the code:

ERROR: LoadError: UndefVarError: k not defined

I have implemented the same model in OPL for CPLEX in the same way, and this was not an issue. Am I not allowed to introduce such variable as an index in the summation, then use it subsequently as an index to an array within the same sum() as I am trying to do above?

答:
My colleague found a workaround to this issue. Converting the sum into the equivalent double sum made it work, i.e.:

```<code>sum(data.A[i][k][t] for k = 1:length(data.P[i]), t = data.T[data.P[i][k]])
</code>```

was changed to:

```<code>sum(sum(data.A[i][k][t] for t = data.T[data.P[i][k]]) for k = 1:length(data.P[i]))
</code>```

This solves the issue.

Body:
I am trying to define a constraint containing summation over two indices, k and t.

for i in data.I
    for j in 1:length(data.P[i])
        @constraint(m, w[i, j, length(data.T[data.P[i][j]])]/(1+sum(data.A[i][k][t] for k in 1:length(data.P[i]), t in data.T[data.P[i][k]])) <= s[i, j])
    end
end

I get the following error in running the code:

ERROR: LoadError: UndefVarError: k not defined

I have implemented the same model in OPL for CPLEX in the same way, and this was not an issue. Am I not allowed to introduce such variable as an index in the summation, then use it subsequently as an index to an array within the same sum() as I am trying to do above?

Body:
My colleague found a workaround to this issue. Converting the sum into the equivalent double sum made it work, i.e.:

sum(data.A[i][k][t] for k = 1:length(data.P[i]), t = data.T[data.P[i][k]])

was changed to:

sum(sum(data.A[i][k][t] for t = data.T[data.P[i][k]]) for k = 1:length(data.P[i]))

This solves the issue.


问:
Using HTML Divs to Make Navigation Bar
I'm just starting web development, and I'm trying to construct a page-navigation bar with a bunch of 'Div' elements, but I cant seem to get my second button ("AboutButton") to appear on the screen. Here is my HTML body code:

```<code><body>

    <div id="navbar" id="top">
        <div id="pageselection">
            <div id="HomeButton"> <a href="#top"> HOME </a> </div>
            <div id="AboutButton"> <a href="#About> ABOUT </a> </div>
        </div>
    </div>

</body>
</code>```

and here is my CSS for the page:

```<code>#navbar{
Position: fixed;
Width: 100%;
Height: 10%;
}

#pageselection{
Position: absolute;
Width: 40%;
Height: 100%;
Right: 30%;
}

#HomeButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 0%;
text-align: center;
}

#AboutButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 33%;
text-align: center;
}
</code>```

Essentially, I'm trying to build a 'div' that runs across the top of the page, then mark off the central 40% of that 'div' as a space for a second 'div' to sit, which will in turn hold the three links that users can use to navigate the page.

Thanks in advance, hopefully its a stupid error, and I hope my description was clear enough :)

答:
You missed an ending quote " in . I also recommend another approach on your nav bar. Don't absolute position the links in the nav bar, that's not needed. And also, one element can have one ID, not multiple. I've made some changes and used classes instead of IDs below. Please have a look.

#navbar{
  position: fixed;
  width: 100%;
  height: 10%;
  top: 0;
  left: 0;
  background-color: whitesmoke;
  height: 40px;
}

#pageselection{
  position: absolute;
  width: 40%;
  height: 100%;
  right: 30%;
  background-color: gray;
}

.nav-button{
  float:left;
  width:33%;
  height: 100%;
  text-align: center;
  line-height:40px;
}
.nav-button a{
  display:block;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar" id="top">
    <div id="pageselection">
        <div class="nav-button">HOME</div>
        <div class="nav-button">ABOUT</div>
        <div class="nav-button">href="#test">TEST</div>
    </div>
</div></code>```

Title: Using HTML Divs to Make Navigation Bar

Body:
I'm just starting web development, and I'm trying to construct a page-navigation bar with a bunch of 'Div' elements, but I cant seem to get my second button ("AboutButton") to appear on the screen. Here is my HTML body code:

  HOME

  ABOUT

and here is my CSS for the page:

#navbar{
Position: fixed;
Width: 100%;
Height: 10%;
}

#pageselection{
Position: absolute;
Width: 40%;
Height: 100%;
Right: 30%;
}

#HomeButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 0%;
text-align: center;
}

#AboutButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 33%;
text-align: center;
}

Essentially, I'm trying to build a 'div' that runs across the top of the page, then mark off the central 40% of that 'div' as a space for a second 'div' to sit, which will in turn hold the three links that users can use to navigate the page.

Thanks in advance, hopefully its a stupid error, and I hope my description was clear enough :)

Body:
You missed an ending quote " in <a href="#About>. I also recommend another approach on your nav bar. Don't absolute position the links in the nav bar, that's not needed. And also, one element can have one ID, not multiple. I've made some changes and used classes instead of IDs below. Please have a look.

#navbar{
  position: fixed;
  width: 100%;
  height: 10%;
  top: 0;
  left: 0;
  background-color: whitesmoke;
  height: 40px;
}

#pageselection{
  position: absolute;
  width: 40%;
  height: 100%;
  right: 30%;
  background-color: gray;
}

.nav-button{
  float:left;
  width:33%;
  height: 100%;
  text-align: center;
  line-height:40px;
}
.nav-button a{
  display:block;
  height: 100%;
}

<div id="navbar" id="top">
    <div id="pageselection">
        <div class="nav-button"><a href="#top">HOME</a></div>
        <div class="nav-button"><a href="#about">ABOUT</a></div>
        <div class="nav-button"><a href="#test">TEST</a></div>
    </div>
</div>


问:
Laravel Utilize ValidationException
I am using...

```<code>$validator  = Validator::make(...)
</code>```

...to validate my input. However, instead of using that method, for API purposes, I would like to make use of Laravel's Validation Exception class.

Currently, I am trying:

```<code>// Model (Not Eloquent Model)
Validator::make(...)

// Controller
try { $model->createUser(Request $request); }
catch(ValidationException $ex)
{
    return response()->json(['errors'=>$ex->errors()], 422);
}
</code>```

However, the validation in the model does not appear to throw any validation exceptions. I can still get the errors by using $validator->errors(). Yet, that is still defeating my purpose.

I am trying to keep really clean controllers with only try and catch statements; therefore, keeping any and all logic and out of controllers.

How can I utilize the ValidationException to do just that?

答:
I do not know what happens in your $model->createUser(Request $request);, but if you use the Validator facade then you'd have to process the validation yourself as in:

```<code>use Validator;

...

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    // With a "Accept: application/json" header, this will format the errors
    // for you as the JSON response you have right now in your catch statement
    $this->throwValidationException($request, $validator);
}
</code>```

On the other hand you might want to use the validate() method in your controller as it does all of the above for you:

```<code>$this->validate($request, $rules);
</code>```

Title: Laravel Utilize ValidationException

Body:
I am using...

$validator  = Validator::make(...)

...to validate my input. However, instead of using that method, for API purposes, I would like to make use of Laravel's Validation Exception class.

Currently, I am trying:

// Model (Not Eloquent Model)
Validator::make(...)

// Controller
try { $model->createUser(Request $request); }
catch(ValidationException $ex)
{
    return response()->json(['errors'=>$ex->errors()], 422);
}

However, the validation in the model does not appear to throw any validation exceptions. I can still get the errors by using $validator->errors(). Yet, that is still defeating my purpose.

I am trying to keep really clean controllers with only try and catch statements; therefore, keeping any and all logic and out of controllers.

How can I utilize the ValidationException to do just that?

Body:
I do not know what happens in your $model->createUser(Request $request);, but if you use the Validator facade then you'd have to process the validation yourself as in:

use Validator;

...

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    // With a "Accept: application/json" header, this will format the errors
    // for you as the JSON response you have right now in your catch statement
    $this->throwValidationException($request, $validator);
}

On the other hand you might want to use the validate() method in your controller as it does all of the above for you:

$this->validate($request, $rules);


问:
Need help to change postgresql port on CentOS 7
I just installed the postgresql (as it says on postgresql), server is running like  charm, no problem at all.

I just tried(want) to change the default port (5432) to (9898).

First I just tried to do it by postgresql.conf file under /var/lib/pgsql/data/postgresql.conf.

I just remove the comment for port related line, and change it as port=9898, but there is a comment saying overriding port here doesn't change anything for RHEL and deriven guys, it also says try to override the port config by service config file(cannot find it, where is it?).

I also change the postmaster.opts too (doesn't work the same).

Finally! how may I change the Postgresql 9.2.7 port number on CentOS 7?

答:
I am using Amazon EC2 instance with Amazon Linux AMI release ( A kind of CentOS it seems). I needed to change PGPORT variable in /etc/init.d/postgresql file and restart the postgresql service using 'service postgresql restart'. And it works!!</p>

```<code>PGPORT=some_new_port # /etc/init.d/postgresql
</code>```

Body:
I am using Amazon EC2 instance with Amazon Linux AMI release ( A kind of CentOS it seems). I needed to change PGPORT variable in /etc/init.d/postgresql file and restart the postgresql service using 'service postgresql restart'. And it works!!

PGPORT=some_new_port # /etc/init.d/postgresql


问:
How to create a 3d point with 2 same way textured sides?
So I create a points cloud using no 3d engines but one baked into flash:

```<code>import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(400,400,true,0x00000000);

var xn:Number;
var yn:Number;
var zn:Number;
var norm:Number;
var c1:Number;
var c2:Number;
var c3:Number;
var c4:Number;
var counter:int;
var color:uint;
while (counter < 20000)
{
    xn = Math.random() * 400;
    yn = Math.random() * 400;
    zn = Math.random() * 400;
    norm = Math.sqrt(xn * xn + yn * yn + zn * zn);
    c1 = (1 - norm / 200) * 255;
    c2 = (1 - norm / 250) * 255;
    c3 = Math.abs(xn) / norm * 255;
    c4 = Math.abs(yn) / norm * 255;
    color =  (c1 << 24 | c2 << 16 | c3 << 8 | c4);
    counter++;

    var pointGraphicData = new BitmapData(1,1,true,color);
    var pointGraphic:Bitmap = new Bitmap(pointGraphicData);

    pointGraphic.x = xn;
    pointGraphic.y = yn;
    pointGraphic.z = zn;
    addChild(pointGraphic);
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove );
this.x = 150;
this.y = 150;
this.z = 450;
function handleMouseMove( event:MouseEvent ):void
{
    this.rotationX = 0 - event.localX;
    this.rotationY = 0 - event.localY;
    this.rotationZ = 0 - Math.sqrt((event.localX * event.localX + event.localY * event.localY ));
}
</code>```

so its a wary simple code. how to make my points have 2 sides or be always face to wiever?

答:
There's a javascript example of how to create a spiral on a sphere surface at this link:

http://lines-about-to-be-generated.blogspot.com/2009/06/image-spiral-sphere.html

Body:
So I create a points cloud using no 3d engines but one baked into flash:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(400,400,true,0x00000000);

var xn:Number;
var yn:Number;
var zn:Number;
var norm:Number;
var c1:Number;
var c2:Number;
var c3:Number;
var c4:Number;
var counter:int;
var color:uint;
while (counter < 20000)
{
    xn = Math.random() * 400;
    yn = Math.random() * 400;
    zn = Math.random() * 400;
    norm = Math.sqrt(xn * xn + yn * yn + zn * zn);
    c1 = (1 - norm / 200) * 255;
    c2 = (1 - norm / 250) * 255;
    c3 = Math.abs(xn) / norm * 255;
    c4 = Math.abs(yn) / norm * 255;
    color =  (c1 << 24 | c2 << 16 | c3 << 8 | c4);
    counter++;

    var pointGraphicData = new BitmapData(1,1,true,color);
    var pointGraphic:Bitmap = new Bitmap(pointGraphicData);

    pointGraphic.x = xn;
    pointGraphic.y = yn;
    pointGraphic.z = zn;
    addChild(pointGraphic);
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove );
this.x = 150;
this.y = 150;
this.z = 450;
function handleMouseMove( event:MouseEvent ):void
{
    this.rotationX = 0 - event.localX;
    this.rotationY = 0 - event.localY;
    this.rotationZ = 0 - Math.sqrt((event.localX * event.localX + event.localY * event.localY ));
}

so its a wary simple code. how to make my points have 2 sides or be always face to wiever?


问:
How do I update records in sql using other records as values?
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2
</code>```

After:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2
</code>```

Self-taught, relatively new to SQL.  Patience is appreciated.

答:
Another way to do it:

```<code>UPDATE  t1
SET     t1.ColumnX = t2.ColumnX
FROM    @table t1
        INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
                                AND t1.ColumnA = t2.ColumnA
                                AND t1.ColumnY <> t2.ColumnY
                                AND t1.TxID > t2.TxID -- the lowest TxID keeps its original value
</code>```

Or...

```<code>UPDATE  t1
SET     t1.ColumnX = t2.ColumnX
FROM    @table t1
        INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
                                AND t1.ColumnA = t2.ColumnA
                                AND t1.ColumnY <> t2.ColumnY
                                AND t1.TxID < t2.TxID -- the largest TxId keeps its original value
</code>```

Body:
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2

After:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2

Self-taught, relatively new to SQL.  Patience is appreciated.

Body:
Another way to do it:

UPDATE  t1
SET     t1.ColumnX = t2.ColumnX
FROM    @table t1
        INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
                                AND t1.ColumnA = t2.ColumnA
                                AND t1.ColumnY <> t2.ColumnY
                                AND t1.TxID > t2.TxID -- the lowest TxID keeps its original value

Or...

UPDATE  t1
SET     t1.ColumnX = t2.ColumnX
FROM    @table t1
        INNER JOIN @table t2 ON t1.RecordID = t2.RecordID
                                AND t1.ColumnA = t2.ColumnA
                                AND t1.ColumnY <> t2.ColumnY
                                AND t1.TxID < t2.TxID -- the largest TxId keeps its original value


问:
How can I do custom JWT validation with Flask and flask_jwt_extended?
I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?

Currently my code just calls:

```<code>jwt = JWTManager(app)
</code>```

And I decorate the functions with: @jwt_required

答:
Off the top of my head, my inclination would be to create a custom decorator that wraps jwt_required.

Here's a rough idea of how it might look, via the functools.wraps documentation:

```<code>from functools import wraps
from flask_jwt_extended import jwt_required
from flask_jwt_extended.view_decorators import _decode_jwt_from_request
from flask_jwt_extended.exceptions import NoAuthorizationError

def custom_validator(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        jwt_data = _decode_jwt_from_request(request_type='access')

        # Do your custom validation here.
        if (...):
            authorized = True
        else:
            authorized = False

        if not authorized:
            raise NoAuthorizationError("Explanation goes here")

        return view_function(*args, **kwargs)

    return jwt_required(wrapper)

@app.route('/')
@custom_validator
def index():
    return render_template('index.html')
</code>```

Here is where you can find the source code for jwt_required.

Body:
I want to add additional verification to the token when @jwt_required is called. I want to verify one of the claims. Is there away I can do this with JWTManager?

Currently my code just calls:

jwt = JWTManager(app)

And I decorate the functions with: @jwt_required

Body:
Off the top of my head, my inclination would be to create a custom decorator that wraps jwt_required.

Here's a rough idea of how it might look, via the functools.wraps documentation:

from functools import wraps
from flask_jwt_extended import jwt_required
from flask_jwt_extended.view_decorators import _decode_jwt_from_request
from flask_jwt_extended.exceptions import NoAuthorizationError

def custom_validator(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        jwt_data = _decode_jwt_from_request(request_type='access')

        # Do your custom validation here.
        if (...):
            authorized = True
        else:
            authorized = False

        if not authorized:
            raise NoAuthorizationError("Explanation goes here")

        return view_function(*args, **kwargs)

    return jwt_required(wrapper)

@app.route('/')
@custom_validator
def index():
    return render_template('index.html')

Here is where you can find the source code for jwt_required.

ContentLicense: CC BY-SA 4.0


问:
replace '\r\n' with '
' in Text area javascript?
when I press Enter I want to insert "
" instead of the new line '\n\r'in my text area,
Exemple:

i want the text in the text area  to be:

```<code>"hello <br> dear",
</code>```

instead of

```<code>"hello
dear"
</code>```

I tried this code but with no luck:

```<code>$('#inputText').bind('keyup', function(e) {
   var data = $('#inputText').val();
   $('#inputText').text(data.replace(/\n/g, "<br />"));
}
</code>```

答:
Your code will work fine if:-

1.bind() converted to on()(because bind() is deprecated)

2.text()  need to be .val()

Working example (check comments too):-

// applied mouseout to prevent repetition on each key-press

//you can apply keyup also no problem

$('#inputText').on('mouseout', function(e) {
  var data = $('#inputText').val();
  $('#inputText').val(data.replace(/\n/g, "
")); // text() need be val()
}); // here ); missing in your given code```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="inputText"></textarea></code>```

Title: replace '\r\n' with '< br>' in Text area javascript?

Body:
when I press Enter I want to insert "
" instead of the new line '\n\r'in my text area,
Exemple:

i want the text in the text area  to be:

"hello
 dear",

instead of

"hello
dear"

I tried this code but with no luck:

$('#inputText').bind('keyup', function(e) {
   var data = $('#inputText').val();
   $('#inputText').text(data.replace(/\n/g, "
"));
}

Body:
Your code will work fine if:-

1.bind() converted to on()(because bind() is deprecated)

2.text()  need to be .val()

Working example (check comments too):-

// applied mouseout to prevent repetition on each key-press

//you can apply keyup also no problem

$('#inputText').on('mouseout', function(e) {
  var data = $('#inputText').val();
  $('#inputText').val(data.replace(/\n/g, "<br />")); // text() need be val()
}); // here ); missing in your given code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="inputText"></textarea>