问:
Ruby on Rails server setup
I'm trying to deploy ROR application to Ubuntu server(EC2).
I'm using following versions:

Ruby : 2.4.0p0

Rails : 4.2.8

Bundler : 1.17.3

*For some reason my colleague has created a gemset instead of normal setup.

gem env is:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.8
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
  - USER INSTALLATION DIRECTORY: /home/ubuntu/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
  - SPEC CACHE DIRECTORY: /home/ubuntu/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global/bin
     - /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin
     - /home/ubuntu/.rvm/bin
     - /home/ubuntu/bin
     - /home/ubuntu/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

</code>```

I did the setup of nginx and passenger and set the root paths.

nginx version: nginx/1.17.3

Phusion Passenger : 6.0.4

I believe there is nothing wrong with nginx and passenger's settings but I'm getting following error:
The Phusion Passenger application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error.

Error details:

```<code>cannot load such file -- bundler/setup (LoadError)
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'
</code>```

The stdout/stderr output of the subprocess so far is:

```<code> [passenger_native_support.so] trying to compile for the current user (nobody) and Ruby interpreter...
     (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
     Warning: compilation didn't succeed. To learn why, read this file:
     /tmp/passenger_native_support-18gfm98.log
 [passenger_native_support.so] finding downloads for the current Ruby interpreter...
     (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
     Could not download https://github.com/phusion/passenger/releases/download/release-6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 403 Forbidden
 [passenger_native_support.so] will not be used (can't compile or download)
  --> Passenger will still operate normally.
Error: The application encountered the following error: cannot load such file -- bundler/setup (LoadError)
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'
</code>```

Does anybody has any idea?

答:
passenger is trying to download a file that does not exist.

try with ruby 2.4.6 since that version is listed on the github release page

https://github.com/phusion/passenger/releases/

Title: Ruby on Rails server setup

Body:
I'm trying to deploy ROR application to Ubuntu server(EC2).
I'm using following versions:

Ruby : 2.4.0p0

Rails : 4.2.8

Bundler : 1.17.3

*For some reason my colleague has created a gemset instead of normal setup.

gem env is:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.8
  - RUBY VERSION: 2.4.0 (2016-12-24 patchlevel 0) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
  - USER INSTALLATION DIRECTORY: /home/ubuntu/.gem/ruby/2.4.0
  - RUBY EXECUTABLE: /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
  - SPEC CACHE DIRECTORY: /home/ubuntu/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@myrepo/bin
     - /home/ubuntu/.rvm/gems/ruby-2.4.0@global/bin
     - /home/ubuntu/.rvm/rubies/ruby-2.4.0/bin
     - /home/ubuntu/.rvm/bin
     - /home/ubuntu/bin
     - /home/ubuntu/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

I did the setup of nginx and passenger and set the root paths.

nginx version: nginx/1.17.3

Phusion Passenger : 6.0.4

I believe there is nothing wrong with nginx and passenger's settings but I'm getting following error:
The Phusion Passenger application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error.

Error details:

cannot load such file -- bundler/setup (LoadError)
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `'

The stdout/stderr output of the subprocess so far is:

 [passenger_native_support.so] trying to compile for the current user (nobody) and Ruby interpreter...
     (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
     Warning: compilation didn't succeed. To learn why, read this file:
     /tmp/passenger_native_support-18gfm98.log
 [passenger_native_support.so] finding downloads for the current Ruby interpreter...
     (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
     Could not download https://github.com/phusion/passenger/releases/download/release-6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
     Trying next mirror...
     Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/6.0.4/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 403 Forbidden
 [passenger_native_support.so] will not be used (can't compile or download)
  --> Passenger will still operate normally.
Error: The application encountered the following error: cannot load such file -- bundler/setup (LoadError)
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /home/ubuntu/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:363:in `activate_gem'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:221:in `block in run_load_path_setup_code'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:527:in `running_bundler'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:220:in `run_load_path_setup_code'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:91:in `preload_app'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:189:in `block in <module:App>'
    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:380:in `run_block_and_record_step_progress'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:188:in `<module:App>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `'

Does anybody has any idea?


来源: stackexchange

问:
'mvn' is not recognized as an internal or external command, operable program or batch file
May be question is asked before but i found very strange kind of error.
When I run mvn --version command from bin its gives the version and the other information. However when I run outside bin it gives exception. Both the result mention below

```<code>C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin>mvn --version
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:
28+0530)
Maven home: C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5>mvn --version
'mvn' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Also i set JAVA_HOME in user variable and M2_HOME, M2 in system environment variable. The output for these variables and %path% is:

```<code>C:\Users\SAHILBHALLA>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.7.0_25

C:\Users\SAHILBHALLA>echo %M2%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin

C:\Users\SAHILBHALLA>echo %M2_HOME%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5

C:\Users\SAHILBHALLA>echo %path%
C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPow erShell\v1.0\;C:\Program Files\Java\jdk1.7.0_25\bin;.;
</code>```

Tell me where i am wrong. What should i do recover from it?

答:
To solve this problem please follow the steps below:

Download the maven zip file from
http://maven.apache.org/download.cgi

Extract the maven zip file

Open the environment variable and in user variable section click on new button and make a variable called MAVEN_HOME and assign it the value of bin path of extracted maven zip

Now in System Variable click on Path and click on Edit button --> Now Click on New button and paste the bin path of maven zip

Now click on OK button

Open CMD and type mvn -version

Installed Maven version will be displayed and your setup is completed

ContentLicense: CC BY-SA 4.0

Body:
May be question is asked before but i found very strange kind of error.
When I run mvn --version command from bin its gives the version and the other information. However when I run outside bin it gives exception. Both the result mention below

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin>mvn --version
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:
28+0530)
Maven home: C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5>mvn --version
'mvn' is not recognized as an internal or external command,
operable program or batch file.

Also i set JAVA_HOME in user variable and M2_HOME, M2 in system environment variable. The output for these variables and %path% is:

C:\Users\SAHILBHALLA>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.7.0_25

C:\Users\SAHILBHALLA>echo %M2%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5\bin

C:\Users\SAHILBHALLA>echo %M2_HOME%
C:\Program Files\apache-maven-3.0.5-bin\apache-maven-3.0.5

C:\Users\SAHILBHALLA>echo %path%
C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPow erShell\v1.0\;C:\Program Files\Java\jdk1.7.0_25\bin;.;

Tell me where i am wrong. What should i do recover from it?


问:
ASIHTTPRequest in iOS
I have been using ASIHTTPRequest for an application but it gives me error in topSecretFetchFailed method 5 out of 10 request, Not sure how to deal with it, Isn't ASIHTTPRequest stable enough?

```<code>[request setDidFailSelector:@selector(topSecretFetchFailed:)];
</code>```

EDIT:

This is my code or method which get called in each request. MARKET_INDEXES_URL its static string which has "someurl.com";

```<code>- (void)requestData {
   ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:MARKET_INDEXES_URL]];
   [req setDelegate:self];
   [req setDidFailSelector:@selector(topSecretFetchFailed:)];
   [req setDidFinishSelector:@selector(topSecretFetchComplete:)];
   [self setRequest:req];
   [self.request startAsynchronous];
}
</code>```

and this is the fail handler

```<code>- (void)topSecretFetchFailed:(ASIHTTPRequest *)theRequest {
   [[NSNotificationCenter defaultCenter] postNotificationName:@"MarketIndexesError" object:nil];
   UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"Connection error, Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [view show];
  [view release];
  NSLog(@"MarketIndex service Fail: %d %@", [theRequest responseStatusCode], [theRequest responseStatusMessage]);
}
</code>```

答:
What you need is some reporting of the response details. Without that, you're diagnosing in the dark. Put this in your failure handler:</p>

```<code>NSLog(@"Fail: %d %@", [request responseStatusCode], [request responseStatusMessage]);
</code>```

ContentLicense: CC BY-SA 3.0

Title: ASIHTTPRequest in iOS

Body:
I have been using ASIHTTPRequest for an application but it gives me error in topSecretFetchFailed method 5 out of 10 request, Not sure how to deal with it, Isn't ASIHTTPRequest stable enough?

[request setDidFailSelector:@selector(topSecretFetchFailed:)];

EDIT:

This is my code or method which get called in each request. MARKET_INDEXES_URL its static string which has "someurl.com";

- (void)requestData {
   ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:MARKET_INDEXES_URL]];
   [req setDelegate:self];
   [req setDidFailSelector:@selector(topSecretFetchFailed:)];
   [req setDidFinishSelector:@selector(topSecretFetchComplete:)];
   [self setRequest:req];
   [self.request startAsynchronous];
}

and this is the fail handler

- (void)topSecretFetchFailed:(ASIHTTPRequest *)theRequest {
   [[NSNotificationCenter defaultCenter] postNotificationName:@"MarketIndexesError" object:nil];
   UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"Connection error, Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [view show];
  [view release];
  NSLog(@"MarketIndex service Fail: %d %@", [theRequest responseStatusCode], [theRequest responseStatusMessage]);
}

Body:
What you need is some reporting of the response details. Without that, you're diagnosing in the dark. Put this in your failure handler:

NSLog(@"Fail: %d %@", [request responseStatusCode], [request responseStatusMessage]);


问:
Footer exceeding width of screen with sliding vertical navbar
So I have a vertical sliding navbar and the rest of the content flows next to it with right width. Although, I am having a lot of trouble with the footer. I want it to sit at the bottom of the page regardless of how much content is on the page.

```<code>   <footer class="container">
      <div class="row">
         <div class="col-md-3">
            <a href="">link</a>
         </div>
         <div class="col-md-3">
            <a href="">link</a>
         </div>
      </div>
   </footer>

   //css
   html {
    position: relative;
    min-height: 100%;
    padding-bottom: 80px;
   }

   .legal {
    position: absolute;
    bottom: 0px;
    height: 80px;
    width: 100%;
    margin: 0;
   }
</code>```

Because I want the footer sitting at the bottom ive set it to absolute, but because its inheriting its width from the content above and being pushed across from the navbar its exceeding the screen by the width of the navbar. But if I was to set a left margin for it when the navbar collapsed with the screen size changing it will still sit with the margin and be out of position. Is there anyway to have it still sit at the bottom without making it absolute? Even with the content above set to 100% height when I make it relative it still isn't at the bottom.
Any help would be appreciated.

答:
Since you didn't provide many details about the code or any screenshot of the problem, I can't really tell you how you can fix the overflowing width issue but here are something you can try:

Try setting box-sizing to border-box

To make the footer stick to the bottom, you can try multiple options like, making the position fixed and bottom 0 and adding a bottom margin to the rest of the upper content to which should exactly be equal to the max height of the footer.

You can move everything in a flex container and only make the content area scrollable with the overflow property with flex set to 1 (flex: 1; flex-flow: column).

You can set the height of the content container to 100vh so it will always be expanded and will keep the footer to the bottom.

For the width overflow issue, try making sure the text is using "white-space: nowrap" property so it won't set footer items min-width to the text width. Or, try setting overflow X / Y to hidden so the expanded content doesn't show outside the container. If you're using flex, try using Flex-wrap so Flex can automatically adust the component to the container's width.

Hope it helps!

Body:
So I have a vertical sliding navbar and the rest of the content flows next to it with right width. Although, I am having a lot of trouble with the footer. I want it to sit at the bottom of the page regardless of how much content is on the page.

            link

            link

   //css
   html {
    position: relative;
    min-height: 100%;
    padding-bottom: 80px;
   }

   .legal {
    position: absolute;
    bottom: 0px;
    height: 80px;
    width: 100%;
    margin: 0;
   }

Because I want the footer sitting at the bottom ive set it to absolute, but because its inheriting its width from the content above and being pushed across from the navbar its exceeding the screen by the width of the navbar. But if I was to set a left margin for it when the navbar collapsed with the screen size changing it will still sit with the margin and be out of position. Is there anyway to have it still sit at the bottom without making it absolute? Even with the content above set to 100% height when I make it relative it still isn't at the bottom.
Any help would be appreciated.


问:
Using React to create a form, how could I get my err message to display on Submit (when the submit button is clicked)?
I am using React to create a form with two input text and would like to display an error message every time the user enters a non-numerical value as the age and clicks the submit button. The form apparently is doing most of what I want but it is not displaying the error message.

NB: I would love not to use the alert() syntax here if possible.

Thanks for your help.

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
      errormessage: ''
    };
  }

 errorHandler = () => {
  let err = '';
  if (nam === "age") {
    if (val !="" && !Number(val)) {
      err = Your age must be a number;
    }
  }
  this.setState({errormessage: err});
 }

  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }

  render() {
    return (
      <form onSubmit={this.errorHandler}>

Hello {this.state.username} {this.state.age}

Enter your name:

      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />

Enter your age:

      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />

      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div></code>```

答:
There is a problem with your errorHander method. The nam and val variables in your onChangeHandler() are using let and therefore, its having local scope only. I'll suggest you to bring nam and age from your state in errorHandler.

```<code>import ReactDOM from 'react-dom';
import React, { Component } from 'react';

class MyForm extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     username: '',
     age: null,
     errormessage: ''
   };
 }

 myChangeHandler = (event) => {
   let nam = event.target.name;
   let val = event.target.value;
   this.setState({[nam]: val});
 }

