问:
Internal ruby error in vim
I've been having this problem for a while with vim. The first time I do anything that interacts with ruby, such as :ruby puts "test", I get <internal:gem_prelude>:1:in 'require': cannot load such file -- rubygems.rb (LoadError).

Some diagnostic information that may be useful : my OS is OS X 10.11.2, Vim is version 7.4, ruby is 2.1.2 installed with rvm, my shell is zsh (but this also happens with bash), and my vim is completely vanilla.

```<code> $  ruby --version
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
 $  rvm list

rvm rubies

=* ruby-2.1.2 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

 $  which -a ruby
/Users/marcusbuffett/.rvm/rubies/ruby-2.1.2/bin/ruby
/usr/local/bin/ruby
/usr/local/bin/ruby
/usr/bin/ruby
 $  vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Mar 18 2016 09:07:16)
MacOS X (unix) version
Included patches: 1-1401
Compiled by Homebrew
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +syntax
+arabic          +file_in_path    +mouse_sgr       +tag_binary
+autocmd         +find_in_path    -mouse_sysmouse  +tag_old_static
-balloon_eval    +float           +mouse_urxvt     -tag_any_white
-browse          +folding         +mouse_xterm     -tcl
++builtin_terms  -footer          +multi_byte      +terminfo
+byte_offset     +fork()          +multi_lang      +termresponse
+channel         -gettext         -mzscheme        +textobjects
+cindent         -hangul_input    +netbeans_intg   +title
-clientserver    +iconv           +packages        -toolbar
+clipboard       +insert_expand   +path_extra      +user_commands
+cmdline_compl   +job             +perl            +vertsplit
+cmdline_hist    +jumplist        +persistent_undo +virtualedit
+cmdline_info    +keymap          +postscript      +visual
+comments        +langmap         +printer         +visualextra
+conceal         +libcall         +profile         +viminfo
+cryptv          +linebreak       +python          +vreplace
+cscope          +lispindent      -python3         +wildignore
+cursorbind      +listcmds        +quickfix        +wildmenu
+cursorshape     +localmap        +reltime         +windows
+dialog_con      -lua             +rightleft       +writebackup
+diff            +menu            +ruby            -X11
+digraphs        +mksession       +scrollbind      -xfontset
-dnd             +modify_fname    +signs           -xim
-ebcdic          +mouse           +smartindent     -xsmp
+emacs_tags      -mouseshape      -sniff           -xterm_clipboard
+eval            +mouse_dec       +startuptime     -xterm_save
+ex_extra        -mouse_gpm       +statusline      -xpm
+extra_search    -mouse_jsbterm   -sun_workshop
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/local/share/vim"
Compilation: /usr/bin/clang -c -I. -Iproto -DHAVE_CONFIG_H   -F/usr/local/Frameworks -DMACOS_X_UNIX  -Os -w -pipe -march=native -mmacosx-version-min=10.11 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: /usr/bin/clang   -L. -L/Users/travis/.sm/pkg/active/lib -fPIC -Bstatic -fstack-protector -L/usr/local/lib -F/usr/local/Frameworks -Wl,-headerpad_max_install_names -o vim        -lm  -lncurses -liconv -framework Cocoa   -fstack-protector  -L/System/Library/Perl/5.18/darwin-thread-multi-2level/CORE -lperl -framework Python   -lruby-static -framework CoreFoundation -lobjc -L/Users/marcusbuffett/.rvm/rubies/ruby-2.1.2/lib
</code>```

答:
You could just run ruby like any other command with :!ruby -e "puts 'Hello'", or -- to run the current file -- :!ruby %:p.

Caveat: This will, by itself, toggle back to your shell until you press a key to go back to vim, as opposed to executing the code in the command window like :ruby does. I consider it worth the tradeoff, considering that it is significantly more versatile. See below for a workaround.

The last one can be particularly useful when paired with:

```<code>if __FILE__ == $0
  run_some_command || assert_something || run_only_this_test_file
end
</code>```

You can, for example, add an autocmd on buffer write to specific file names (e.g. *_test.rb) that automatically runs a test on save, if that sort of thing interests you.

Alternative to Screen Flickering on Shell Command

If the flickering annoys you, you can also store the result into a variable, spawn a new buffer and put the result in it with :let res=system('ruby '.expand('%:p')) | new | put=res

Title: Internal ruby error in vim

Body:
I've been having this problem for a while with vim. The first time I do anything that interacts with ruby, such as :ruby puts "test", I get <internal:gem_prelude>:1:in 'require': cannot load such file -- rubygems.rb (LoadError).

Some diagnostic information that may be useful : my OS is OS X 10.11.2, Vim is version 7.4, ruby is 2.1.2 installed with rvm, my shell is zsh (but this also happens with bash), and my vim is completely vanilla.

 $  ruby --version
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
 $  rvm list

rvm rubies

=* ruby-2.1.2 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

 $  which -a ruby
/Users/marcusbuffett/.rvm/rubies/ruby-2.1.2/bin/ruby
/usr/local/bin/ruby
/usr/local/bin/ruby
/usr/bin/ruby
 $  vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Mar 18 2016 09:07:16)
MacOS X (unix) version
Included patches: 1-1401
Compiled by Homebrew
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +syntax
+arabic          +file_in_path    +mouse_sgr       +tag_binary
+autocmd         +find_in_path    -mouse_sysmouse  +tag_old_static
-balloon_eval    +float           +mouse_urxvt     -tag_any_white
-browse          +folding         +mouse_xterm     -tcl
++builtin_terms  -footer          +multi_byte      +terminfo
+byte_offset     +fork()          +multi_lang      +termresponse
+channel         -gettext         -mzscheme        +textobjects
+cindent         -hangul_input    +netbeans_intg   +title
-clientserver    +iconv           +packages        -toolbar
+clipboard       +insert_expand   +path_extra      +user_commands
+cmdline_compl   +job             +perl            +vertsplit
+cmdline_hist    +jumplist        +persistent_undo +virtualedit
+cmdline_info    +keymap          +postscript      +visual
+comments        +langmap         +printer         +visualextra
+conceal         +libcall         +profile         +viminfo
+cryptv          +linebreak       +python          +vreplace
+cscope          +lispindent      -python3         +wildignore
+cursorbind      +listcmds        +quickfix        +wildmenu
+cursorshape     +localmap        +reltime         +windows
+dialog_con      -lua             +rightleft       +writebackup
+diff            +menu            +ruby            -X11
+digraphs        +mksession       +scrollbind      -xfontset
-dnd             +modify_fname    +signs           -xim
-ebcdic          +mouse           +smartindent     -xsmp
+emacs_tags      -mouseshape      -sniff           -xterm_clipboard
+eval            +mouse_dec       +startuptime     -xterm_save
+ex_extra        -mouse_gpm       +statusline      -xpm
+extra_search    -mouse_jsbterm   -sun_workshop
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/local/share/vim"
Compilation: /usr/bin/clang -c -I. -Iproto -DHAVE_CONFIG_H   -F/usr/local/Frameworks -DMACOS_X_UNIX  -Os -w -pipe -march=native -mmacosx-version-min=10.11 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: /usr/bin/clang   -L. -L/Users/travis/.sm/pkg/active/lib -fPIC -Bstatic -fstack-protector -L/usr/local/lib -F/usr/local/Frameworks -Wl,-headerpad_max_install_names -o vim        -lm  -lncurses -liconv -framework Cocoa   -fstack-protector  -L/System/Library/Perl/5.18/darwin-thread-multi-2level/CORE -lperl -framework Python   -lruby-static -framework CoreFoundation -lobjc -L/Users/marcusbuffett/.rvm/rubies/ruby-2.1.2/lib

Body:
You could just run ruby like any other command with :!ruby -e "puts 'Hello'", or -- to run the current file -- :!ruby %:p.

Caveat: This will, by itself, toggle back to your shell until you press a key to go back to vim, as opposed to executing the code in the command window like :ruby does. I consider it worth the tradeoff, considering that it is significantly more versatile. See below for a workaround.

The last one can be particularly useful when paired with:

if __FILE__ == $0
  run_some_command || assert_something || run_only_this_test_file
end

You can, for example, add an autocmd on buffer write to specific file names (e.g. *_test.rb) that automatically runs a test on save, if that sort of thing interests you.

Alternative to Screen Flickering on Shell Command

If the flickering annoys you, you can also store the result into a variable, spawn a new buffer and put the result in it with :let res=system('ruby '.expand('%:p')) | new | put=res


来源: stackexchange

问:
How to add a custom polyfill to an angular-cli project?
I need the ability to easily sort collections and I've chosen to extend the Array primitive. I realize this is considered bad practice in most cases, but this will be used only internally (not a shared lib). No matter what approach I've tried I'm not getting a working result even though it works as expected in the playground.

I've tried adding the polyfill inline in /src/polyfills.ts but that gives me a "TypeError: Attempted to assign to readonly property" in the console when I call the $sortBy method...

declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey]  b[sortKey]) { return 1; }
        return 0;
      });
    }
  })

}
```

<p>I've also tried adding a plain javascript version via npm and importing but that gives me the same type error. What's the secret???</p>

<p><em>/node_modules/my-polyfills/sortBy.js</em></p>

<pre class="lang-js prettyprint-override"><code>if (!Array.prototype.$sortBy) {
  Object.defineProperties(Array.prototype, {
    '$sortBy': {
      value: function (sortKey) {
        return this.sort(function (a, b) {
          if (a[sortKey] < b[sortKey]) {
            return -1;
          }
          if (a[sortKey] > b[sortKey]) {
            return 1;
          }
          return 0;
        });
      }
    }
  });
}
</code>```