errorHandler = () => {
 let err = '';
 let val = this.state.age
   if (val !="" && !Number(val)) {
     err = <strong>Your age must be a number</strong>;
 }
 this.setState({errormessage: err});
}

 render() {
   return (
     <form onSubmit={this.errorHandler}>
     <h1>Hello {this.state.username} {this.state.age}</h1>
     <p>Enter your name:</p>
     <input
       type='text'
       name='username'
       onChange={this.myChangeHandler}
     />
     <p>Enter your age:</p>
     <input
       type='text'
       name='age'
       onChange={this.myChangeHandler}
     />
     <br/>
     <input
       type='submit'
     />
     {this.state.errormessage}
     </form>
   );
 }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
</code>```

Body:
There is a problem with your errorHander method. The nam and val variables in your onChangeHandler() are using let and therefore, its having local scope only. I'll suggest you to bring nam and age from your state in errorHandler.

import ReactDOM from 'react-dom';
import React, { Component } from 'react';

class MyForm extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     username: '',
     age: null,
     errormessage: ''
   };
 }

 myChangeHandler = (event) => {
   let nam = event.target.name;
   let val = event.target.value;
   this.setState({[nam]: val});
 }

errorHandler = () => {
 let err = '';
 let val = this.state.age
   if (val !="" && !Number(val)) {
     err = <strong>Your age must be a number</strong>;
 }
 this.setState({errormessage: err});
}

 render() {
   return (
     <form onSubmit={this.errorHandler}>
     <h1>Hello {this.state.username} {this.state.age}</h1>
     <p>Enter your name:</p>
     <input
       type='text'
       name='username'
       onChange={this.myChangeHandler}
     />
     <p>Enter your age:</p>
     <input
       type='text'
       name='age'
       onChange={this.myChangeHandler}
     />
     <br/>
     <input
       type='submit'
     />
     {this.state.errormessage}
     </form>
   );
 }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));


问:
Yoxview make crash IE7
I have a photo/video gallery and I apply the Yoxview jquery plugin on. On every browser their is no problem except for IE7.

I try to update my code to the latest version of the plugin but it does not helped.

The strange part is that I go on the Yoxview site, IE7 doest not crash.

This is the code is use:

```<code>$(".Gallery").yoxview();
</code>```

.Gallery is a div with nested a that contains img.

Do anybody have encounter this situation before me?

NOTE: The problem exist even if their is only 1 image on the page.

答:
I change my Jquery version. The version 1.6 seam to cause the problem. I try with the 1.4 and the plugin work perfectly. So, I got to the Jquery site and download the latest version of Jquery (1.6.1) and everything is now ok.

Thank for you help guys!

Title: Yoxview make crash IE7

Body:
I have a photo/video gallery and I apply the Yoxview jquery plugin on. On every browser their is no problem except for IE7.

I try to update my code to the latest version of the plugin but it does not helped.

The strange part is that I go on the Yoxview site, IE7 doest not crash.

This is the code is use:

$(".Gallery").yoxview();

.Gallery is a div with nested a that contains img.

Do anybody have encounter this situation before me?

NOTE: The problem exist even if their is only 1 image on the page.


问:
Create data file by Automake
I want Automake to create an .img file in my hobby project (to test the compiled program in a virtual machine).

I can use Automake to compile programs, eg.:

```<code>noinst_PROGRAMS = loader.elf

loader_elf_SOURCES = init.s console.c disk.c elf.c ext2.c fat.c lib.c loader.c multiboot.c
loader_elf_LDFLAGS = $(AM_LDFLAGS) -T $(srcdir)/loader.ld
loader_elf_LDADD = $(LDADD) -lgcc

</code>```

But it doesn't work for data files:

```<code>noinst_DATA = x.img
x_img_DEPENDENCIES = loader.elf
x_img_LINK = makeimg.sh
</code>```

When I execute autoreconf -i then I get this error message:

```<code>automake: warnings are treated as errors
arch/i386/emulator/Makefile.am:14: warning: variable 'x_img_DEPENDENCIES' is defined but no program or
arch/i386/emulator/Makefile.am:14: library has 'x_img' as canonical name (possible typo)
autoreconf: automake failed with exit status: 1
</code>```

I'm trying to turn my Makefile into Makefile.am. It was as simle in Makefile as:

```<code>x.img: loader.elf
    makeimg.sh $@ $<
</code>```

I studied the Automake manual at the gnu ftp page, and I think there is no possibility to add sources or dependencies to a DATA file in Automake. What should I do? Should I put the .img file into the PROGRAMS primary instead of DATA?

I'm using Automake 1.16.1 and Autoconf 2.69 (if that matters).

答:
Simply add this to the Makefile.am:

```<code>noinst_PROGRAMS = loader.elf
loader_elf_SOURCES = ...

noinst_DATA = x.img
x.img: loader.elf
    makeimg.sh x.img loader.elf
</code>```

(I have changed the $@ and $< to use the explicit names as there are apparently some versions of make which have difficulties with $@ and $< in rules which are defined by explicit file names, instead of by patterns or suffixes.)

Title: Create data file by Automake

Body:
I want Automake to create an .img file in my hobby project (to test the compiled program in a virtual machine).

I can use Automake to compile programs, eg.:

noinst_PROGRAMS = loader.elf

loader_elf_SOURCES = init.s console.c disk.c elf.c ext2.c fat.c lib.c loader.c multiboot.c
loader_elf_LDFLAGS = $(AM_LDFLAGS) -T $(srcdir)/loader.ld
loader_elf_LDADD = $(LDADD) -lgcc

But it doesn't work for data files:

noinst_DATA = x.img
x_img_DEPENDENCIES = loader.elf
x_img_LINK = makeimg.sh

When I execute autoreconf -i then I get this error message:

automake: warnings are treated as errors
arch/i386/emulator/Makefile.am:14: warning: variable 'x_img_DEPENDENCIES' is defined but no program or
arch/i386/emulator/Makefile.am:14: library has 'x_img' as canonical name (possible typo)
autoreconf: automake failed with exit status: 1

I'm trying to turn my Makefile into Makefile.am. It was as simle in Makefile as:

x.img: loader.elf
    makeimg.sh $@ $<

I studied the Automake manual at the gnu ftp page, and I think there is no possibility to add sources or dependencies to a DATA file in Automake. What should I do? Should I put the .img file into the PROGRAMS primary instead of DATA?

I'm using Automake 1.16.1 and Autoconf 2.69 (if that matters).

Body:
Simply add this to the Makefile.am:

noinst_PROGRAMS = loader.elf
loader_elf_SOURCES = ...

noinst_DATA = x.img
x.img: loader.elf
    makeimg.sh x.img loader.elf

(I have changed the $@ and $< to use the explicit names as there are apparently some versions of make which have difficulties with $@ and $< in rules which are defined by explicit file names, instead of by patterns or suffixes.)


问:
Show x-Axis line but hide all data points
I want the second datetime x-Axis to show, but I want none of the points from that series to be visible. I just want the x-Axis line. How can I do this?

```<code> Highcharts.chart("container", {
      chart: {
        type: "line",
      },
      xAxis: [
        {
          type: "category"
        },
        {
          type: "datetime",
        }
      ]
    });
</code>```

https://codepen.io/austeng/pen/mdJrRRm

Edit: I want the black line to be gone, but I want to keep the Date x-Axis line. The black line are the points from the date x-Axis. I just the date x-Axis grid line to show... not the points associated with it.

答:
```<code>data: [],
</code>```

I hope it helps if you want something like as below!!

Body:
I want the second datetime x-Axis to show, but I want none of the points from that series to be visible. I just want the x-Axis line. How can I do this?

 Highcharts.chart("container", {
      chart: {
        type: "line",
      },
      xAxis: [
        {
          type: "category"
        },
        {
          type: "datetime",
        }
      ]
    });

https://codepen.io/austeng/pen/mdJrRRm

Edit: I want the black line to be gone, but I want to keep the Date x-Axis line. The black line are the points from the date x-Axis. I just the date x-Axis grid line to show... not the points associated with it.

Body:
data: [],

I hope it helps if you want something like as below!!


问:
What are all these deprecated "loop" parameters in asyncio?
A lot of the functions in asyncio have deprecated loop parameters, scheduled to be removed in Python 3.10. Examples include as_completed(), sleep(), and wait().

I'm looking for some historical context on these parameters and their removal.

What problems did loop solve? Why would one have used it in the first place?

What was wrong with loop? Why is it being removed en masse?

What replaces loop, now that it's gone?

答:
The loop parameter was the way to pass the global event loop around. New implementations of the same functions no longer require you to pass the global event loop, they instead just request it where it's needed.

As the documentation suggests https://docs.python.org/3/library/asyncio-eventloop.html: "Application developers should typically use the high-level asyncio functions, such as asyncio.run(), and should rarely need to reference the loop object or call its methods."

Removing the need for you to pass it around to library functions aligns with that principle. The loop is not replaced, but its disappearance simply means you no longer have to deal with it 'manually'.


问:
indexOf issues with Array when loading list from .txt file
I'm working on a fairly simple web application that accepts user input in either number or word form. The basic premise behind this is I need to find the word in the array if I start with the number and/or the index number of the word if I start with the word. I have created a function that can do both. The only catch is, if I don't manually type out the list like let generic_list = ["Item1", "Item2", "Item3"];, the index isn't found when trying to load it from the text file.

The code I am using to load the text file is:

```<code>$.get("list.txt", function(data) {
    let list_loaded = data.split("\n");
})
</code>```

This is the code that I'm using to find the index that works if I manually make the list.

```<code>let item_index = list_loaded.indexOf(item_index_im_searching_for);
</code>```

When I manually create the list, the return value will be the proper index number. If the text file loads the list the value will return -1 undefined. I've done some reading around, but I'm not exactly sure what I'm missing. Hoping some of you JavaScript vets can lead me to the right direction.

Also, when testing in the console, both lists appear to exactly the same.

答:
Check JSFiddle for details related to javascript indexOf method: https://jsfiddle.net/ecx8Lhtj/

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
var htmlText = "
Finding position of the first occurrence for word welcome from string is at "+ n +"
";

str = str.split(" ");
htmlText += "
Array Elements="+ str +"
";
htmlText += "
Also check CONSOLE for seeing array elements.
";
console.log(str);
n = str.indexOf("welcome");
htmlText += "
a. Finding position of the first occurrence for word welcome from array elements is at "+ n +"
";

n = str.indexOf("world");
htmlText += '
b. Finding position of the first occurrence for word welcome from array elements is at "world" '+ n +'
';

n = str.indexOf("world,");
htmlText += '
b. Finding position of the first occurrence for word welcome from array elements is at "world," '+ n +'
';

document.getElementById("displayText").innerHTML = htmlText;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>JavaScript String indexOf() Method, reference URL: https://www.w3schools.com/jsref/jsref_indexof.asp</p>
<p><h3>Definition and Usage</h3></p>
<p>The indexOf() method returns the position of the first occurrence of a specified value in a string.</p>
<p>This method returns -1 if the value to search for never occurs.</p>
<p><b>Note</b>: The indexOf() method is case sensitive.</p>
<p>Whenever indexOf used with array elements, it will try to find searching text as a complete text against each element from an array. If such match found then only it will return an index otherwise it will return -1.</p>
<p>Please see below examples:</p>
<p id="displayText"></p></code>```