.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": { ... },
  "apps": [
    {
      ...,
      "scripts": [
        "../node_modules/my-polyfills/sortBy.js",
        "../node_modules/moment/moment.js"
      ],
      ...
    }
  ],
  ...
}
```

答:
I have an generated app on angular cli 1.0.0. While I think your issue has nothing to do with the version, I have taken your code below and appended it to src/polyfills.ts it works as expected:

```<code>declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey] < b[sortKey]) { return -1; }
        if (a[sortKey] > b[sortKey]) { return 1; }
        return 0;
      });
    }
  })
}
</code>```

in one of my components I added:

```<code>var a = [1,2,3];
var b = a.$sortBy('');
console.log(b)
</code>```

I did not see the error in the console and array a was printed just fine.

I think the issue you are having is because you have the code above in your src/polyfills.ts AND you have included the same polyfill in /node_modules/my-polyfills/sortBy.js and added that to scripts section of your .angular-cli

You should add either or, not both. I recommend the former, but in it's own file and not appended to polyfills.ts

this error TypeError: Attempted to assign to readonly property happens when you try to assign a non-writable property to something else. By using Object.defineProperty you are making $sortBy non-writable. You defined Arrays.prototype.$sortBy THEN you try to modify that $sortBy by assigning it to a new function, hence you get the error.

ContentLicense: CC BY-SA 3.0

Body:
I need the ability to easily sort collections and I've chosen to extend the Array primitive. I realize this is considered bad practice in most cases, but this will be used only internally (not a shared lib). No matter what approach I've tried I'm not getting a working result even though it works as expected <a href="http://www.typescriptlang.org/play/index.html#src=interface%20Array%3CT%3E%20%7B%0D%0A%20%20%20%20%24sortBy(sortKey%3A%20string)%3A%20T%5B%5D%3B%0D%0A%20%20%20%20%24sortKey%3A%20string%3B%0D%0A%20%20%20%20%24reversed%3A%20boolean%3B%0D%0A%7D%0D%0A%0D%0Aif%20(!Array.prototype.%24sortBy)%20%7B%0D%0A%0D%0A%20%20%20%20Object.defineProperties(Array.prototype%2C%20%7B%0D%0A%20%20%20%20%20%20%20%20'%24sortBy'%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20value%3A%20function%20(sortKey)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(sortKey%20%3D%3D%3D%20this.%24sortKey)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20this.reverse()%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20this.%24reversed%20%3D%20true%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%20else%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20this.%24reversed%20%3D%20false%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20this.%24sortKey%20%3D%20sortKey%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20this.sort(function%20(a%2C%20b)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20this%20will%20be%20replaced%20by%20a%20more%20complex%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20alphanumeric%2Fnatural%20sort%20method%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(a%5BsortKey%5D%20%3C%20b%5BsortKey%5D)%20%7B%20return%20-1%3B%20%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(a%5BsortKey%5D%20%3E%20b%5BsortKey%5D)%20%7B%20return%201%3B%20%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%200%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%20%20'%24sortKey'%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20writable%3A%20true%2C%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20value%3A%20null%0D%0A%20%20%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%20%20'%24reversed'%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20writable%3A%20true%2C%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20value%3A%20false%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%7D)%3B%0D%0A%0D%0A%7D%0D%0A%0D%0Alet%20people%20%3D%20%5B%0D%0A%20%20%20%20%7Bname%3A%20'dick'%7D%2C%0D%0A%20%20%20%20%7Bname%3A%20'alice'%7D%2C%0D%0A%20%20%20%20%7Bname%3A%20'zed'%7D%2C%0D%0A%20%20%20%20%7Bname%3A%20'barry'%7D%0D%0A%5D%0D%0A%0D%0A%2F%2F%20original%0D%0Aconsole.log(%60Original%3A%20%24%7BJSON.stringify(people)%7D%60)%3B%0D%0A%0D%0A%2F%2F%20sorted%0D%0Alet%20people1%20%3D%20people.slice().%24sortBy('name')%0D%0Aconsole.log(%60Sorted%3A%20%24%7BJSON.stringify(people1)%7D%60)%3B%0D%0A%0D%0A%2F%2F%20reversed%0D%0Alet%20people2%20%3D%20people.slice().%24sortBy('name')%3B%0D%0Apeople2.%24sortBy('name')%3B%0D%0Aconsole.log(%60Reversed%3A%20%24%7BJSON.stringify(people2)%7D%60)%3B%0D%0A" rel="nofollow noreferrer">in the playground.

I've tried adding the polyfill inline in /src/polyfills.ts but that gives me a "TypeError: Attempted to assign to readonly property" in the console when I call the $sortBy method...

declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey]  b[sortKey]) { return 1; }
        return 0;
      });
    }
  })

}

I've also tried adding a plain javascript version via npm and importing but that gives me the same type error. What's the secret???

/node_modules/my-polyfills/sortBy.js

if (!Array.prototype.$sortBy) {
  Object.defineProperties(Array.prototype, {
    '$sortBy': {
      value: function (sortKey) {
        return this.sort(function (a, b) {
          if (a[sortKey]  b[sortKey]) {
            return 1;
          }
          return 0;
        });
      }
    }
  });
}

.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": { ... },
  "apps": [
    {
      ...,
      "scripts": [
        "../node_modules/my-polyfills/sortBy.js",
        "../node_modules/moment/moment.js"
      ],
      ...
    }
  ],
  ...
}

Body:
I have an generated app on angular cli 1.0.0. While I think your issue has nothing to do with the version, I have taken your code below and appended it to src/polyfills.ts it works as expected:

declare global {
  interface Array<T> {
    $sortBy(sortKey:string): T[];
  }
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey] < b[sortKey]) { return -1; }
        if (a[sortKey] > b[sortKey]) { return 1; }
        return 0;
      });
    }
  })
}

in one of my components I added:

var a = [1,2,3];
var b = a.$sortBy('');
console.log(b)

I did not see the error in the console and array a was printed just fine.

I think the issue you are having is because you have the code above in your src/polyfills.ts AND you have included the same polyfill in /node_modules/my-polyfills/sortBy.js and added that to scripts section of your .angular-cli

You should add either or, not both. I recommend the former, but in it's own file and not appended to polyfills.ts

this error TypeError: Attempted to assign to readonly property happens when you try to assign a non-writable property to something else. By using Object.defineProperty you are making $sortBy non-writable. You defined Arrays.prototype.$sortBy THEN you try to modify that $sortBy by assigning it to a new function, hence you get the error.


问:
Remove '.0' from double, but keep every other possibility
I've seen a bunch of questions here on Stackoverflow referring to hiding the .0 after a double, but every single answer says to use DecimalFormat and do #.# to hide it. Except this is not what I want.

For every single possibility where the double does NOT end in simply .0, I want them to be how they are. Except when it DOES end in .0, remove it. In other words, I want to keep my precision at all times, unless it ends with a .0.

Examples:

```<code>0.0000000000000000042345470000230 -> 0.0000000000000000042345470000230
0.4395083451 -> 0.4395083451
46547453.00024235 -> 46547453.00024235

435.0 -> 435
</code>```

Is there a way I can achieve this?

Further example:

This question here has the type of answer I am talking about:

Use DecimalFormat

```<code>double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
</code>```

The ###.# above means that I am going to have the first 3 digits appear, a period, and then the first number after it. Regardless of my value, only the first fractional number will be formatted.

答:
Well actually it's not complicated at all. Just check this (It even gives you the most precise number):

```<code>//Square root of 5 will give you a lot of decimals
BigDecimal d1 = new BigDecimal(sqrt(5));
//5 will give you none
BigDecimal d2 = new BigDecimal(5);
//Print and enjoy
System.out.println(d1.stripTrailingZeros());
System.out.println(d2.stripTrailingZeros());
</code>```

The stripTrailingZeros() will remove any trail of plain 0's, but keep the formatting if other numbers are present.

Body:
I've seen a bunch of questions here on Stackoverflow referring to hiding the .0 after a double, but every single answer says to use DecimalFormat and do #.# to hide it. Except this is not what I want.

For every single possibility where the double does NOT end in simply .0, I want them to be how they are. Except when it DOES end in .0, remove it. In other words, I want to keep my precision at all times, unless it ends with a .0.

Examples:

0.0000000000000000042345470000230 -> 0.0000000000000000042345470000230
0.4395083451 -> 0.4395083451
46547453.00024235 -> 46547453.00024235

435.0 -> 435

Is there a way I can achieve this?

Further example:

This question here has the type of answer I am talking about:

Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));

The ###.# above means that I am going to have the first 3 digits appear, a period, and then the first number after it. Regardless of my value, only the first fractional number will be formatted.

Body:
Well actually it's not complicated at all. Just check this (It even gives you the most precise number):

//Square root of 5 will give you a lot of decimals
BigDecimal d1 = new BigDecimal(sqrt(5));
//5 will give you none
BigDecimal d2 = new BigDecimal(5);
//Print and enjoy
System.out.println(d1.stripTrailingZeros());
System.out.println(d2.stripTrailingZeros());

The stripTrailingZeros() will remove any trail of plain 0's, but keep the formatting if other numbers are present.


问:
How does `tf.image.decode_image` deal with channels in Tensorflow?
Does the channels in tf.image.decode_image must equal to the real channel of images? What would happen if the real channel is greater or less than the channels in tf.image.decode_image?
If they must be equal, how should I deal with the situation that my image set contains images with different channels?

答:
The channels do not need to be equal but the values are limited to 0, 1, and 3.

0 defaults to the original number of channels in the image.

1 outputs the images as greyscale.

3 outputs the images as RGB.

Update 5-30-2020:

Tensorflow 2.0 decode_image also handles 4 color channel images.

ContentLicense: CC BY-SA 4.0


问:
Session 'app': Error Installing APK
Trying to install app on real device following instructions:- http://developer.android.com/tools/device.html. At end Android Studio giving error:

```<code>Session 'app': Error Installing APK
</code>```

I guess the problem probably can be in my android device(it is chinese Doogee X5). It does not have a given USB Vendor ID in developer docs so I decided to follow instructions with random vendor ID from HTC.

I'm sure there is a way to run application on any android device, but yet I didn't find an answer on how to do that.

I'm running through Linux Ubuntu 14.04 LTS

答: just press Build button from menu bar and then press build app wait for it finished then press build APK and then run your emulator, it will work</p>

Title: Session 'app': Error Installing APK

Body:
Trying to install app on real device following instructions:- http://developer.android.com/tools/device.html. At end Android Studio giving error:

Session 'app': Error Installing APK

I guess the problem probably can be in my android device(it is chinese Doogee X5). It does not have a given USB Vendor ID in developer docs so I decided to follow instructions with random vendor ID from HTC.

I'm sure there is a way to run application on any android device, but yet I didn't find an answer on how to do that.

I'm running through Linux Ubuntu 14.04 LTS


问:
is there a way of showing MKMapView from an angle (not directly from the top) on a specific zoom level?
In swift I'm using MapKit.

I set up the outlet @IBOutlet weak var mapView: MKMapView!, used the MKMapViewDelegate, and then I'm adding some annotations.

I was wondering if there's a possibility to show my map tilted and disable changing it until user zooms out the map. So basically when he zooms in - from the specific zoom level up to the closest zoom - he would only see this:

instead of this:

and changing this option by scrolling with two fingers should be locked.
When user zooms out to some specific zoom level (e.g. country-wise), then it could switch to non-3d map. Is that achievable?

答:
try this</p>

```<code>            camera.pitch = 85.0
            camera.altitude = 223.0
            camera.heading = 31.2

            self.mapView.isPitchEnabled = true;
            self.mapView.showsBuildings = true;