Whenever we are using javascript indexOf method against an array, then it will try to find a searching string as an exact match against each element of an array. And if exact match found then only it will return proper index value else it will return -1.

Body:
I'm working on a fairly simple web application that accepts user input in either number or word form. The basic premise behind this is I need to find the word in the array if I start with the number and/or the index number of the word if I start with the word. I have created a function that can do both. The only catch is, if I don't manually type out the list like let generic_list = ["Item1", "Item2", "Item3"];, the index isn't found when trying to load it from the text file.

The code I am using to load the text file is:

$.get("list.txt", function(data) {
    let list_loaded = data.split("\n");
})

This is the code that I'm using to find the index that works if I manually make the list.

let item_index = list_loaded.indexOf(item_index_im_searching_for);

When I manually create the list, the return value will be the proper index number. If the text file loads the list the value will return -1 undefined. I've done some reading around, but I'm not exactly sure what I'm missing. Hoping some of you JavaScript vets can lead me to the right direction.

Also, when testing in the console, both lists appear to exactly the same.

Body:
Check JSFiddle for details related to javascript indexOf method: https://jsfiddle.net/ecx8Lhtj/

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
var htmlText = "<p>Finding position of the first occurrence for word welcome from string is at "+ n +"</p>";

str = str.split(" ");
htmlText += "<p>Array Elements="+ str +"</p>";
htmlText += "<p>Also check CONSOLE for seeing array elements.</p>";
console.log(str);
n = str.indexOf("welcome");
htmlText += "<p>a. Finding position of the first occurrence for word welcome from array elements is at "+ n +"</p>";

n = str.indexOf("world");
htmlText += '<p>b. Finding position of the first occurrence for word welcome from array elements is at "world" '+ n +'</p>';

n = str.indexOf("world,");
htmlText += '<p>b. Finding position of the first occurrence for word welcome from array elements is at "world," '+ n +'</p>';

document.getElementById("displayText").innerHTML = htmlText;

<p>JavaScript String indexOf() Method, reference URL: https://www.w3schools.com/jsref/jsref_indexof.asp</p>
<p><h3>Definition and Usage</h3></p>
<p>The indexOf() method returns the position of the first occurrence of a specified value in a string.</p>
<p>This method returns -1 if the value to search for never occurs.</p>
<p><b>Note</b>: The indexOf() method is case sensitive.</p>
<p>Whenever indexOf used with array elements, it will try to find searching text as a complete text against each element from an array. If such match found then only it will return an index otherwise it will return -1.</p>
<p>Please see below examples:</p>
<p id="displayText"></p>

Whenever we are using javascript indexOf method against an array, then it will try to find a searching string as an exact match against each element of an array. And if exact match found then only it will return proper index value else it will return -1.


问:
java dyn parser
Im a novice java-programer, whos trying to create a small java app.

In the program im working on, I want to load the configurations from different ini-files.
The basic idea is, that I would have a library containing all the config files, the parser should read all of them and make configurations named after their filenames.
The parser should be created to work dynamicly, so it can read different types of configs.
example

```<code>House.ini
 -> type0
 -> id  name  height  witdh  length   price_based_on_dimensions
 -> id1  name1  height  witdh  length   price_based_on_dimensions
</code>```

These data should be saved to a config object named config.house. The tricky part is that a different config file, can have its type = type0 but with a different number of attributtes.

I realise that there is no simply solution to this, but any help and or guides to create a dynamic parser is welcome

答: Other then ini4j (which is a really good library) I personally prefer to use xml config files.  To me they are easier to use and allow for easier configuration</p>

Title: java dyn parser

Body:
Im a novice java-programer, whos trying to create a small java app.

In the program im working on, I want to load the configurations from different ini-files.
The basic idea is, that I would have a library containing all the config files, the parser should read all of them and make configurations named after their filenames.
The parser should be created to work dynamicly, so it can read different types of configs.
example

House.ini
 -> type0
 -> id  name  height  witdh  length   price_based_on_dimensions
 -> id1  name1  height  witdh  length   price_based_on_dimensions

These data should be saved to a config object named config.house. The tricky part is that a different config file, can have its type = type0 but with a different number of attributtes.

I realise that there is no simply solution to this, but any help and or guides to create a dynamic parser is welcome


问:
How to use switch statement inside a React component?
I have a React component, and inside the render method of the component I have something like this:

```<code>render() {
    return (
        <div>
            <div>
                // removed for brevity
            </div>

           { switch(...) {} }

            <div>
                // removed for brevity
            </div>
        </div>
    );
}
</code>```

Now the point is that I have two div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?

答:
I'm not a big fan of any of the current answers, because they are either too verbose, or require you to jump around the code to understand what is going on.

I prefer doing this in a more react component centred way, by creating a <Switch/>. The job of this component is to take a prop, and only render children whose child prop matches this one. So in the example below I have created a test prop on the switch, and compared it to a value prop on the children, only rendering the ones that match.

Example:

const Switch = props => {
  const { test, children } = props
  // filter out only children with a matching prop
  return children.find(child => {
    return child.props.value === test
  })
}

const Sample = props => {
  const someTest = true
  return (
    <Switch test={someTest}>

Will display if someTest is false

Will display if someTest is true

    </Switch>
  )
}

ReactDOM.render(
  <Sample/>,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

You can make the switch as simple or as complex as you want. Don't forget to perform more robust checking of the children and their value props.

Body:
I have a React component, and inside the render method of the component I have something like this:

render() {
    return (

                // removed for brevity

           { switch(...) {} }

                // removed for brevity

    );
}

Now the point is that I have two div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?

Body:
I'm not a big fan of any of the current answers, because they are either too verbose, or require you to jump around the code to understand what is going on.

I prefer doing this in a more react component centred way, by creating a <Switch/>. The job of this component is to take a prop, and only render children whose child prop matches this one. So in the example below I have created a test prop on the switch, and compared it to a value prop on the children, only rendering the ones that match.

Example:

const Switch = props => {
  const { test, children } = props
  // filter out only children with a matching prop
  return children.find(child => {
    return child.props.value === test
  })
}

const Sample = props => {
  const someTest = true
  return (
    <Switch test={someTest}>
      <div value={false}>Will display if someTest is false</div>
      <div value={true}>Will display if someTest is true</div>
    </Switch>
  )
}

ReactDOM.render(
  <Sample/>,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

You can make the switch as simple or as complex as you want. Don't forget to perform more robust checking of the children and their value props.


问:
How to rollback stored procedure that updates a table
Why doesn't this ROLLBACK TRANSACTION statement work?

```<code>BEGIN TRANSACTION;
DECLARE @foo INT
EXECUTE [database].[dbo].[get_counter] @CounterID='inventory_records', @nextValue=@foo OUTPUT;
ROLLBACK TRANSACTION;
</code>```

Background

I'm inserting records into a customer's ERP system built on SQL Server 19. The ERP database doesn't have auto-incrementing primary keys. It instead uses a table called counters where each row has a counterID field and an integer value field.

To insert a new row into a table like inventory_record, I first need to call a stored procedure like this:

EXECUTE get_counter @counterID='inventory_record'

This procedure returns an OUT parameter called @nextValue which I then INSERT into the inventory_record table as its uid.

I need to ROLLBACK this stored procedure's behavior if my insert fails. That way the counter doesn't increase boundlessly on failed INSERT attempts.

Contents of get_counter stored procedure

It's dirt simple but also subject to copyright. I've summarized and truncated here. The counters are stored as sequences in the DB. So get_counter calls sp_sequence_get_range after checking that the requested counter is legitimate.

```<code>ALTER PROCEDURE get_counter
    @strCounterID varchar(64),
    @iIncrementValue integer = 1,
    @LastValue BIGINT = NULL OUTPUT
AS

SET NOCOUNT ON
BEGIN

DECLARE
          @nextSeqVar SQL_VARIANT
        , @lastSeqVar SQL_VARIANT

-- code that confirms valid counter name

BEGIN TRY
    -- code that calls [sp_sequence_get_range]
END TRY
BEGIN CATCH
    THROW
END CATCH

RETURN(@LastValue)
END
</code>```

The Problem

The inventory_record counter always increments. I can't roll it back.

If I run the SQL at the top of this question from SSMS, then SELECT value FROM counters WHERE counterID = 'inventory_record', the counter increments each time I execute.

I'm new to transaction handling in SQL Server. Any ideas what I'm missing?

答:
re-post comments as answer for better readability.

The get_counter is using Sequence Numbers (sp_sequence_get_range). Please refer to documentation on Limitation section.

Sequence numbers are generated outside the scope of the current
  transaction. They are consumed whether the transaction using the
  sequence number is committed or rolled back

You may see a simple demo here

Body:
Why doesn't this ROLLBACK TRANSACTION statement work?

BEGIN TRANSACTION;
DECLARE @foo INT
EXECUTE [database].[dbo].[get_counter] @CounterID='inventory_records', @nextValue=@foo OUTPUT;
ROLLBACK TRANSACTION;

Background

I'm inserting records into a customer's ERP system built on SQL Server 19. The ERP database doesn't have auto-incrementing primary keys. It instead uses a table called counters where each row has a counterID field and an integer value field.

To insert a new row into a table like inventory_record, I first need to call a stored procedure like this:

EXECUTE get_counter @counterID='inventory_record'

This procedure returns an OUT parameter called @nextValue which I then INSERT into the inventory_record table as its uid.

I need to ROLLBACK this stored procedure's behavior if my insert fails. That way the counter doesn't increase boundlessly on failed INSERT attempts.

Contents of get_counter stored procedure

It's dirt simple but also subject to copyright. I've summarized and truncated here. The counters are stored as sequences in the DB. So get_counter calls sp_sequence_get_range after checking that the requested counter is legitimate.

ALTER PROCEDURE get_counter
    @strCounterID varchar(64),
    @iIncrementValue integer = 1,
    @LastValue BIGINT = NULL OUTPUT
AS

SET NOCOUNT ON
BEGIN

DECLARE
          @nextSeqVar SQL_VARIANT
        , @lastSeqVar SQL_VARIANT

-- code that confirms valid counter name

BEGIN TRY
    -- code that calls [sp_sequence_get_range]
END TRY
BEGIN CATCH
    THROW
END CATCH

RETURN(@LastValue)
END

The Problem

The inventory_record counter always increments. I can't roll it back.

If I run the SQL at the top of this question from SSMS, then SELECT value FROM counters WHERE counterID = 'inventory_record', the counter increments each time I execute.

I'm new to transaction handling in SQL Server. Any ideas what I'm missing?


问:
How to setup github with Visual Studio Code where there are already files present in the repo?
I've been trying to go through this tutorial: https://www.youtube.com/watch?v=ghL-KlAhBnc

But when I tried to push, after following everything, I got the following problem: cant push refs to remote. try running pull first...

I went to the menu in Source Control and tried the Pull option. I then got an error saying 'Git: There is no tracking information for the current branch'

Next, I found this solution to the issue: There is no tracking information for the current branch

The problem is, since I am working with a tutorial in VS code, I don't think I can do that, because I get the 'fatal: not a git repository (or any of the parent directories): .git

How would I go about solving my original issue in VS code..?

To clarify, I am completely new with github. I used it with VS 2017 but when it worked it worked, I didn't have to worry about much. I have got git bash but not sure how to use it.

答:
At 12.05 mark in the video, pay attention to the initialization of a new GitHub repository: it must be empty.

If you create a GitHub repo with a README file, for instance, then it would have a commit of its own, hence your error message when doing your first push.

In your case, a simple git push --force would be enough.


问:
How to modify program to run until a certain key is entered
What is the best way to terminate this by entering a specific keyword or letter? Ideally want the program to terminate by entering a key followed by enter</p>

```<code>class NestedLoopTable {
    private int start;
    private int end;

    public NestedLoopTable() {
    }

    public NestedLoopTable(int aStart, int aEnd) {
        super();
        start = aStart;
        end = aEnd;
    }

    public void printTable() {
        // looping through the number of rows to print the table
        for (int i = start; i <= end - start + 1; i++) {
            for (int j = start; j <= i; j++)
                System.out.print(j + " ");
            System.out.println();
        }
    }
}
</code>```

```<code>import java.util.Scanner;

public class NestedLoopTableApp {
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start and end");
        int start = sc.nextInt();
        int end = sc.nextInt();

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        sc.close();
    }
}
</code>```

答:
You need a simple loop in for your program:

```<code>public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNext()) {
        int start = 0;
        while (true) {
            System.out.printf("Enter start or %s:\n", EXIT_KEYWORD);

            if(scanner.hasNextInt())
                start = scanner.nextInt();
            else if(scanner.next().equalsIgnoreCase(EXIT_KEYWORD))
                return;
        }

        int end = 0;
        while (true) {
            System.out.printf("Enter end or %s:\n", EXIT_KEYWORD);

            if(scanner.hasNextInt())
                end = scanner.nextInt();
            else if(scanner.next().equalsIgnoreCase(EXIT_KEYWORD))
                return;
        }

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        scanner.close();
    }
}
</code>```

(Actually this is just a sample code and you can employ other approaches with much cleaner interface and code!)

Body:
What is the best way to terminate this by entering a specific keyword or letter? Ideally want the program to terminate by entering a key followed by enter

class NestedLoopTable {
    private int start;
    private int end;

    public NestedLoopTable() {
    }

    public NestedLoopTable(int aStart, int aEnd) {
        super();
        start = aStart;
        end = aEnd;
    }

    public void printTable() {
        // looping through the number of rows to print the table
        for (int i = start; i <= end - start + 1; i++) {
            for (int j = start; j <= i; j++)
                System.out.print(j + " ");
            System.out.println();
        }
    }
}

import java.util.Scanner;

public class NestedLoopTableApp {
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start and end");
        int start = sc.nextInt();
        int end = sc.nextInt();

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        sc.close();
    }
}

Body:
You need a simple loop in for your program:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNext()) {
        int start = 0;
        while (true) {
            System.out.printf("Enter start or %s:\n", EXIT_KEYWORD);

            if(scanner.hasNextInt())
                start = scanner.nextInt();
            else if(scanner.next().equalsIgnoreCase(EXIT_KEYWORD))
                return;
        }

        int end = 0;
        while (true) {
            System.out.printf("Enter end or %s:\n", EXIT_KEYWORD);

            if(scanner.hasNextInt())
                end = scanner.nextInt();
            else if(scanner.next().equalsIgnoreCase(EXIT_KEYWORD))
                return;
        }

        NestedLoopTable np = new NestedLoopTable(start, end);
        np.printTable();
        scanner.close();
    }
}