</code>```

Body:
try this

            camera.pitch = 85.0
            camera.altitude = 223.0
            camera.heading = 31.2

            self.mapView.isPitchEnabled = true;
            self.mapView.showsBuildings = true;


问:
How to avoid duplicate database connection in java?
I have 2 classes. C_DB and C_Test.

In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.

Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.

C_DB

```<code>public class C_DB {
    Connection con;

    public C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public Connection getConnection() {
        return con;
    }
}
</code>```

C_Test

```<code>public class C_Test {

    public static void main(String[] args) throws Exception {
        Connection con1 = new C_DB().getConnection(); // new connection
        Connection con2 = new C_DB().getConnection(); // new duplicate connection
        Connection con3 = new C_DB().getConnection(); // new duplicate connection
    }

}
</code>```

答:
You should use Singleton design pattern to avoid multiple instances.

something like this :

```<code>public class C_DB {

    private static final Connection con;
    private static final C_DB singleInstance;

    private C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public static C_DB getInstance() {
        if (singleInstance == null) {
            synchronized (C_DB.class) {
                if (singleInstance == null) {
                    singleInstance = new C_DB();
                }
            }
        }

        return singleInstance;
    }

    public Connection getConnection() {
        return con;
    }
}
</code>```

And get the connection as :

```<code>Connection con = C_DB.getInstance().getConnection();
</code>```

Body:
I have 2 classes. C_DB and C_Test.

In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.

Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.

C_DB

public class C_DB {
    Connection con;

    public C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public Connection getConnection() {
        return con;
    }
}

C_Test

public class C_Test {

    public static void main(String[] args) throws Exception {
        Connection con1 = new C_DB().getConnection(); // new connection
        Connection con2 = new C_DB().getConnection(); // new duplicate connection
        Connection con3 = new C_DB().getConnection(); // new duplicate connection
    }

}

Body:
You should use Singleton design pattern to avoid multiple instances.

something like this :

public class C_DB {

    private static final Connection con;
    private static final C_DB singleInstance;

    private C_DB() {
        String dbLink = "jdbc:mysql://localhost:3306/database";
        String dbUser = "root";
        String dbPass = "";

        try {
            con = DriverManager.getConnection(dbLink, dbUser, dbPass);
        } catch (SQLException e) {
            throw new IllegalStateException("DB Errors: ", e);
        }
    }

    public static C_DB getInstance() {
        if (singleInstance == null) {
            synchronized (C_DB.class) {
                if (singleInstance == null) {
                    singleInstance = new C_DB();
                }
            }
        }

        return singleInstance;
    }

    public Connection getConnection() {
        return con;
    }
}

And get the connection as :

Connection con = C_DB.getInstance().getConnection();


问:
Array size in Java
What would be the memory size/space occupied in bits/bytes by array as follows.</p>

```<code>final String[] objects_user1={"1","10","100","1000","10000"};
</code>```

答: ROUGH ESTIMATE: 12 bytes for array header, 4x5 bytes for the pointers (8x5 if you're on a 64 bit jvm), each string has 3 ints (+3x4 bytes), and an array of chars (+12 bytes for header + length of the string x2, because it's char).</p>

ContentLicense: CC BY-SA 2.5

Title: Array size in Java

Body:
What would be the memory size/space occupied in bits/bytes by array as follows.

final String[] objects_user1={"1","10","100","1000","10000"};


问:
Use of " for(string str: tmp) " in c++?
I came accross this for(string str: tmp) s.insert(str) in a C++ code for LCS and I don't know what it means. I saw it used in Java. Can it be written in any other way in C++?

答:
Here is a small working example in C++

```<code>#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> tmp = { "s1", "s2", "s3", "s4"};

    std::vector<std::string> s;

    for (const std::string& str : tmp)
        s.insert(s.end(),str);

    return 0;
}
</code>```

Here, tmp and s are vectors of string

So we are copying the content of the vector tmp to the s vector

The for loop: for (const std::string& str : tmp) will take every value from the tmp vector and insert it (append it) to the end of the s vector.

This for loop is called a range based loop (since C++11)

Title: Use of " for(string str: tmp) " in c++?

Body:
Here is a small working example in C++

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> tmp = { "s1", "s2", "s3", "s4"};

    std::vector<std::string> s;

    for (const std::string& str : tmp)
        s.insert(s.end(),str);

    return 0;
}

Here, tmp and s are vectors of string

So we are copying the content of the vector tmp to the s vector

The for loop: for (const std::string& str : tmp) will take every value from the tmp vector and insert it (append it) to the end of the s vector.

This for loop is called a range based loop (since C++11)


问:
Ionic: Unable to run ionic serve with WARN:ionic project has been renamed to ionic.config.json
My folder for ionic is working in the working but without doing anything, it can not run with command ionic serve. It ask to change ionic.project or run npm bower install. I choose to install bower and it shown "WARN: ionic.project has been renamed to ionic.config.json, please rename it.". rename it and run ionic serve but the app doesn't appear.

The method I rename the ionic.project is press F2 and change to "ionic.config.json"

```<code>D:\app_abc\abc\.git\cha>ionic service
WARN: ionic.project has been renamed to ionic.config.json, please rename it.

You must have bower installed to continue.
Type `npm install -g bower` (CLI v2.0.0-beta.25)

Your system information:

Cordova CLI: 6.1.1
Gulp version:  CLI version 3.9.1
Gulp local:
Ionic Framework Version: 1.3.1
Ionic CLI Version: 2.0.0-beta.25
Ionic App Lib Version: 2.0.0-beta.15
OS:
Node Version: v5.11.1

D:\abc\abc\.git\cha>npm install -g bower
C:\Users\jane\AppData\Roaming\npm\bower -> C:\Users\jane\AppData\Roaming\npm\node_modules\bower\bin\bower
C:\Users\jane\AppData\Roaming\npm
`-- bower@1.8.0

D:\abc\abc\.git\cha>ionic service
WARN: ionic.project has been renamed to ionic.config.json, please rename it.

D:\abc\abc\.git\cha>ionic service

D:\abc\abc\.git\cha>ionic service
Couldn't find ionic.config.json file. Are you in an Ionic project?
</code>```

答:
you are not in ionic project. So it is throwing error.

Example: your project name is ioninProject

Then, path should be like this

D:\abc\abc.git\cha\ionicProject>ionic service

Body:
My folder for ionic is working in the working but without doing anything, it can not run with command ionic serve. It ask to change ionic.project or run npm bower install. I choose to install bower and it shown "WARN: ionic.project has been renamed to ionic.config.json, please rename it.". rename it and run ionic serve but the app doesn't appear.

The method I rename the ionic.project is press F2 and change to "ionic.config.json"

D:\app_abc\abc\.git\cha>ionic service
WARN: ionic.project has been renamed to ionic.config.json, please rename it.

You must have bower installed to continue.
Type `npm install -g bower` (CLI v2.0.0-beta.25)

Your system information:

Cordova CLI: 6.1.1
Gulp version:  CLI version 3.9.1
Gulp local:
Ionic Framework Version: 1.3.1
Ionic CLI Version: 2.0.0-beta.25
Ionic App Lib Version: 2.0.0-beta.15
OS:
Node Version: v5.11.1

D:\abc\abc\.git\cha>npm install -g bower
C:\Users\jane\AppData\Roaming\npm\bower -> C:\Users\jane\AppData\Roaming\npm\node_modules\bower\bin\bower
C:\Users\jane\AppData\Roaming\npm
`-- bower@1.8.0

D:\abc\abc\.git\cha>ionic service
WARN: ionic.project has been renamed to ionic.config.json, please rename it.

D:\abc\abc\.git\cha>ionic service

D:\abc\abc\.git\cha>ionic service
Couldn't find ionic.config.json file. Are you in an Ionic project?


问:
How to fetch json data from external url and compile list of objects using a handlebars template, then render it in bootstrap list?
I am trying to load some JSON data from this external URL http://jsonplaceholder.typicode.com/users

I really can't figure this out. I'm trying out Handlebars.js, but it doesn't display anything in my template except the bootstrap list I've created. Here's what I've got:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>

<body>
<script>
  $.ajax({
  url: 'http://jsonplaceholder.typicode.com/users',
  dataType:'json'
  success: function(names){
    var source = $('#tpl').html();
    var template = Handlebars.compile(source);
    var context = names;

    $('#container').html(template(context));
  }
    });
    </script>
<div id="users"></div>
<script id="tpl" type="text/template">
    <ul>
        {{#each name}}
          <li>{{this}}</li>
        {{/each}}
    </ul>
  </script>
<div class="container">
  <ul class="list-group">
<li class="list-group-item">Leanne Graham</li>
<li class="list-group-item">Ervin Howell</li>
<li class="list-group-item">Clementine Bauch</li>
<li class="list-group-item">Patricia Lebsack</li>
<li class="list-group-item">Chelsey Dietrich</li>
<li class="list-group-item">Mrs. Dennis Schulist</li>
<li class="list-group-item">Kurtis Weissnat</li>
<li class="list-group-item">Nicholas Runolfsdottir V</li>
<li class="list-group-item">Glenna Reichert</li>
<li class="list-group-item">Clementina DuBuque</li>
  </ul>
</div>
</body>
</html>
</code>```