(Actually this is just a sample code and you can employ other approaches with much cleaner interface and code!)


问:
Session attribute access and converting to int?
I have stored user id in Session using following command in Servlet:

```<code>HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
</code>```

Now, I want to access that user id from another Servlet:

```<code>HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
</code>```

Question:

How can I cast to int and send the id to DAO for SELECT statement

答:
Even if you saved an int, that method expects an Object so your int will become an Integer due to auto-boxing. Try to cast it back to Integer and it should be fine:

```<code>int userid = (Integer) session.getAttribute("user");
</code>```

However, if the attribute is null you will get a NullPointerException here, so maybe it's better to go with Integer all the way:

```<code>Integer userid = (Integer) session.getAttribute("user");
</code>```

After this, you can safely check if userid is null.

EDIT:
In response to your comments, here's what I mean by "check for null".

```<code>Integer userid = (Integer) session.getAttribute("user");
User user = null;
if (userid != null) {
    user = new UserDAO().getUser(userid);
}
// here user will be null if no userid has been stored on the session,
// and it wil be loaded from your persistence layer otherwise.
</code>```

Body:
I have stored user id in Session using following command in Servlet:

HttpSession session = request.getSession();
session.setAttribute("user", user.getId());

Now, I want to access that user id from another Servlet:

HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)

Question:

How can I cast to int and send the id to DAO for SELECT statement

Body:
Even if you saved an int, that method expects an Object so your int will become an Integer due to auto-boxing. Try to cast it back to Integer and it should be fine:

int userid = (Integer) session.getAttribute("user");

However, if the attribute is null you will get a NullPointerException here, so maybe it's better to go with Integer all the way:

Integer userid = (Integer) session.getAttribute("user");

After this, you can safely check if userid is null.

EDIT:
In response to your comments, here's what I mean by "check for null".

Integer userid = (Integer) session.getAttribute("user");
User user = null;
if (userid != null) {
    user = new UserDAO().getUser(userid);
}
// here user will be null if no userid has been stored on the session,
// and it wil be loaded from your persistence layer otherwise.


问:
Google Maps info Bubble With Font Awesome Icons and bootstrap?
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

```<code><a href="https://www.youtube.com/watch?v=u8iaZF-iFNk" target="_blank" class="list-group-item list-group-item-action"> <i class="fab fa-youtube"></i> Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)</a>
</code>```

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....

答:
You are follow FontAwesome v4.7.0 then you can't use fab class because of this is belong to FontAwesome v5+. So you just need to replace fab fa-youtube to fa fa-youtube.

function initMap() {
  var lakeShore = {lat: 47.7231, lng: 86.9407};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: lakeShore
  });

  var contentString = `
Lake Shore Trail

       Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)

`;

  var infowindow = new google.maps.InfoWindow({
    content: contentString,
    // maxWidth: 320
  });
  var marker = new google.maps.Marker({
    position: lakeShore,
    map: map,
    title: 'Lake Shore Trail'
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}
</script>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}</code>```

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

```

Body:
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

  Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....

Body:
You are follow FontAwesome v4.7.0 then you can't use fab class because of this is belong to FontAwesome v5+. So you just need to replace fab fa-youtube to fa fa-youtube.

function initMap() {
  var lakeShore = {lat: 47.7231, lng: 86.9407};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: lakeShore
  });

  var contentString = `<h6>Lake Shore Trail</h6>
   <div class="list-group">
     <a href="https://www.youtube.com/watch?v=u8iaZF-iFNk" target="_blank" class="list-group-item list-group-item-action"><i class="fa fa-youtube"></i>&nbsp; Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)</a>
   </div>`;

  var infowindow = new google.maps.InfoWindow({
    content: contentString,
    // maxWidth: 320
  });
  var marker = new google.maps.Marker({
    position: lakeShore,
    map: map,
    title: 'Lake Shore Trail'
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}
</script>

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div id="map"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>


问:
how to create arrayList for ListView SecondActivity
I created a List of String Array in the strings.xml so it can then be used in and Adapter, but I don't want the array stored in the string to be set as new-descriptive text when a listItemClick opens to a new activity.
Please help me. I want to create another list of array as full-description which should be different from the one tied to the row.

Let me describe what I mean furthermore.

My row.xml shows an Image, TextView as Title, & another TextView as description.
Now i have used this arrangement to generate constructor and getters for my Model.java

Now, if I click on a list of ListView items, it opens to a NewActivity.java there by feeding its data stored in string.xml as arrayList which is simply Title & description texts. But I want another text different from that discription  to show in that NewActivity.java as brand-new-descrption text. That is what I'm struggling to do now.

Thanks

this is the MainActivity.java code

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private String TAG = "MainActivity ----- ; " ;
    // Store instance variables

    private int page;
    private ConsentForm form;

    ListView listView;
    ListViewAdapter adapter;
    List<String> title, description2,description;
    int[] icon;
    int [] soundfile;
    ArrayList<Model> arrayList = new ArrayList<Model>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Redeemed Songs");

        //listview soundfile file for songs in position
        soundfile= new int[] {R.raw.song_1,R.raw.song_2,R.raw.song_3, R.raw.song_4,R.raw.song_5,R.raw.song_6,R.raw.song_7,R.raw.song_8,};

        title = Arrays.asList(getResources().getStringArray(R.array.array_titles));

        description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));
        description2 = Arrays.asList(getResources().getStringArray(R.array.array_lyrics2));

        icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song, R.drawable.song,};

        listView = findViewById(R.id.list);

        for (int i = 0; i< title.size(); i++){
            Model model =new Model(title.get(i), description.get(i),description2.get(i), icon[i]);
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass result to listview class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview class
        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    adapter.filter("");
                    listView.clearTextFilter();
                }
                else {
                    adapter.filter(s);
                }
                return true;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.action_settings){
            Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main2Activity.class));
            return true;
            //do your funtionality here

        }
        else if (id==R.id.action_howtouse){
                Toast.makeText(this, "How-To", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here

        }else if (id==R.id.action_favorites){
                Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here

        }
        else if (id==R.id.action_developers){
            Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main4Activity.class));
            return true;
            //do your funtionality here

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
}```
</div>
</div>
</p>

<p><strong>This is the ListViewAdapter.java</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class ListViewAdapter extends BaseAdapter{

    //Variables
    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;
    int [] soundfile;

    //Constructor
    public ListViewAdapter(Context context, List<Model> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder{
        TextView mTitleTv, mDescTv;
        ImageView mIconTv;
        MediaPlayer mediaPlayer;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, null);

            //locate the views in row.xml
            holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
            holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
            holder.mIconTv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);
        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the result into textview
        holder.mTitleTv.setText(modellist.get(i).getTitle());
        holder.mDescTv.setText(modellist.get(i).getDesc());
        //Set the result in imagview
        holder.mIconTv.setImageResource(modellist.get(i).getIcon());

        //listview soundfile file for songs in position
        soundfile= new int[] {R.raw.song_1,R.raw.song_2,R.raw.song_3, R.raw.song_4,R.raw.song_5,R.raw.song_6,R.raw.song_7,R.raw.song_8,};

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                Intent intent = new Intent(mContext, NewActivity.class);
                intent.putExtra("position", getViewTypeCount());
                intent.putExtra("actionBarTitle", modellist.get(i).getTitle());
                intent.putExtra("contentTv", modellist.get(i).getDesc());
                mContext.startActivity(intent);

            }
        });

        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (Model model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }

}</code>```

This is the String.xml

<resources>
    <string name="app_name">Redeemed Songs</string>

    <string-array name="array_lyrics">
        <item>This song lyrics 1</item>
        <item>This song lyrics 2</item>
    </string-array>

    <string-array name="array_lyrics2">
        <item>This brand new description for song lyrics 1</item>
        <item>This brand new description for song lyrics 1</item>
    </string-array>

    <string-array name="array_titles">
        <item>Song 001</item>
        <item>Song 002</item>
    </string-array>

</resources>```

答:
Add it to your Model as attribute

```<code>class Model{

your variable
.
.
.
String brandNewDesc;

public String getBrandNewDesc(){

return brandNewDesc;
}
public void setBrandNewDesc(String description){

brandNewDesc =description;
}

}
</code>```

and use

```<code>   //listview item clicks
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //code later
            Intent intent = new Intent(mContext, NewActivity.class);
            intent.putExtra("position", getViewTypeCount());
            intent.putExtra("actionBarTitle", modellist.get(i).getTitle());
            intent.putExtra("contentTv", modellist.get(i).getDesc());
            **intent.putExtra("brandNewDesc", modellist.get(i).getBrandNewDesc());**

            mContext.startActivity(intent);

        }
    });
</code>```

Body:
I created a List of String Array in the strings.xml so it can then be used in and Adapter, but I don't want the array stored in the string to be set as new-descriptive text when a listItemClick opens to a new activity.
Please help me. I want to create another list of array as full-description which should be different from the one tied to the row.

Let me describe what I mean furthermore.

My row.xml shows an Image, TextView as Title, & another TextView as description.
Now i have used this arrangement to generate constructor and getters for my Model.java

Now, if I click on a list of ListView items, it opens to a NewActivity.java there by feeding its data stored in string.xml as arrayList which is simply Title & description texts. But I want another text different from that discription  to show in that NewActivity.java as brand-new-descrption text. That is what I'm struggling to do now.

Thanks

this is the MainActivity.java code

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private String TAG = "MainActivity ----- ; " ;
    // Store instance variables

    private int page;
    private ConsentForm form;

    ListView listView;
    ListViewAdapter adapter;
    List<String> title, description2,description;
    int[] icon;
    int [] soundfile;
    ArrayList<Model> arrayList = new ArrayList<Model>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Redeemed Songs");

        //listview soundfile file for songs in position
        soundfile= new int[] {R.raw.song_1,R.raw.song_2,R.raw.song_3, R.raw.song_4,R.raw.song_5,R.raw.song_6,R.raw.song_7,R.raw.song_8,};

        title = Arrays.asList(getResources().getStringArray(R.array.array_titles));

        description = Arrays.asList(getResources().getStringArray(R.array.array_lyrics));
        description2 = Arrays.asList(getResources().getStringArray(R.array.array_lyrics2));

        icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song, R.drawable.song,};

        listView = findViewById(R.id.list);

        for (int i = 0; i< title.size(); i++){
            Model model =new Model(title.get(i), description.get(i),description2.get(i), icon[i]);
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass result to listview class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview class
        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    adapter.filter("");
                    listView.clearTextFilter();
                }
                else {
                    adapter.filter(s);
                }
                return true;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.action_settings){
            Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main2Activity.class));
            return true;
            //do your funtionality here

        }
        else if (id==R.id.action_howtouse){
                Toast.makeText(this, "How-To", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here

        }else if (id==R.id.action_favorites){
                Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here

        }
        else if (id==R.id.action_developers){
            Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main4Activity.class));
            return true;
            //do your funtionality here

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
}

This is the ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter{

    //Variables
    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;
    int [] soundfile;

    //Constructor
    public ListViewAdapter(Context context, List<Model> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder{
        TextView mTitleTv, mDescTv;
        ImageView mIconTv;
        MediaPlayer mediaPlayer;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, null);

            //locate the views in row.xml
            holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
            holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
            holder.mIconTv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);
        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the result into textview
        holder.mTitleTv.setText(modellist.get(i).getTitle());
        holder.mDescTv.setText(modellist.get(i).getDesc());
        //Set the result in imagview
        holder.mIconTv.setImageResource(modellist.get(i).getIcon());

        //listview soundfile file for songs in position
        soundfile= new int[] {R.raw.song_1,R.raw.song_2,R.raw.song_3, R.raw.song_4,R.raw.song_5,R.raw.song_6,R.raw.song_7,R.raw.song_8,};

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                Intent intent = new Intent(mContext, NewActivity.class);
                intent.putExtra("position", getViewTypeCount());
                intent.putExtra("actionBarTitle", modellist.get(i).getTitle());
                intent.putExtra("contentTv", modellist.get(i).getDesc());
                mContext.startActivity(intent);

            }
        });

        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (Model model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }

}

This is the String.xml

<resources>
    <string name="app_name">Redeemed Songs</string>

    <string-array name="array_lyrics">
        <item>This song lyrics 1</item>
        <item>This song lyrics 2</item>
    </string-array>

    <string-array name="array_lyrics2">
        <item>This brand new description for song lyrics 1</item>
        <item>This brand new description for song lyrics 1</item>
    </string-array>

    <string-array name="array_titles">
        <item>Song 001</item>
        <item>Song 002</item>
    </string-array>

</resources>

Body:
Add it to your Model as attribute

class Model{

your variable
.
.
.
String brandNewDesc;

public String getBrandNewDesc(){

return brandNewDesc;
}
public void setBrandNewDesc(String description){

brandNewDesc =description;
}

}

and use

   //listview item clicks
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //code later
            Intent intent = new Intent(mContext, NewActivity.class);
            intent.putExtra("position", getViewTypeCount());
            intent.putExtra("actionBarTitle", modellist.get(i).getTitle());
            intent.putExtra("contentTv", modellist.get(i).getDesc());
            **intent.putExtra("brandNewDesc", modellist.get(i).getBrandNewDesc());**

            mContext.startActivity(intent);

        }
    });


问:
Microsoft Bot Builder - send proactive message to user
I am trying to create a to-do app for microsoft Teams. Whenever a new task is created inside a team, this task is saved to team's sharepoint and i want to use a chat bot to notify all members of this team that " a new task is created". The flow is somehow like Planner. If you are assigned to task in Planner, you'll receive immediately a message from Planner chat bot. Does any have idea, how can I implement this?</p>

答: In essence, if you're not replying directly to an existing message, and you want to send a message at another later time from your bot, then it's referred to as "pro-active messaging", as you've said in the title. To do this, you need to capture certain information when the bot is added to the team (things like a "conversation reference", serviceurl, and a few other bits of info as well). I've described more about this, with links and sample code, over at Programmatically sending a message to a bot in Microsoft Teams. Of course, start first with the docs themselves, such as Send Proactive Message.</p>


问:
Active Record Could not obtain a database connection within 5.000 seconds
From the last few weeks, I am seeing this error "Could not obtain a database connection within 5.000 seconds." I have tried the following solutions.

As per Sidekiq Docs I have reduced the concurrency to 10 and increased MySql DB pool size to 12. But I was still getting this error so I increased the DB pool size to 27. But still, the issue is there. Tried solutions from this and this answer. My Sidekiq server machine doesn't have any other process running which can consume AR connections. I am not spinning any threads from outside. Below are the configurations I have

```<code>Sidekiq version - 3.4.2
Rails version - 4.2.4
Active Record version - 4.2.4
Database pool size - 27
Sidekiq concurrency - 10
</code>```

Any help with this will be appreciated.

答:
I suspect it to be a connection leak from the server side.

Sidekiq::Middleware::Server::ActiveRecord is the middleware that is responsible for returning connections to the pool, after a job is completed. This should be included by default.

When you start your server with -v flag,

```<code>bundle exec sidekiq -v -C config_file
</code>```

it will print all the middlewares that will be invoked. Can you check if this middleware is present in the list?

Body:
From the last few weeks, I am seeing this error "Could not obtain a database connection within 5.000 seconds." I have tried the following solutions.

As per Sidekiq Docs I have reduced the concurrency to 10 and increased MySql DB pool size to 12. But I was still getting this error so I increased the DB pool size to 27. But still, the issue is there. Tried solutions from this and this answer. My Sidekiq server machine doesn't have any other process running which can consume AR connections. I am not spinning any threads from outside. Below are the configurations I have

Sidekiq version - 3.4.2
Rails version - 4.2.4
Active Record version - 4.2.4
Database pool size - 27
Sidekiq concurrency - 10

Any help with this will be appreciated.

Body:
I suspect it to be a connection leak from the server side.

Sidekiq::Middleware::Server::ActiveRecord is the middleware that is responsible for returning connections to the pool, after a job is completed. This should be included by default.

When you start your server with -v flag,

bundle exec sidekiq -v -C config_file

it will print all the middlewares that will be invoked. Can you check if this middleware is present in the list?


问:
'react-native' is not recognized as an internal or external command, operable program or batch file when I already have python,npm,nodejs and jdk
I am trying to install react native in my laptop. For this, I have already intalled NodeJS, react-native CLI, NPM, python 3.8 and JDK. This is my cmd image when I typed javac and other commands for checking if everything is installed or not.

What is the error?

答:
I think you have followed the old installation documentation please follow the new installation documentation
https://facebook.github.io/react-native/docs/getting-started

If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues. npm uninstall -g react-native-cli

then use new npx to install new react native applications npx react-native init NewProject


问:
Using Function to generate numbers
```<code>def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num
</code>```

I was looking at someone's code for generating numbers and I don't understand why he used 'str(num)' to iterate i to num. Then he translates the str(i) again to int(i).

What is the intention behind this? Why can we not create

```<code>def generate(num):
    res = 0
    for i in num:
       res = res + i
    return res + num