Any help would be greatly appreciated:(

答:
There are a few misused of Handlebar in your code:

The $('#container') should be $('.container')

type="text/template" should be type="text/x-handlebars-template"

Based on the data structure of the return json, it should be {{#each this}}, and then display
{{name}}

So in summary, the correct code should be:

```<code><script>
  $.ajax({
    url: 'http://jsonplaceholder.typicode.com/users',
    dataType:'json',
    success: function(names){
      var source = $('#tpl').html();
      var template = Handlebars.compile(source);
      var context = names;
      $('.container').html(template(context));
    }
  });
</script>

<div id="users"></div>

<script id="tpl" type="text/x-handlebars-template">
  <ul>
    {{#each this}}
      <li>{{name}}</li>
    {{/each}}
  </ul>
</script>
</code>```

Body:
I am trying to load some JSON data from this external URL http://jsonplaceholder.typicode.com/users

I really can't figure this out. I'm trying out Handlebars.js, but it doesn't display anything in my template except the bootstrap list I've created. Here's what I've got:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Leanne Graham

Ervin Howell

Clementine Bauch

Patricia Lebsack

Chelsey Dietrich

Mrs. Dennis Schulist

Kurtis Weissnat

Nicholas Runolfsdottir V

Glenna Reichert

Clementina DuBuque

Any help would be greatly appreciated:(

Body:
There are a few misused of Handlebar in your code:

The $('#container') should be $('.container')

type="text/template" should be type="text/x-handlebars-template"

Based on the data structure of the return json, it should be {{#each this}}, and then display <li>{{name}}</li>

So in summary, the correct code should be:

<script>
  $.ajax({
    url: 'http://jsonplaceholder.typicode.com/users',
    dataType:'json',
    success: function(names){
      var source = $('#tpl').html();
      var template = Handlebars.compile(source);
      var context = names;
      $('.container').html(template(context));
    }
  });
</script>

<div id="users"></div>

<script id="tpl" type="text/x-handlebars-template">
  <ul>
    {{#each this}}
      <li>{{name}}</li>
    {{/each}}
  </ul>
</script>


问:
Inline Assembler for Visual Studio Call
So, first off, this is an assignment for a friend that I'm helping with, and while it's been a while since I've done C, that's not the problem (Or at least I don't think it is), the problem is the assembly code. The assignment must use a function written in inline assembly to sum two numbers that have been passed to the function after having been input by the user, and return the value, which is then output. On running my code, I get errors either reading or writing to memory locations found in the asm function, specifically the second mov command, and the program will hang while attempting to execute that line of code. Tracing the program, one of the values will be stored correctly (Whatever the second value the user enters, which I believe is normal, because values are read in reverse in assembly?) and the other isn't read at all, and the program crashes. I've spent about four hours trying to figure this out, and am now resorting to outside help. Anyways, enough background, trying to be thorough, here's the code. I'm sure what I'm doing is probably something basic and is staring me in the face, but any help is appreciated. Oh, and yes, I made sure masm was enabled in visual studio.</p>

```<code>#include "stdafx.h"
#include "stdio.h"
#include <conio.h>

int sum( int val1, int val2 );
int main (void)
{
int val1=0, val2=0, val3=0;

printf("Hello, this program will add two whole numbers. Please enter the first    number.\n");
scanf("%d",&val1);

printf("Please enter the second number.\n");
scanf("%d",&val2);

val3 = sum(val1, val2);
printf("The sum of %d and %d is %d", val1, val2, val3);
_getch();

return 0;
 }

 int sum ( int val1, int val2 ){
 int val3;

    __asm{  mov eax, val2        ;
            push eax             ;
            mov ebx, val1        ;
            push ebx             ;
            add eax, ebx         ;
            mov ecx, val3        ;
            pop val3             ;
            pop ebx              ;
            pop eax              ;
            pop ecx              ;
            ret                  ;
    }
    return val3;

}
</code>```

答: There's no need to use push and pop when loading CPU registers. The push  instruction causes the value to be written to the memory location pointed to by the SS:[ESP] register pair, where SS is the 16-bit stack segment and ESP is the 32-bit stack pointer. This also decrements ESP by the size of the operand in bytes. The pop instruction performs the inverse operation, reading from the memory location pointed to by SS:[ESP] and incrementing ESP by the size of the operand in bytes.</p>

Title: Inline Assembler for Visual Studio Call

Body:
So, first off, this is an assignment for a friend that I'm helping with, and while it's been a while since I've done C, that's not the problem (Or at least I don't think it is), the problem is the assembly code. The assignment must use a function written in inline assembly to sum two numbers that have been passed to the function after having been input by the user, and return the value, which is then output. On running my code, I get errors either reading or writing to memory locations found in the asm function, specifically the second mov command, and the program will hang while attempting to execute that line of code. Tracing the program, one of the values will be stored correctly (Whatever the second value the user enters, which I believe is normal, because values are read in reverse in assembly?) and the other isn't read at all, and the program crashes. I've spent about four hours trying to figure this out, and am now resorting to outside help. Anyways, enough background, trying to be thorough, here's the code. I'm sure what I'm doing is probably something basic and is staring me in the face, but any help is appreciated. Oh, and yes, I made sure masm was enabled in visual studio.

#include "stdafx.h"
#include "stdio.h"
#include <conio.h>

int sum( int val1, int val2 );
int main (void)
{
int val1=0, val2=0, val3=0;

printf("Hello, this program will add two whole numbers. Please enter the first    number.\n");
scanf("%d",&val1);

printf("Please enter the second number.\n");
scanf("%d",&val2);

val3 = sum(val1, val2);
printf("The sum of %d and %d is %d", val1, val2, val3);
_getch();

return 0;
 }

 int sum ( int val1, int val2 ){
 int val3;

    __asm{  mov eax, val2        ;
            push eax             ;
            mov ebx, val1        ;
            push ebx             ;
            add eax, ebx         ;
            mov ecx, val3        ;
            pop val3             ;
            pop ebx              ;
            pop eax              ;
            pop ecx              ;
            ret                  ;
    }
    return val3;

}


问:
Heroku can't open file created in worker
So my project has 2 dynos [web, worker] both in PHP.

In worker I created a file (ex: /app/abc.txt) after a long running process.

In web I allow user to download that file, but even though I provide the exact file name, the system could not open it (it said file not found).

2017-04-02T03:38:29.606293+00:00 app[worker.1]: [2017-04-02 03:38:29] myapp.INFO: [start] confirmed existence of /app/abc.txt [] []

I confirmed the existence of the file by using file_exists function which return TRUE. (I even try file_get_contents and able to get the content with no problem). But when I try to access it from web.

2017-04-02T04:21:13.226793+00:00 app[web.1]: [2017-04-02 04:21:13] myapp.INFO: [api.download] find not found /app/abc.txt [] []

Do anyone has any idea why that is?

答: Unfortunately, you can't access file in one dyno from another dyno, because they are different instances of VMs. What you CAN do is use external storage such as S3.</p>


问:
Why is this semaphore code failing?
```<code>#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}
</code>```

<p>I'm getting: </p>

```<code>/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status
</code>```

答:
Per the sem_init() man page

Link with -lrt or -pthread.

As in gcc your_code.c -lpthread -o your_code

Title: Why is this semaphore code failing?

Body:
#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}

I'm getting:

/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status


问:
Knockout not providing Updated value using value binding
I want to print the value of an input element in console using knockout.

When I try to print that value I am getting "result" instead of the value of the textbox.

var ViewModel = {
   name: ko.observable("name"),
   company: ko.observable("company"),
   submit: ko.observable("Submit"),
   onsubmit: function(){
      console.log(name);
   }
}

ko.applyBindings(ViewModel);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<form>
   <label>Name</label>
   <input type="text" data-bind="value:name"/>
   <label>Company</label>
   <input type="text" data-bind="value:company"/>
   <button data-bind="click:onsubmit,text:submit"></button>
</form></code>```

答:
You can also do it this way. I like to declare a function for my viewmodel so that later it can be used to initialize another new object.

var ViewModel = function() {
  var self = this;
  self.name = ko.observable("name");
  self.company = ko.observable("company");
  self.submit = ko.observable("Submit");
  self.onsubmit = function(){
   alert(self.name())
   console.log(self.name());
  };
}
ko.applyBindings(new ViewModel());```
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>Name</label>
<input type="text" data-bind="value: name"/>
<label>Company</label>
<input type="text" data-bind="value: company"/>
<button data-bind="click: onsubmit, text: submit"></button></code>```

Body:
I want to print the value of an input element in console using knockout.

When I try to print that value I am getting "result" instead of the value of the textbox.

var ViewModel = {
   name: ko.observable("name"),
   company: ko.observable("company"),
   submit: ko.observable("Submit"),
   onsubmit: function(){
      console.log(name);
   }
}

ko.applyBindings(ViewModel);

<form>
   Name
   <input type="text" data-bind="value:name"/>
   Company
   <input type="text" data-bind="value:company"/>
   <button data-bind="click:onsubmit,text:submit"></button>
</form>

Body:
You can also do it this way. I like to declare a function for my viewmodel so that later it can be used to initialize another new object.

var ViewModel = function() {
  var self = this;
  self.name = ko.observable("name");
  self.company = ko.observable("company");
  self.submit = ko.observable("Submit");
  self.onsubmit = function(){
   alert(self.name())
   console.log(self.name());
  };
}
ko.applyBindings(new ViewModel());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>Name</label>
<input type="text" data-bind="value: name"/>
<label>Company</label>
<input type="text" data-bind="value: company"/>
<button data-bind="click: onsubmit, text: submit"></button>


问:
check if text input matches one item inside one of multiple arrays within if and else if statements in javascript
I have a page in a application where I want to have specific images pop up if a specific text is entered by the user. I tried with one example and it worked, but now that I added several variables and their array rows, it does not work. I can't tell exactly what mistake I have made here, I am guessing it's something to do with the nesting with the if and else if condition/statements

HTML

```<code>      <form>
        <input type="text" name="search" placeholder="Type or tap on the microphone above">
      </form>
      <div class="imageContainerSearchPage">

            <img id="toast_018" class="hiddenElement" src="animsAll/Anims_018_Toast.gif">
            <img id="nobaloons_014" class="hiddenElement" src="animsAll/Anims_014_no baloons.gif">
            <img id="wegotastory_019"  class="hiddenElement" src="animsAll/Anims_019_Button_We got a story_textandbook.gif">
            <img id="parisIsBurningButton_021" class="hiddenElement" src="animsAll/Anims_021_Paris is Burning Button.gif">
    </div>
    <!--[•VIDEO BACKGROUND•]-->
    <video  autoplay loop muted>
    <source src="videos/music_saint_etienne_only_love_cropped_370x660.mp4" type="video/mp4">
    Your browser does not support the video tag.
    </video></div>
</code>```

JAVASCRIPT: not working

```<code>     $( "input" )
          .keyup(function() {
            var value = $( this ).val();
            var no = ["sixties", "sixty", "sixtys"];
            var weGotAStory = ["we", "got", "story"];
            var sandwich = ["sandwich", "grilled"];
            var parisIsBurningButton = ["paris", "burning"];
            var toast = ["toasted", "toast", "toasts"];
          if($.inArray(value, no) !== false) {
              $("#nobaloons_014").show().delay(10000).fadeOut();
          } else if ($.inArray(value, weGotAStory) !== false) {
            $("#wegotastory_019").show().delay(10000).fadeOut();
          } else if ($.inArray(value, parisIsBurningButton) !== false) {
            $("#parisIsBurningButton_021").show().delay(10000).fadeOut();
        } else ($.inArray(value, toast) !== false) {
          $("#toast_018").show().delay(10000).fadeOut();

        }

          })
</code>```

JAVASCRIPT: working (single IF statement)

```<code>     $( "input" ).keyup(function() {
            var value = $( this ).val();
            var no = ["no", "nope", "nos"];
          if($.inArray(value, no) !== false) {
              $("#nobaloons_014").show().delay(10000).fadeOut();
         }

      })
</code>```

答:
I compromised with the arrays and took them out because nothing else was working. This works to make the hidden image corresponding to the string pop up but it's not exactly what I wanted (it does not offer the multiple word option w/o the arrays). </p>

```<code>$( "input" )
  .keyup(function() {
    var value = $( this ).val();
    var sixties = "sixties";
    var paris = "paris";
    var weGotAStory = "story";
  if (value == sixties) {
    $("#button1960s_002").show().delay(10000).fadeOut();
  }   else if (value == paris) {
      $("#parisIsBurningButton_021").show().delay(10000).fadeOut();
    } else if (value == weGotAStory) {
        $("#wegotastory_019").show().delay(10000).fadeOut();
      }

  })
</code>```

Body:
I have a page in a application where I want to have specific images pop up if a specific text is entered by the user. I tried with one example and it worked, but now that I added several variables and their array rows, it does not work. I can't tell exactly what mistake I have made here, I am guessing it's something to do with the nesting with the if and else if condition/statements

HTML

      <form>
        <input type="text" name="search" placeholder="Type or tap on the microphone above">
      </form>

    <video  autoplay loop muted>
    <source src="videos/music_saint_etienne_only_love_cropped_370x660.mp4" type="video/mp4">
    Your browser does not support the video tag.
    </video>

JAVASCRIPT: not working

     $( "input" )
          .keyup(function() {
            var value = $( this ).val();
            var no = ["sixties", "sixty", "sixtys"];
            var weGotAStory = ["we", "got", "story"];
            var sandwich = ["sandwich", "grilled"];
            var parisIsBurningButton = ["paris", "burning"];
            var toast = ["toasted", "toast", "toasts"];
          if($.inArray(value, no) !== false) {
              $("#nobaloons_014").show().delay(10000).fadeOut();
          } else if ($.inArray(value, weGotAStory) !== false) {
            $("#wegotastory_019").show().delay(10000).fadeOut();
          } else if ($.inArray(value, parisIsBurningButton) !== false) {
            $("#parisIsBurningButton_021").show().delay(10000).fadeOut();
        } else ($.inArray(value, toast) !== false) {
          $("#toast_018").show().delay(10000).fadeOut();

        }

          })

JAVASCRIPT: working (single IF statement)

     $( "input" ).keyup(function() {
            var value = $( this ).val();
            var no = ["no", "nope", "nos"];
          if($.inArray(value, no) !== false) {
              $("#nobaloons_014").show().delay(10000).fadeOut();
         }

      })

Body:
I compromised with the arrays and took them out because nothing else was working. This works to make the hidden image corresponding to the string pop up but it's not exactly what I wanted (it does not offer the multiple word option w/o the arrays).

$( "input" )
  .keyup(function() {
    var value = $( this ).val();
    var sixties = "sixties";
    var paris = "paris";
    var weGotAStory = "story";
  if (value == sixties) {
    $("#button1960s_002").show().delay(10000).fadeOut();
  }   else if (value == paris) {
      $("#parisIsBurningButton_021").show().delay(10000).fadeOut();
    } else if (value == weGotAStory) {
        $("#wegotastory_019").show().delay(10000).fadeOut();
      }

  })


问:
Using a loop to get all tables within a database

Please understand that I am fairly new to PhP and I might have come by the answer to my question without knowing it. If this is the case, please direct me to the correct answer.

I have a database which has multiple tables in it. Each table does have the exact same structure, as each table corresponds with a different unit within a franchise of restaurants. I am trying to create a "master" page for the franchise owner to be able to pull up all (or one) of the tables onto one page in order to view the data associated with each unit. I have tried every permeation that I could think of to get the code to work right but I keep getting errors thrown at me. The most recent error message that I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

In past questions people have tried telling me that my code needs to be one way because I only include a portion of my code. This time I will include all of the code within the page that is throwing the errors.

```<code><?php
require_once('../dbconnection.php');

$tables = array($_POST["spenard"], $_POST["benson"], $_POST["eagle"],
$_POST["wasilla"], $_POST["boniface"], $_POST["dimond"], $_POST["tudor"],
$_POST["huffman"], $_POST["dtown"], $_POST["airport"], $_POST["college"],
$_POST["npole"], $_POST["kenai"], $_POST["suldotna"]);
$length = count($tables);

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Food Safety Checklist Master List</title>

<script>

</script>
</head>

<body>

<!--<table>
    ?php
        for ($i = 0; $i < $length; $i++) {?>
        <tr>
            <th>?php echo $tables[$i]; ?></th>
        </tr>
        ?php }
    ?>
    <tr>

    </tr>
</table>-->

<table>
    <tr>
        <th>Food Safety Checklist</th>
    </tr>
    <?php for ($i = 0; $i < $length; $i++) {
        mysqli_select_db($conn, $dbname);
        $query_lists = "SELECT * FROM $tables[$i]";
        $lists = mysqli_query($conn, $query_lists) or
die(mysqli_error($conn));
        $row_lists = mysqli_fetch_assoc($lists);
        $totalRows_lists = mysqli_num_rows($lists);?>
    <tr>
        <th><?php echo $row_lists[' ']; ?></th>
    </tr>
    <?php } ?>
</table>

</body>
</html>
</code>```

The code for the initiating page is:

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Food Safety Checklist Master Selection</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
</head>

<body>

<header>
    <h1>Pizza Hut Food Safety</h1>
</header>

<section>
    <div>
        <form action="mastershow.php" method="post" name="masterselect" id="masterselect">
            <table>
                <tr>
                    <th colspan="2"><h2>Stores</h2></th>
                </tr>
                <tr>
                    <th colspan="2"><input type="submit" value="Run" id="submit" name="submit"></th>
                </tr>
                <tr>
                    <td><label for="spenard">Spenard 010576</label></td>
                    <td><input name="spenard" id="spenard" type="checkbox" value="`010576`"><br/></td>
                </tr>
                <tr>
                    <td><label for="benson">Benson 011169</label></td>
                    <td><input name="benson" id="benson" type="checkbox" value="`011169`"><br/></td>
                </tr>
                <tr>
                    <td><label for="eagle">Eagle River 008181</label></td>
                    <td><input name="eagle" id="eagle" type="checkbox" value="`008181`"><br/></td>
                </tr>
                <tr>
                    <td><label for="wasilla">Wasilla 010324</label></td>
                    <td><input name="wasilla" id="wasilla" type="checkbox" value="`010324`"><br/></td>
                </tr>
                <tr>
                    <td><label for="boniface">Boniface 008615</label></td>
                    <td><input name="boniface" id="boniface" type="checkbox" value="`008615`"><br/></td>
                </tr>
                <tr>
                    <td><label for="dimond">W. Dimond 009150</label></td>
                    <td><input name="dimond" id="dimond" type="checkbox" value="`009150`"><br/></td>
                </tr>
                <tr>
                    <td><label for="tudor">Tudor 014640</label></td>
                    <td><input name="tudor" id="tudor" type="checkbox" value="`014640`"><br/></td>
                </tr>
                <tr>
                    <td><label for="huffman">Huffman 0101684</label></td>
                    <td><input name="huffman" id="huffma" type="checkbox" value="`010684`"><br/></td>
                </tr>
                <tr>
                    <td><label for="dtown">6TH AVE 011168</label></td>
                    <td><input name="dtown" id="dtwon" type="checkbox" value="`011168`"><br/></td>
                </tr>
                <tr>
                    <td><label for="airport">Airport Rd. 014215</label></td>
                    <td><input name="airport" id="airport" type="checkbox" value="`014215`"><br/></td>
                </tr>
                <tr>
                    <td><label for="college">College Rd. 008179</label></td>
                    <td><input name="college" id="college" type="checkbox" value="`008179`"><br/></td>
                </tr>
                <tr>
                    <td><label for="npole">North Pole 008339</label></td>
                    <td><input name="npole" id="npole" type="checkbox" value="`008339`"><br/></td>
                </tr>
                <tr>
                    <td><label for="kenai">Kenai 008668</label></td>
                    <td><input name="kenai" id="kenai" type="checkbox" value="`008668`"><br/></td>
                </tr>
                <tr>
                    <td><label for="suldotna">Suldotna 031574</label></td>
                    <td><input name="suldotna" id="suldotna" type="checkbox" value="`031574`"><br/></td>
                </tr>
            </table>
        </form>
    </div>
</section>

<footer>
    Designed by Greg Weiland ©2017
</footer>

</body>
</html>
</code>```

Again, I am trying to have it to where the franchise owner can "check" which stores to run the report on, and then be able to get all rows from the corresponding tables (again, each table has a name which corresponds to one of the unit numbers) that he has selected. Each table has identical structure. Thank you for any and all help

答:
try this instead :

```<code>$sql = "SELECT * FROM ".$tables[$i];
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
</code>```

then for example youre looking for id within your selection, then just find it with $results['id'];

also a little sidenote : i like putting my database query methods in a seperate php file that i import. in that case, i gather all my data in a $results array and return the array.

something like this :

```<code>$sql = "SELECT * FROM ".$tables[$i];
$result = $conn->query($sql);
$results = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $results[] = $row;
    }
} else {
    echo "0 results";
}
$conn->close();
return $results;
</code>```

Body:
Please understand that I am fairly new to PhP and I might have come by the answer to my question without knowing it. If this is the case, please direct me to the correct answer.

I have a database which has multiple tables in it. Each table does have the exact same structure, as each table corresponds with a different unit within a franchise of restaurants. I am trying to create a "master" page for the franchise owner to be able to pull up all (or one) of the tables onto one page in order to view the data associated with each unit. I have tried every permeation that I could think of to get the code to work right but I keep getting errors thrown at me. The most recent error message that I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"

In past questions people have tried telling me that my code needs to be one way because I only include a portion of my code. This time I will include all of the code within the page that is throwing the errors.

<?php
require_once('../dbconnection.php');

$tables = array($_POST["spenard"], $_POST["benson"], $_POST["eagle"],
$_POST["wasilla"], $_POST["boniface"], $_POST["dimond"], $_POST["tudor"],
$_POST["huffman"], $_POST["dtown"], $_POST["airport"], $_POST["college"],
$_POST["npole"], $_POST["kenai"], $_POST["suldotna"]);
$length = count($tables);

?>
<!doctype html>

<meta charset="utf-8">
<title>Food Safety Checklist Master List</title>

        Food Safety Checklist

    <?php for ($i = 0; $i < $length; $i++) {
        mysqli_select_db($conn, $dbname);
        $query_lists = "SELECT * FROM $tables[$i]";
        $lists = mysqli_query($conn, $query_lists) or
die(mysqli_error($conn));
        $row_lists = mysqli_fetch_assoc($lists);
        $totalRows_lists = mysqli_num_rows($lists);?>

        <?php echo $row_lists[' ']; ?>

    <?php } ?>

The code for the initiating page is:

<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Food Safety Checklist Master Selection</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Pizza Hut Food Safety

        <form action="mastershow.php" method="post" name="masterselect" id="masterselect">

Stores

                    <input type="submit" value="Run" id="submit" name="submit">

                    Spenard 010576
                    <input name="spenard" id="spenard" type="checkbox" value="`010576`">

                    Benson 011169
                    <input name="benson" id="benson" type="checkbox" value="`011169`">

                    Eagle River 008181
                    <input name="eagle" id="eagle" type="checkbox" value="`008181`">

                    Wasilla 010324
                    <input name="wasilla" id="wasilla" type="checkbox" value="`010324`">

                    Boniface 008615
                    <input name="boniface" id="boniface" type="checkbox" value="`008615`">

                    W. Dimond 009150
                    <input name="dimond" id="dimond" type="checkbox" value="`009150`">

                    Tudor 014640
                    <input name="tudor" id="tudor" type="checkbox" value="`014640`">

                    Huffman 0101684
                    <input name="huffman" id="huffma" type="checkbox" value="`010684`">

                    6TH AVE 011168
                    <input name="dtown" id="dtwon" type="checkbox" value="`011168`">

                    Airport Rd. 014215
                    <input name="airport" id="airport" type="checkbox" value="`014215`">

                    College Rd. 008179
                    <input name="college" id="college" type="checkbox" value="`008179`">

                    North Pole 008339
                    <input name="npole" id="npole" type="checkbox" value="`008339`">

                    Kenai 008668
                    <input name="kenai" id="kenai" type="checkbox" value="`008668`">

                    Suldotna 031574
                    <input name="suldotna" id="suldotna" type="checkbox" value="`031574`">

        </form>

    Designed by Greg Weiland ©2017

Again, I am trying to have it to where the franchise owner can "check" which stores to run the report on, and then be able to get all rows from the corresponding tables (again, each table has a name which corresponds to one of the unit numbers) that he has selected. Each table has identical structure. Thank you for any and all help

Body:
try this instead :

$sql = "SELECT * FROM ".$tables[$i];
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

then for example youre looking for id within your selection, then just find it with $results['id'];

also a little sidenote : i like putting my database query methods in a seperate php file that i import. in that case, i gather all my data in a $results array and return the array.

something like this :

$sql = "SELECT * FROM ".$tables[$i];
$result = $conn->query($sql);
$results = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $results[] = $row;
    }
} else {
    echo "0 results";
}
$conn->close();
return $results;


问:
WooCommerce - Get the Subscription id from the Order ID
I'm trying to get the subscription id from the action hook woocommerce_order_status_changed.

It gives me the order id which is changed with every switch the customer makes.

For example: If the subscription id is 10, the original order id is 9.

Now every switch the customer made generates a new order id, which the action above gives you. At this point I have the $customer_id, $order_id, and the original post id which is 9,

How I can get the subscription id of the current order?

答:
You can use dedicated function wcs_get_subscriptions_for_order() which will retrieve $subscription IDs.

So this could be your code:

```<code>add_action('woocommerce_order_status_changed', 'action_order_status_changed');
function action_order_status_changed( $order_id ){
    $subscriptions_ids = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
    // We get all related subscriptions for this order
    foreach( $subscriptions_ids as $subscription_id => $subscription_obj )
        if($subscription_obj->order->id == $order_id) break; // Stop the loop

    // The subscription ID: $subscription_id
    // The An instance of the Subscription object: $subscription_obj
    // ...
}
</code>```

Body:
You can use dedicated function wcs_get_subscriptions_for_order() which will retrieve $subscription IDs.

So this could be your code:

add_action('woocommerce_order_status_changed', 'action_order_status_changed');
function action_order_status_changed( $order_id ){
    $subscriptions_ids = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
    // We get all related subscriptions for this order
    foreach( $subscriptions_ids as $subscription_id => $subscription_obj )
        if($subscription_obj->order->id == $order_id) break; // Stop the loop

    // The subscription ID: $subscription_id
    // The An instance of the Subscription object: $subscription_obj
    // ...
}


问:
Where is the entry count for an object stored in Java
I understand that the each Java object can be used as a Monitor. A thread can acquire the lock if the entry count associated with the object is zero. And if the same thread acquires the lock, the entry count is incremented thru the "monitorenter" opcode and is decremented when the same thread releases the code during "monitorexit". Where is this entry count stored? How is it linked to a Java object? Does it get allocated when the object is created?</p>

答:
Each JVM may have different implementation of intrinsic locks. As to HotSpot JVM, it does not count lock entries at all, but rather reserves slots in the stack frames of methods with monitorenter/monitorexit bytecodes.

HotSpot JVM has two mechanisms for Java monitors:

Biased Lock. The object is 'biased' toward the given thread by putting the thread ID in the object header. Then locking and unlocking in the given thread is almost a no-op: JVM just needs to verify that Biased Lock marker is still in the object header.

Regular recursive lock. If a method has synchronized blocks (i.e. monitorenter/monitorexit) bytecodes, a place is reserved on the stack to record the lock info: an object and its displaced header (i.e. the header value before locking). If an object is locked recursively, the displaced header contains zero, so the VM knows that it should not update an object header on monitorexit.

More details in HotSpot sources.


问:
Angular 2 project developed using cli publish as npm package
We are planning to develop a large application using angular 2. So we have one parent angular 2 application, which have 3 sub child applications which do not have any relations to each other. So we developed this 3 sub child applications as 3 different angular 2 applications and these applications have its own routing. Now i want to publish this project into npm, so that i can fetch these projects in parent application. Currently i am stuck at publishing project to npm. Can any one provide me a proper tutorial?</p>

答:
Angular-cli projects are NPM packages since they use a package.json please refer to NPM's tutorial on publishing packages

Also, please read this section on .npmignore you'll need it to publish a clean package.

After publishing, install the published packages as you would any npm package and import the modules, components, services ...etc from the correct location under node_modules/<newly published package>/path/to/tsFile

Hope this helps, cheers.


问:
PHP Search Result Concatenation
I'm trying to find a method in php to concat all related search return results from mysql DB into a single string separated by a comma. See below for DB table php output formats and php code.

Beach table:

```<code>bname    length  city_name
Beach A  4       City Z
Beach B  3       City X
Beach C  7       City E
</code>```

Beach_Act_Type table:

```<code>bname        act_type
Beach A      Swimming
Beach A      Surfing
Beach B      Surfing
Beach C      Swimming
Beach C      Fishing
Beach C      Surfing
</code>```

Output I'm looking for:

```<code>`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming, Fishing, Surfing
</code>```

Instead of this output format:

```<code>`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming
 Beach C           Fishing
 Beach C           Surfing
</code>```

My php code:

```<code>$conn = new mysqli('localhost','test','','beachproject');

if (!$conn) {
    die('DB Connection Error');
}

$search = $_POST['search'];
$search_sql="select `beach`.`bname`, `beach_act_type`.`act_type`
from `beach` inner join `beach_act_types`
on `beach`.`bname`=`beach_act_type`.`bname`
where `beach`.`bname`='$search'";
$search_query=$conn->query($search_sql);

if ($search_query->num_rows > 0) {
    while($row = $search_query->fetch_assoc()) {
        echo "<table border='1' cellpadding='4'>
        <tr>
        <th>Beach Name</th>
        <th>Beach Activity Allowed</th>
        </tr>";

        echo "<tr>";
        echo "<td>" . $row['bname'] . "</td>";
        echo "<td>" . $row['act_type'] . "</td>";
        echo "</tr>";

        echo "</table>";
    }
} else {
    echo "No Search Results";
}
</code>```

答:
You are just crrating two seperate table data which wont give you result you want , try the code below
You cant get "," in different table data.
Try this ,</p>

```<code>    <?php $conn = new
  mysqli('localhost','test','','beachproject');
  if (!$conn) { die('DB Connection
  Error'); }
  $search = $_POST['search'];
  $search_sql="select `beach`.`bname`,
 `beach_act_type`.`act_type` from
 `beach` inner join `beach_act_types` on
 `beach`.`bname`=`beach_act_type`.`
  bname` where
  `beach`.`bname`='$search'";
 $search_query=$conn
 >query($search_sql);
 if ($search_query->num_rows > 0) {
 while($row = $search_query
 >fetch_assoc()) { echo "<table
 border='1' cellpadding='4'>
 <tr> <th>Beach Name</th> <th>Beach
 Activity Allowed</th> </tr>"; echo "<tr>";
 echo "<td>" . $row['bname'] . , .
 $row['act_type']"</td>"; echo "</tr>";
 echo "</table>"; } } else { echo "No
 Search Results"; } ?>
</code>```

Title: PHP Search Result Concatenation

Body:
I'm trying to find a method in php to concat all related search return results from mysql DB into a single string separated by a comma. See below for DB table php output formats and php code.

Beach table:

bname    length  city_name
Beach A  4       City Z
Beach B  3       City X
Beach C  7       City E

Beach_Act_Type table:

bname        act_type
Beach A      Swimming
Beach A      Surfing
Beach B      Surfing
Beach C      Swimming
Beach C      Fishing
Beach C      Surfing

Output I'm looking for:

`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming, Fishing, Surfing

Instead of this output format:

`beach`.`bname`    `beach_act_type`.`act_type`
 Beach C           Swimming
 Beach C           Fishing
 Beach C           Surfing

My php code:

$conn = new mysqli('localhost','test','','beachproject');

if (!$conn) {
    die('DB Connection Error');
}

$search = $_POST['search'];
$search_sql="select `beach`.`bname`, `beach_act_type`.`act_type`
from `beach` inner join `beach_act_types`
on `beach`.`bname`=`beach_act_type`.`bname`
where `beach`.`bname`='$search'";
$search_query=$conn->query($search_sql);

if ($search_query->num_rows > 0) {
    while($row = $search_query->fetch_assoc()) {
        echo "

        Beach Name
        Beach Activity Allowed

";

        echo "
";
        echo "" . $row['bname'] . "	";
        echo "" . $row['act_type'] . "	";
        echo "
";

        echo "
";
    }
} else {
    echo "No Search Results";
}

Body:
You are just crrating two seperate table data which wont give you result you want , try the code below
You cant get "," in different table data.
Try this ,

    <?php $conn = new
  mysqli('localhost','test','','beachproject');
  if (!$conn) { die('DB Connection
  Error'); }
  $search = $_POST['search'];
  $search_sql="select `beach`.`bname`,
 `beach_act_type`.`act_type` from
 `beach` inner join `beach_act_types` on
 `beach`.`bname`=`beach_act_type`.`
  bname` where
  `beach`.`bname`='$search'";
 $search_query=$conn
 >query($search_sql);
 if ($search_query->num_rows > 0) {
 while($row = $search_query
 >fetch_assoc()) { echo "<table
 border='1' cellpadding='4'>
 <tr> <th>Beach Name</th> <th>Beach
 Activity Allowed</th> </tr>"; echo "<tr>";
 echo "<td>" . $row['bname'] . , .
 $row['act_type']"</td>"; echo "</tr>";
 echo "</table>"; } } else { echo "No
 Search Results"; } ?>


问:
How to parse query string in react-router v4
In react-router v3 I could access it with props.location.query.foo (if the current location was ?foo=bar)

In react-router-dom@4.0.0 props.location only has props.location.search with is a string like ?foo=bar&other=thing.

Perhaps I need to manually parse and deconstruct that string to find the value for foo or other.

Screenshot of console.log(this.props):

(Note how from ?artist=band here I'd like to get the value from artist which is the value band)

答:
Glad I found this post.  Thanks for the links, after a couple of hours I finally got my code upgraded.

For those of you using query-string, you might have to do something like

```<code>var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;
</code>```

This happened in my case, and this.props.location.search.theUrlYouWant would refuse to work.  The second option Tyler mentioned also worked for me with some similar tweaking.

Body:
Glad I found this post.  Thanks for the links, after a couple of hours I finally got my code upgraded.

For those of you using query-string, you might have to do something like

var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;

This happened in my case, and this.props.location.search.theUrlYouWant would refuse to work.  The second option Tyler mentioned also worked for me with some similar tweaking.


问:
(android) an scrollview that gets programmatically filled loses title
I have this layout:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

I fill the 'container' TableLayout with elements like this:

```<code>    layout.addView(buildTitleRow());

    for (int i = 0; i < users.length(); i++) {

        JSONObject parent = (JSONObject) users.get(i);

        layout.addView(buildRowFrom(parent, i + 1));
    }
</code>```

buildTitleRow:

```<code>private TableRow buildTitleRow(){

    TableRow result = new TableRow(this);

    int color = Color.parseColor("#ffff00");

    View view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    //the same for other views

    return result;
}
</code>```

buildRowFrom:

```<code>private TableRow buildRowFrom(final JSONObject element, int counter) throws JSONException {

    TableRow result = new TableRow(this);

    String rowName = element.getString("name");

    int color = Color.parseColor("#00ff00");

    if(rowName.equals(userName)){
        color = Color.parseColor("#ffffff");
    }

    TextView textView = new TextView(this);
    textView.setText(counter + ".");
    textView.setTextColor(color);
    result.addView(textView);

    //some other views

    return result;
}
</code>```

this really works well just until the scrolling needs to take place...

Once there are more elements than the height of the screen the table remains scrollable (luckily) but the original 'title' Textview doesn't show up anymore (you can't scroll up towards it anymore)

Does anyone know how to tweak the layout to keep it visible once more elements are added than the size of the screen?

Thanks a lot,

S.

答:
I've tried your code and found find something wrong in your xml layout.

The attribute android:layout_gravity will change the layout's own gravity. So if set this attribute to a LinearLayout with center and its android:layout_height is wrap_content(means that the real height of the 'LinearLayout' will exceed the screen's height) and fill ScrollView(its height is the screen's height) with it, the LinearLayout will align to center of its parent ScrollView.

If you want to keep the content of 'LinearLayout' centered, you can set android:fillViewport="true" to ScrollView and then the LinearLayout will fill the parent and you can use android:gravity="center" on the LinearLayout. Reference

But there is still some thing need to be changed. In your java code, View view = new View(this) this line will new a View and then you add it into TableLayout. But this TableLayout will be full of View because of the description of View below.

* The base class implementation of measure defaults to the background size,
* unless a larger size is allowed by the MeasureSpec. Subclasses should
* override {@link #onMeasure(int, int)} to provide better measurements of
* their content.

You can use a concrete view like TextView instead of it.

I don't know if I have clarified it. I think if you remove the attribute android:layout_gravity of LinearLayout, it will work.

I'm glad if it would help.

Body:
I have this layout:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

I fill the 'container' TableLayout with elements like this:

    layout.addView(buildTitleRow());

    for (int i = 0; i < users.length(); i++) {

        JSONObject parent = (JSONObject) users.get(i);

        layout.addView(buildRowFrom(parent, i + 1));
    }

buildTitleRow:

private TableRow buildTitleRow(){

    TableRow result = new TableRow(this);

    int color = Color.parseColor("#ffff00");

    View view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    //the same for other views

    return result;
}

buildRowFrom:

private TableRow buildRowFrom(final JSONObject element, int counter) throws JSONException {

    TableRow result = new TableRow(this);

    String rowName = element.getString("name");

    int color = Color.parseColor("#00ff00");

    if(rowName.equals(userName)){
        color = Color.parseColor("#ffffff");
    }

    TextView textView = new TextView(this);
    textView.setText(counter + ".");
    textView.setTextColor(color);
    result.addView(textView);

    //some other views

    return result;
}

this really works well just until the scrolling needs to take place...

Once there are more elements than the height of the screen the table remains scrollable (luckily) but the original 'title' Textview doesn't show up anymore (you can't scroll up towards it anymore)

Does anyone know how to tweak the layout to keep it visible once more elements are added than the size of the screen?

Thanks a lot,

S.


问:
Find the longest arithmetic progression inside a sequence
Suppose I have a sequence of increasing numbers, and I want to find the length of longest arithmetic progression within the sequence. Longest arithmetic progression means an increasing sequence with common difference, such as [2, 4, 6, 8] or [3, 6, 9, 12].

For example,
for [5, 10, 14, 15, 17], [5, 10, 15] is the longest arithmetic progression, with length 3;

for [10, 12, 13, 20, 22, 23, 30], [10, 20, 30] is the longest arithmetic progression with length 3;

for [7, 10, 12, 13, 15, 20, 21], [10, 15, 20] or [7, 10, 13] are the longest arithmetic progressions with length 3.

This site
https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_22_-_Longest_arithmetic_progression.jsp
offers some insight into the problem, i.e. by looping around j and consider
every 3 elements. I intend to use this algorithm in Python, and my code is as follows:

```<code>def length_of_AP(L):
n = len(L)
Table = [[0 for _ in range(n)] for _ in range(n)]
length_of_AP = 2

# initialise the last column of the table as all i and (n-1) pairs have lenth 2
for i in range(n):
        Table[i][n-1] =2

# loop around the list and i, k such that L[i] + L[k] = 2 * L[j]
for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while i >= 0 and k < n:
                difference = (L[i] + L[k]) - 2 * L[j]
                if difference < 0:
                        k = k + 1
                else:
                        if difference > 0:
                                i = i - 1
                        else:
                                Table[i][j] = Table[j][k] + 1
                                length_of_AP = max(length_of_AP, Table[i][j])
                                k = k + 1
                                i = i - 1
return length_of_AP
</code>```

This function works fine with [1, 3, 4, 5, 7, 8, 9], but it doesn't work for [5, 10, 14, 15, 20, 25, 26, 27, 28, 30, 31], where I am supposed to get 6 but I got 4. I can see the reason being that 25, 26, 27, 28 inside the list may be a distracting factor for my function. How do I change my function so that it gives me the result desired.

Any help may be appreciated.

答:
Following your link and running second sample, it looks like the code actually find proper LAP

5, 10, 15, 20, 25, 30,

but fails to find proper length. I didn't spend too much time analyzing the code but the piece

    // Any 2-letter series is an AP
    // Here we initialize only for the last column of lookup because
    // all i and (n-1) pairs form an AP of size 2
    for (int i=0; i<n; i++)
        lookup[i][n-1] = 2;
```

<p>looks suspicious to me. It seems that you need to initialize <strong>whole</strong> <code>lookup</code> table with 2 instead of just last column and if I do so, it starts to get correct length on your sample as well. </p>

<p>So get rid of the "initialise" loop and change your 3rd line to following code:</p>

```# initialise whole table with 2 as all (i, j) pairs have length 2
Table = [[2 for _ in range(n)] for _ in range(n)]
```

<p>Moreover their</p>

<blockquote>
  <p>Sample Execution:  <br />
  Max AP length = 6  <br />
  3, 5, 7, 9, 11, 13, 15, 17, </p>
</blockquote>

<p>Contains this bug as well and actually prints correct sequence only because of sheer luck. If I modify the sortedArr to </p>

```int sortedArr[] = new int[] {3, 4, 5, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18,  112, 113, 114, 115, 116, 117, 118};
```

I get following output

Max AP length = 7

  112, 113, 114, 115, 116, 117, 118,

which is obviously wrong as original 8-items long sequence 3, 5, 7, 9, 11, 13, 15, 17, is still there.

Body:
Suppose I have a sequence of increasing numbers, and I want to find the length of longest arithmetic progression within the sequence. Longest arithmetic progression means an increasing sequence with common difference, such as [2, 4, 6, 8] or [3, 6, 9, 12].

For example,
for [5, 10, 14, 15, 17], [5, 10, 15] is the longest arithmetic progression, with length 3;

for [10, 12, 13, 20, 22, 23, 30], [10, 20, 30] is the longest arithmetic progression with length 3;

for [7, 10, 12, 13, 15, 20, 21], [10, 15, 20] or [7, 10, 13] are the longest arithmetic progressions with length 3.

This site
https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_22_-_Longest_arithmetic_progression.jsp
offers some insight into the problem, i.e. by looping around j and consider
every 3 elements. I intend to use this algorithm in Python, and my code is as follows:

def length_of_AP(L):
n = len(L)
Table = [[0 for _ in range(n)] for _ in range(n)]
length_of_AP = 2

# initialise the last column of the table as all i and (n-1) pairs have lenth 2
for i in range(n):
        Table[i][n-1] =2

# loop around the list and i, k such that L[i] + L[k] = 2 * L[j]
for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while i >= 0 and k < n:
                difference = (L[i] + L[k]) - 2 * L[j]
                if difference < 0:
                        k = k + 1
                else:
                        if difference > 0:
                                i = i - 1
                        else:
                                Table[i][j] = Table[j][k] + 1
                                length_of_AP = max(length_of_AP, Table[i][j])
                                k = k + 1
                                i = i - 1
return length_of_AP

This function works fine with [1, 3, 4, 5, 7, 8, 9], but it doesn't work for [5, 10, 14, 15, 20, 25, 26, 27, 28, 30, 31], where I am supposed to get 6 but I got 4. I can see the reason being that 25, 26, 27, 28 inside the list may be a distracting factor for my function. How do I change my function so that it gives me the result desired.

Any help may be appreciated.

Body:
Following your link and running second sample, it looks like the code actually find proper LAP

5, 10, 15, 20, 25, 30,

but fails to find proper length. I didn't spend too much time analyzing the code but the piece

    // Any 2-letter series is an AP
    // Here we initialize only for the last column of lookup because
    // all i and (n-1) pairs form an AP of size 2
    for (int i=0; i<n; i++)
        lookup[i][n-1] = 2;

looks suspicious to me. It seems that you need to initialize whole lookup table with 2 instead of just last column and if I do so, it starts to get correct length on your sample as well.

So get rid of the "initialise" loop and change your 3rd line to following code:

# initialise whole table with 2 as all (i, j) pairs have length 2
Table = [[2 for _ in range(n)] for _ in range(n)]

Moreover their

Sample Execution:

  Max AP length = 6

  3, 5, 7, 9, 11, 13, 15, 17,

Contains this bug as well and actually prints correct sequence only because of sheer luck. If I modify the sortedArr to

int sortedArr[] = new int[] {3, 4, 5, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18,  112, 113, 114, 115, 116, 117, 118};

I get following output

Max AP length = 7

  112, 113, 114, 115, 116, 117, 118,

which is obviously wrong as original 8-items long sequence 3, 5, 7, 9, 11, 13, 15, 17, is still there.


问:
Very strange iPhone app crash problem with tabbar based app
I know the title sounds a bit awkward but let me explain my problem.

I have a tab bar based iPhone app which works perfectly so far. I can switch through the tabs and every tab loads a view controller.

But here is how it crashes. After I used the app and working with a bunch of other apps I switch back to my app (for example after one hour). The app shows the screen where I left it. Now when I try to change the tab, it crashes immediately.

The problem is that I can't reproduce this crash in the simulator or in the debug mode. I tried to open it, then close it, then reopen it but then everything works. Only after a certain amount of time the crash can be reproduced. But I don't have any logs.

Maybe anyone had the same the problem and knows what to do here?

答: Could it be related to low memory (i.e., you have a bug that only shows up during low memory)?  Have you tried "Simulate Memory Warning" in the simulator?</p>


问:
load data to "from workspace" block simulink from .m file
I have a problem when I try to import data to "from Workspace" block in Simulink.

I have data from the .m file, I want to write this data to "from Workspace."  The system shows an error is "undefined variable."
Someone have any idea for my problem.

Thank you!

答:
The "from Workspace" block allows to import values from already stored variables, not from any script. If you have your data in any script, you can run it and make sure the desired variables are in the workspace.

Also, the Simulink block asks for a specific data structure as follows:

If you're having troubles with this structure, you can do it in the other sense, use the block "to Workspace" and see the structure of the returned variables.


问:
getting invalid errors for array type
getting an invalid array type in the for loop not allowing me to fill the array sivalues. it wont poulate the array with x  </p>

```<code>int main () {
    double a,b,increment,para;
    int N;
    cout<< "enter values for (a,b,N)";
    cin>>a;
    cin>>b;
    cin>>N;
    increment= (b-a)/(N-1);
    double sivalues[N];
    for (double x=a;x<=b;x+=increment){
        sivalues[x]=si(x);
        cout<<"si("<<x<<") = "<< sivalues[x];
    }

    system("PAUSE"); return 0;

}
</code>```

答:
When you write sivalues[x], you are using a double as an array index. This is not valid, as it would make no sense to get the 2.5th element of an array, for instance. You would therefore need to cast your double into a int.

You could use the default cast (for example : sivalues[int(x)]=si(x);. Do note that this cast does not round, so if x is 5.99, it will still be converted to 5 (see C++: How to round a double to an int?)

Title: getting invalid errors for array type

Body:
getting an invalid array type in the for loop not allowing me to fill the array sivalues. it wont poulate the array with x

int main () {
    double a,b,increment,para;
    int N;
    cout<< "enter values for (a,b,N)";
    cin>>a;
    cin>>b;
    cin>>N;
    increment= (b-a)/(N-1);
    double sivalues[N];
    for (double x=a;x<=b;x+=increment){
        sivalues[x]=si(x);
        cout<<"si("<<x<<") = "<< sivalues[x];
    }

    system("PAUSE"); return 0;

}


问:
javascript not running onBlur
The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here.  Just trying to test a simply validation.

```<code>   <div class="cell">
   <label>DOB</label><br>
   <input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">
   </div>

   <script type="text/javascript">

 function checkForm(form)
 {
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

if(form.dob.value != '' && !form.dob.value.match(re)) {
  alert("Invalid date format: " + form.dob.value);
  form.dob.focus();
  return false;
}

alert("All input fields have been validated!");
return true;
 }
</code>```

答:
```<code> <div class="cell">
   <label>DOB</label><br>
   <input id="startdate" type="text" placeholder="01/01/1980" onblur="checkForm()">
   <script>
    function checkForm()
 {
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
var date = document.getElementById("startdate").value;
alert(date);
if(date != '' && !date.match(re)) {
  alert("Invalid date format: " + date);
  date.focus();
  return false;
}
alert("All input fields have been validated!");
return true;
 }
   </script>
   </div>
</code>```

Title: javascript not running onBlur

Body:
The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here.  Just trying to test a simply validation.

   DOB

   <input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">