</code>```

from the beginning?

Thanks

答:
By turning a number into a string, you are allowed to iterate over the various digits.

Try this:

```<code>for c in str(123):
   print(c)
</code>```

Of course, c is then a string, so if you want to use the digit as a number, you need to cast it back to an int.

In other words, the first function you shared computes the sum of the digits of a number. The second function you shared would compute the sum of numbers in an iterable, like a list of integers.

A single int is not an iterable, while a single str is - so for x in y: will work if y is a str, but it will cause an error if y is an int.

Title: Using Function to generate numbers

Body:
def generate(num):
    res = 0
    for i in str(num):
       res = res + int(i)
    return res + num

I was looking at someone's code for generating numbers and I don't understand why he used 'str(num)' to iterate i to num. Then he translates the str(i) again to int(i).

What is the intention behind this? Why can we not create

def generate(num):
    res = 0
    for i in num:
       res = res + i
    return res + num

from the beginning?

Thanks

Body:
By turning a number into a string, you are allowed to iterate over the various digits.

Try this:

for c in str(123):
   print(c)

Of course, c is then a string, so if you want to use the digit as a number, you need to cast it back to an int.

In other words, the first function you shared computes the sum of the digits of a number. The second function you shared would compute the sum of numbers in an iterable, like a list of integers.

A single int is not an iterable, while a single str is - so for x in y: will work if y is a str, but it will cause an error if y is an int.


问:
Getting error while switching to Linux Container in docker
I have installed docker. When its running in windows container it works fine. But if i switch to Linux container getting below error.

Os: Windows 10
Docker Desktop: 2.2.0.3

Error:

```<code>Docker.Core.Backend.BackendDestroyException:
Unable to stop Hyper-V VM: Service 'Hyper-V Host Compute Service (vmcompute)' cannot be started due to the following error: Cannot start service vmcompute on computer '.'.
at Enable-MobyLinuxRequiredService, <No file>: line 103
at <ScriptBlock>, <No file>: line 804
   at Docker.Core.Pipe.NamedPipeClient.<TrySendAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Docker.Core.Pipe.NamedPipeClient.Send(String action, Object[] parameters)
   at Docker.Actions.<>c__DisplayClass39_0.<SwitchDaemon>b__0()
   at Docker.ApiServices.TaskQueuing.TaskQueue.<>c__DisplayClass18_0.<.ctor>b__1()
</code>```

答:
according to this

try the following:

```<code>1, Open "Window Security"
2, Open "App & Browser control"
3, Click "Exploit protection settings" at the bottom
4, Switch to "Program settings" tab
5, Locate "C:\WINDOWS\System32\vmcompute.exe" in the list and expand it
6, Click "Edit"
7, Scroll down to "Code flow guard (CFG)" and uncheck "Override system settings"
8, Start vmcompute from powershell "net start vmcompute"
</code>```

Body:
I have installed docker. When its running in windows container it works fine. But if i switch to Linux container getting below error.

Os: Windows 10
Docker Desktop: 2.2.0.3

Error:

Docker.Core.Backend.BackendDestroyException:
Unable to stop Hyper-V VM: Service 'Hyper-V Host Compute Service (vmcompute)' cannot be started due to the following error: Cannot start service vmcompute on computer '.'.
at Enable-MobyLinuxRequiredService, <No file>: line 103
at

Body:
according to this

try the following:

1, Open "Window Security"
2, Open "App & Browser control"
3, Click "Exploit protection settings" at the bottom
4, Switch to "Program settings" tab
5, Locate "C:\WINDOWS\System32\vmcompute.exe" in the list and expand it
6, Click "Edit"
7, Scroll down to "Code flow guard (CFG)" and uncheck "Override system settings"
8, Start vmcompute from powershell "net start vmcompute"


问:
Shift DataFrame Columns Up Based on Threshold Value found in Columns
I have the following df:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70
</code>```

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106
</code>```

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

答:
You can find the index of the row with -999 and shift the column values.</p>

```<code>(
    df.reset_index()
    .apply(lambda x: x.shift(-x.eq(-999).idxmax()-1) if x.eq(-999).any() else x)
    .set_index('dates')
)

            testcol_45  testcol_76  testcol_99
dates
2020021918  -0.88       -0.88       -0.89
2020022000  -0.70       -0.70       -0.70
2020022006  -0.46       -0.45       NaN
2020022012  -0.37       NaN         NaN
2020022018  NaN         NaN         NaN
2020022100  NaN         NaN         NaN
2020022106  NaN         NaN         NaN
</code>```

Body:
I have the following df:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

Body:
You can find the index of the row with -999 and shift the column values.

(
    df.reset_index()
    .apply(lambda x: x.shift(-x.eq(-999).idxmax()-1) if x.eq(-999).any() else x)
    .set_index('dates')
)

            testcol_45  testcol_76  testcol_99
dates
2020021918  -0.88       -0.88       -0.89
2020022000  -0.70       -0.70       -0.70
2020022006  -0.46       -0.45       NaN
2020022012  -0.37       NaN         NaN
2020022018  NaN         NaN         NaN
2020022100  NaN         NaN         NaN
2020022106  NaN         NaN         NaN