问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答: Your second option (just throwing the exception in the else) would be more correct.  Note, though, that there is no code path to reach the return false; statement -- either the if is true, in which case true is returned, or its not, in which case an exception in thrown (thus aborting the code to the next-higher-level handler).  So you don't really need it.

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}


来源: stackexchange

问:
Template for asp.net core webapi service
Using the asp.net.boilerplate it appears I will always have to choose a front-end option.  It is possible to use this purely for a standardized REST webapi service only?</p>

答:
Yes, it is possible to use ASP.NET Boilerplate templates purely for a Web API service.

For example, choose the ASP.NET Core + Angular template, which provides you with:

```<code>+-- angular/
|   +-- ...
|   +-- src/
|   +-- ...
|
+-- aspnet-core/
    +-- ...
    +-- src/
    +-- ...
</code>```

And then just ignore the angular folder.

ContentLicense: CC BY-SA 4.0

Body:
Yes, it is possible to use ASP.NET Boilerplate templates purely for a Web API service.

For example, choose the ASP.NET Core + Angular template, which provides you with:

+-- angular/
|   +-- ...
|   +-- src/
|   +-- ...
|
+-- aspnet-core/
    +-- ...
    +-- src/
    +-- ...

And then just ignore the angular folder.


问:
How to deploy a different host.json for a different deployment profile?
I deploy my Azure Function from Visual Studio, and as part of my Functions project I have a host.json file which specifies some settings which I need to change for Production vs Development.  (Specifically, the extensions:queues:batchSize setting).  The reason is unfortunately largely beyond my control (the database I use in development is lower-tier than the production one and higher batch sizes will cause it to fall over pretty quickly).

I'd like to be able to specify a small batch size for development and higher batch size for production.  I have production and development deployment profiles already, but I don't see any way to vary the host.json file.

Is there 1) a way to do this natively, and/or 2) a better DevOps practice I should be using to make this issue obsolete?  I can't use Azure DevOps yet (long story) but perhaps just having separate branches for dev and production would be sufficient?

答:
Another way to do this would be to set environment variables for it. In your case, you could set extensions:queues:batchSize with one like this

```<code>AzureFunctionsJobHost__extensions__queues__batchSize
</code>```

When deploying to azure, this would be an application setting with this name/key

Body:
Another way to do this would be to set environment variables for it. In your case, you could set extensions:queues:batchSize with one like this

AzureFunctionsJobHost__extensions__queues__batchSize

When deploying to azure, this would be an application setting with this name/key


问:
Why does my search query doesn't turn out well?
I am tring to make my search function works. It does work but, the result is not true. For example, I search for the word 'data' and it display 'computer programmer'. It suppose to display 'Data Analyst'.</p>

```<code>if (isset($_POST['submit-search'])) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
   // $sql = 'SELECT * FROM professional, job, location WHERE J.JOB_ID = P.PROFESSIONAL_ID AND P.PROFESSIONAL_ID = L.LOCATION_ID AND PROFESSIONAL_NAME LIKE '%$search%'';
    $sql = "SELECT * FROM professional, job, location WHERE JOB_NAME LIKE '%$search%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    $new_result = $row["JOB_NAME"];

    function str_contains($phrase, $word) {
        return strpos($phrase, $word) !== false;
    }

    if (str_contains($new_result,'computer') || str_contains($new_result, 'programmer') || str_contains($new_result, 'computer programmer')) {
        echo "
        <div class= 'expertise'>
        <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='computer_programmer.html'> Computer Programmer</a></h2>
        </div>";
    } else if (str_contains($new_result, 'data') || str_contains($new_result, 'analyst') || str_contains($new_result, 'data analyst')) {
        echo "
        <div class= 'expertise'>
        <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='data_analyst.html'> Data Analyst</a></h2>
        </div>";
    } else {
        echo 'There are no results matching your search!';
    }
}
</code>```

答:
Your if statment is currently incorrect. Currently, your expression will always evaluate to true as a non-empty string is considered truthy. Thus your if statement looks more like:

```<code>if ($result == '%computer%' || true || true) {
</code>```

The above statement will always run the code within the if as the expression will always evaluate to true (as X ∨ T ≡ T).

Instead, you need to recheck the equality of $result:

```<code>if ($result == '%computer%' || $result == '%programmer%' || $result == '%computer programmer%') {
  // do "Computer Programer" code...
} else if ($result =='%data%' || $result == '%analyst%' || $result == '%data analyst%') {
 // do "Data Analyst" code...
} else {
  // do "no results code"...
}
</code>```

However, for this to work you need to ensure $result is what you think it is and not a mysqli_result object

EDIT:
To check whether a string contains computer or analyst etc... you can't use SQL wildcards as you have here. Instead, you can use the PHP method strpos. I suggest you build a helper function which will allow you to do this neatly within your if-statement:

```<code>function str_contains($phrase, $word) {
    return strpos(strtolower($phrase), $word) !== false;
}

// then in your if statement:
if (str_contains($result,'computer') || str_contains($result, 'programmer') || str_contains($result, 'computer programmer')) {
  // do "Computer Programer" code...
} else if (str_contains($result, 'data') || str_contains($result, 'analyst') || str_contains($result, 'data analyst')) {
 // do "Data Analyst" code...
} else {
  // do "no results code"...
}
</code>```

Body:
I am tring to make my search function works. It does work but, the result is not true. For example, I search for the word 'data' and it display 'computer programmer'. It suppose to display 'Data Analyst'.

if (isset($_POST['submit-search'])) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
   // $sql = 'SELECT * FROM professional, job, location WHERE J.JOB_ID = P.PROFESSIONAL_ID AND P.PROFESSIONAL_ID = L.LOCATION_ID AND PROFESSIONAL_NAME LIKE '%$search%'';
    $sql = "SELECT * FROM professional, job, location WHERE JOB_NAME LIKE '%$search%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    $new_result = $row["JOB_NAME"];

    function str_contains($phrase, $word) {
        return strpos($phrase, $word) !== false;
    }

    if (str_contains($new_result,'computer') || str_contains($new_result, 'programmer') || str_contains($new_result, 'computer programmer')) {
        echo "

 Computer Programmer

";
    } else if (str_contains($new_result, 'data') || str_contains($new_result, 'analyst') || str_contains($new_result, 'data analyst')) {
        echo "

 Data Analyst

";
    } else {
        echo 'There are no results matching your search!';
    }
}

Body:
Your if statment is currently incorrect. Currently, your expression will always evaluate to true as a non-empty string is considered truthy. Thus your if statement looks more like:

if ($result == '%computer%' || true || true) {

The above statement will always run the code within the if as the expression will always evaluate to true (as X ∨ T ≡ T).

Instead, you need to recheck the equality of $result:

if ($result == '%computer%' || $result == '%programmer%' || $result == '%computer programmer%') {
  // do "Computer Programer" code...
} else if ($result =='%data%' || $result == '%analyst%' || $result == '%data analyst%') {
 // do "Data Analyst" code...
} else {
  // do "no results code"...
}

However, for this to work you need to ensure $result is what you think it is and not a mysqli_result object

EDIT:
To check whether a string contains computer or analyst etc... you can't use SQL wildcards as you have here. Instead, you can use the PHP method strpos. I suggest you build a helper function which will allow you to do this neatly within your if-statement:

function str_contains($phrase, $word) {
    return strpos(strtolower($phrase), $word) !== false;
}

// then in your if statement:
if (str_contains($result,'computer') || str_contains($result, 'programmer') || str_contains($result, 'computer programmer')) {
  // do "Computer Programer" code...
} else if (str_contains($result, 'data') || str_contains($result, 'analyst') || str_contains($result, 'data analyst')) {
 // do "Data Analyst" code...
} else {
  // do "no results code"...
}


问:
Temporary Environment Variables in Ruby
Try to bear with me as I am fairly new to this and don't have much coding experience.

Im trying to use a ruby script to add a location to my PATH variable. So far I just have

```<code>path = ENV['PATH'].to_s

ENV['PATH'] = path + ";" + location

print ENV['PATH']
</code>```

The problem is that the file seems to be added to the PATH and prints with it, but when I go check my path variable the new location is not there.

Also, when I run a separate script of which is one line:

```<code>print ENV['PATH']
</code>```

the new location is not there either.

My question is is there a way to make the new PATH "save" instead of reverting to the old PATH when the script is finished?

答:
The best you can do is generate a shell command to be evaluated outside the Ruby script and inside the shell you are running.

Something like this should work:

puts "export PATH=#{ENV['PATH']};#{location}"
```

<p>Then, in the shell you do</p>

<pre class="lang-sh prettyprint-override"><code>eval $(ruby_script)
</code>```

However, since you seem to want to run this in Windows you probably want to use command substitution, in which case you output the location directly:

puts location
```

<p>And in the Windows shell:</p>

<pre class="lang-sh prettyprint-override"><code>set PATH=%PATH%;(ruby_script)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Temporary Environment Variables in Ruby

Body:
Try to bear with me as I am fairly new to this and don't have much coding experience.

Im trying to use a ruby script to add a location to my PATH variable. So far I just have

path = ENV['PATH'].to_s

ENV['PATH'] = path + ";" + location

print ENV['PATH']

The problem is that the file seems to be added to the PATH and prints with it, but when I go check my path variable the new location is not there.

Also, when I run a separate script of which is one line:

print ENV['PATH']

the new location is not there either.

My question is is there a way to make the new PATH "save" instead of reverting to the old PATH when the script is finished?

Body:
The best you can do is generate a shell command to be evaluated outside the Ruby script and inside the shell you are running.

Something like this should work:

puts "export PATH=#{ENV['PATH']};#{location}"

Then, in the shell you do

eval $(ruby_script)

However, since you seem to want to run this in Windows you probably want to use command substitution, in which case you output the location directly:

puts location

And in the Windows shell:

set PATH=%PATH%;(ruby_script)


问:
next is not a function. Nodejs http://localhost:3000/api/authenticate
I am developing a mean app login/registration using jwt and passport. Using local storage i am saving token but it is not getting saved in local storage.
It also says that next is not a function in my controller.js. On the other hand registration is working perfectly fine.

contoller.js

```<code>   module.exports.authenticate = (req, res, next) => {
    // call for passport authentication
    passport.authenticate('local', (err, user, info) => {
        // error from passport middleware
        if (err) return res.status(400).json(err);
        // registered user
        else if (user) return res.status(200).json({ "token":
     user.generateJwt() });
        // unknown user or wrong password
        else return res.status(404).json(info);
    })(req, res);
   }
</code>```

index.router.js

```<code>const express = require('express');
const router = express.Router();

const ctrlUser = require('../controllers/user.controller');

const jwtHelper = require('../config/jwtHelper');

router.post('/register', ctrlUser.register);
router.post('/authenticate', ctrlUser.authenticate);
router.get('/profile',jwtHelper.verifyJwtToken, ctrlUser.userProfile);

module.exports = router;
</code>```

login.component.ts

```<code>onSubmit(form : NgForm){
    this.userService.login(form.value).subscribe(
      res => {
        this.userService.setToken(res['token']);
        this.router.navigateByUrl('/profile');
      },
      err => {
        this.serverErrorMessages = err.error.message;
      }
    );
  }
</code>```

user.service

```<code>
  login(authCredentials){
    return this.http.post(environment.apiBaseUrl+'/authenticate', authCredentials, this.noAuthHeader);
  }

  setToken(token: string) {
    localStorage.setItem('token', token);
  }

  getToken() {
    return localStorage.getItem('token');
  }

  deleteToken() {
    localStorage.removeItem('token');
  }

  getUserPayload() {
    var token = this.getToken();
    if (token) {
      var userPayload = atob(token.split('.')[1]);
      return JSON.parse(userPayload);
    }
    else
      return null;
  }

  isLoggedIn() {
    var userPayload = this.getUserPayload();
    if (userPayload)
      return userPayload.exp > Date.now() / 1000;
    else
      return false;
  }

  getUserProfile() {
    return this.http.get(environment.apiBaseUrl + '/profile');
  }
</code>```

```<code>TypeError: next is not a function
    at attempt (D:\fulinkedFolder\flogin\backend\node_modules\passport\lib\middleware\authenticate.js:186:32)
    at authenticate (D:\fulinkedFolder\flogin\backend\node_modules\passport\lib\middleware\authenticate.js:362:7)
    at module.exports.authenticate (D:\fulinkedFolder\flogin\backend\controllers\user.controller.js:37:7)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:335:12)
    at next (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:174:3)
    at router (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:317:13)
    at D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:335:12)
</code>```

答:
Pass the next function along with req and res:

```<code>module.exports.authenticate = (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {

    // ...

  })(req, res, next) // Pass 'next' here
}
</code>```

I hope this helps.

Body:
I am developing a mean app login/registration using jwt and passport. Using local storage i am saving token but it is not getting saved in local storage.
It also says that next is not a function in my controller.js. On the other hand registration is working perfectly fine.

contoller.js

   module.exports.authenticate = (req, res, next) => {
    // call for passport authentication
    passport.authenticate('local', (err, user, info) => {
        // error from passport middleware
        if (err) return res.status(400).json(err);
        // registered user
        else if (user) return res.status(200).json({ "token":
     user.generateJwt() });
        // unknown user or wrong password
        else return res.status(404).json(info);
    })(req, res);
   }

index.router.js

const express = require('express');
const router = express.Router();

const ctrlUser = require('../controllers/user.controller');

const jwtHelper = require('../config/jwtHelper');

router.post('/register', ctrlUser.register);
router.post('/authenticate', ctrlUser.authenticate);
router.get('/profile',jwtHelper.verifyJwtToken, ctrlUser.userProfile);

module.exports = router;

login.component.ts

onSubmit(form : NgForm){
    this.userService.login(form.value).subscribe(
      res => {
        this.userService.setToken(res['token']);
        this.router.navigateByUrl('/profile');
      },
      err => {
        this.serverErrorMessages = err.error.message;
      }
    );
  }

user.service

  login(authCredentials){
    return this.http.post(environment.apiBaseUrl+'/authenticate', authCredentials, this.noAuthHeader);
  }

  setToken(token: string) {
    localStorage.setItem('token', token);
  }

  getToken() {
    return localStorage.getItem('token');
  }

  deleteToken() {
    localStorage.removeItem('token');
  }

  getUserPayload() {
    var token = this.getToken();
    if (token) {
      var userPayload = atob(token.split('.')[1]);
      return JSON.parse(userPayload);
    }
    else
      return null;
  }

  isLoggedIn() {
    var userPayload = this.getUserPayload();
    if (userPayload)
      return userPayload.exp > Date.now() / 1000;
    else
      return false;
  }

  getUserProfile() {
    return this.http.get(environment.apiBaseUrl + '/profile');
  }

TypeError: next is not a function
    at attempt (D:\fulinkedFolder\flogin\backend\node_modules\passport\lib\middleware\authenticate.js:186:32)
    at authenticate (D:\fulinkedFolder\flogin\backend\node_modules\passport\lib\middleware\authenticate.js:362:7)
    at module.exports.authenticate (D:\fulinkedFolder\flogin\backend\controllers\user.controller.js:37:7)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:335:12)
    at next (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:174:3)
    at router (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:317:13)
    at D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\fulinkedFolder\flogin\backend\node_modules\express\lib\router\index.js:335:12)

Body:
Pass the next function along with req and res:

module.exports.authenticate = (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {

    // ...

  })(req, res, next) // Pass 'next' here
}

I hope this helps.


问:
anoter ajax function for another form not working
i have 2 form with different id (form_sign and form_login) and use ajax for submit it. form_sign working nice, but another form not working.

i was try to show alert when the function for form_login if form was submit, and it's work, but when i add ajax code for transaction form, ajax code not running. i was inspect the code element, but the browser not displayed the error

$(document).ready(function() {
  checkSame('#_password');
  checkChar('#password');

  $("#form_sign").on('submit', function(e) { // form 1
    e.preventDefault();
    let post_url = $(this).attr("action"); //get form action url
    let request_method = $(this).attr("method"); //get form GET/POST method
    let form_data = $(this).serialize(); //Encode form elements for submission

    $.ajax({
      url: post_url,
      type: request_method,
      data: form_data,
      success: function(data) {
        if (data == "success") {
          reseter("#form_sign");
          $('#massage').html("Save data success! silahkan login");
          $("#divMassage").fadeOut(5000);

        }
      }
    })
  });

  $("#form_login").on('submit', function(ev) { //form 2
    ev.preventDefault();
    let post_url = $(this).attr("action"); //get form action url
    let request_method = $(this).attr("method"); //get form GET/POST method
    let form_data = $(this).serialize(); //Encode form elements for submission
    // i put alert here, the alert run
    $.ajax({
      url: post_url,
      type: request_method,
      data: form_data,
      success: function(data) {

        alert("eee"); // this alert not run
      }
    })
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<section class="content">
  <div class="row">
    <div class="col-md-5 col-md-offset-3">
      <div class="nav-tabs-custom" style=" box-shadow: 10px 10px 5px 5px #888888;">
        <ul class="nav nav-tabs">
          <li class="active" id="link_1"><b>Creat an Account</b></li>
          <li class="" id="link_2"><b>Login</b></li>
        </ul>
        <div class="tab-content">
          <div class="tab-pane active" id="tab_1">
            <form id="form_sign" role="form" action="<?php echo $see?>halaman/simaksi/creat-account.php" method="POST">
              <div class="box-body">
                <div class="form-group">
                  <label for="exampleInputEmail1">Username</label>
                  <input type="text" class="form-control" name="username" placeholder="Enter Username" required>
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="email" class="form-control" name="email" placeholder="Enter email" required>
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Password</label>
                  <input type="password" class="form-control" name="password" id="password" onkeyup="checkChar(this.id)" placeholder="Enter Magic Words" required>
                  <span id="mass1" class="text-red"></span>
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Retype Password</label>
                  <input type="password" class="form-control" name="_password" id="_password" onkeyup="checkSame(this.id)" placeholder="Retype Magic Words" required>
                  <span id="mass2" class="text-red"></span>
                </div>
                <div class="form-group">
                  <button type="submit" name="create" class="btn btn-lg btn-success btn-block" id="btn-submit" disabled>Create</button>
                  <button type="reset" class="btn btn-lg btn-warning btn-block">Clear</button>
                </div>
              </div>
            </form>
          </div>
          <!-- /.tab-pane -->
          <div class="tab-pane" id="tab_2">
            <form id="form_login" role="form" action="post" method="<?php echo $see?>halaman/simaksi/login-account.php">
              <div class="box-body">
                <div class="form-group">
                  <label for="exampleInputEmail1">Username</label>
                  <input type="text" class="form-control" name="user" placeholder="Enter Username" required>
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Password</label>
                  <input type="password" class="form-control" name="password" placeholder="Enter Magic Words" required>
                </div>
                <div class="form-group ">
                  <button type="submit" class="btn btn-lg btn-success btn-block" id="btn-login">Login</button>
                </div>
              </div>
            </form>
          </div>
          <!-- /.tab-pane -->
        </div>
        <!-- /.tab-content -->
      </div>
    </div>
  </div>
</section></code>```

I hope that 2 different forms can work well even though they are on the same page

sorry for my bad english
regards

答:
You are using tag form type submit and submit form using jQuery function. in this case form submitted 2 times by ajax and post method.
to submit these form you need to change button type submit with button only. like below </p>

```<code><button type="button" name="create" class="btn btn-lg btn-success btn-block" id="btn-submit" disabled>Create</button>

<button type="submit" class="btn btn-lg btn-success btn-block" id="btn-login">Login</button>
</code>```

<p>ajax code </p>

```<code><script>
    // use jquery-2.1.4
    $(document).ready(function(){
        checkSame('#_password');
        checkChar('#password');

        $("#form_sign").on('click', function(e){ // form 1
            e.preventDefault();
            let post_url = $(this).attr("action"); //get form action url
            let request_method = $(this).attr("method"); //get form GET/POST method
            let form_data = $(this).serialize();//Encode form elements for submission

            $.ajax({
                url:post_url,
                type:request_method,
                data:form_data,
                success:function(data){
                    if (data=="success") {
                        reseter("#form_sign");
                        $('#massage').html("Save data success! silahkan login");
                        $("#divMassage").fadeOut(5000);

                    }
                }
            })
        });

        $("#form_login").on('click', function(ev){ //form 2
            ev.preventDefault();
            let post_url = $(this).attr("action"); //get form action url
            let request_method = $(this).attr("method"); //get form GET/POST method
            let form_data = $(this).serialize();//Encode form elements for submission
// i put alert here, the alert run
            $.ajax({
                url:post_url,
                type:request_method,
                data:form_data,
                success:function(data){
                      alert("eee"); // this alert not run
                }
            })
        });
    });
    </script>
</code>```

Body:
i have 2 form with different id (form_sign and form_login) and use ajax for submit it. form_sign working nice, but another form not working.

i was try to show alert when the function for form_login if form was submit, and it's work, but when i add ajax code for transaction form, ajax code not running. i was inspect the code element, but the browser not displayed the error

$(document).ready(function() {
  checkSame('#_password');
  checkChar('#password');

  $("#form_sign").on('submit', function(e) { // form 1
    e.preventDefault();
    let post_url = $(this).attr("action"); //get form action url
    let request_method = $(this).attr("method"); //get form GET/POST method
    let form_data = $(this).serialize(); //Encode form elements for submission

    $.ajax({
      url: post_url,
      type: request_method,
      data: form_data,
      success: function(data) {
        if (data == "success") {
          reseter("#form_sign");
          $('#massage').html("Save data success! silahkan login");
          $("#divMassage").fadeOut(5000);

        }
      }
    })
  });

  $("#form_login").on('submit', function(ev) { //form 2
    ev.preventDefault();
    let post_url = $(this).attr("action"); //get form action url
    let request_method = $(this).attr("method"); //get form GET/POST method
    let form_data = $(this).serialize(); //Encode form elements for submission
    // i put alert here, the alert run
    $.ajax({
      url: post_url,
      type: request_method,
      data: form_data,
      success: function(data) {

        alert("eee"); // this alert not run
      }
    })
  });
});

Creat an Account

Login

            <form id="form_sign" role="form" action="<?php echo $see?>halaman/simaksi/creat-account.php" method="POST">

                  Username
                  <input type="text" class="form-control" name="username" placeholder="Enter Username" required>

                  Email address
                  <input type="email" class="form-control" name="email" placeholder="Enter email" required>

                  Password
                  <input type="password" class="form-control" name="password" id="password" onkeyup="checkChar(this.id)" placeholder="Enter Magic Words" required>

                  Retype Password
                  <input type="password" class="form-control" name="_password" id="_password" onkeyup="checkSame(this.id)" placeholder="Retype Magic Words" required>

                  <button type="submit" name="create" class="btn btn-lg btn-success btn-block" id="btn-submit" disabled>Create</button>
                  <button type="reset" class="btn btn-lg btn-warning btn-block">Clear</button>

            </form>

            <form id="form_login" role="form" action="post" method="<?php echo $see?>halaman/simaksi/login-account.php">

                  Username
                  <input type="text" class="form-control" name="user" placeholder="Enter Username" required>

                  Password
                  <input type="password" class="form-control" name="password" placeholder="Enter Magic Words" required>

                  <button type="submit" class="btn btn-lg btn-success btn-block" id="btn-login">Login</button>

            </form>

I hope that 2 different forms can work well even though they are on the same page

sorry for my bad english
regards

Body:
You are using tag form type submit and submit form using jQuery function. in this case form submitted 2 times by ajax and post method.
to submit these form you need to change button type submit with button only. like below

<button type="button" name="create" class="btn btn-lg btn-success btn-block" id="btn-submit" disabled>Create</button>

<button type="submit" class="btn btn-lg btn-success btn-block" id="btn-login">Login</button>

ajax code

<script>
    // use jquery-2.1.4
    $(document).ready(function(){
        checkSame('#_password');
        checkChar('#password');

        $("#form_sign").on('click', function(e){ // form 1
            e.preventDefault();
            let post_url = $(this).attr("action"); //get form action url
            let request_method = $(this).attr("method"); //get form GET/POST method
            let form_data = $(this).serialize();//Encode form elements for submission

            $.ajax({
                url:post_url,
                type:request_method,
                data:form_data,
                success:function(data){
                    if (data=="success") {
                        reseter("#form_sign");
                        $('#massage').html("Save data success! silahkan login");
                        $("#divMassage").fadeOut(5000);

                    }
                }
            })
        });

        $("#form_login").on('click', function(ev){ //form 2
            ev.preventDefault();
            let post_url = $(this).attr("action"); //get form action url
            let request_method = $(this).attr("method"); //get form GET/POST method
            let form_data = $(this).serialize();//Encode form elements for submission
// i put alert here, the alert run
            $.ajax({
                url:post_url,
                type:request_method,
                data:form_data,
                success:function(data){
                      alert("eee"); // this alert not run
                }
            })
        });
    });
    </script>


问:
Parsing JSON string in Java android
I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.

```<code>    "place": [
            {
                "address": {
                    "country_code": "fr",
                    "country": "France",
                    "state": "Normandie",
                    "county": "Calvados"
                },
                "icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
                "importance": 0.74963706049207,
                "type": "administrative",
                "class": "boundary",
                "display_name": "Calvados, Normandie, France",
                "lon": "-0.24139500722798",
                "lat": "49.09076485",
                "boundingbox": [
                    "48.7516623",
                    "49.4298653",
                    "-1.1597713",
                    "0.4466332"
                ],
                "osm_id": "7453",
                "osm_type": "relation",
                "licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
                "place_id": "158910871"
            }
        ]
</code>```

any help would be appreciated. thanks.

these is my android code :

```<code>JSONObject objectPremium = new JSONObject(String.valueOf(result));
                        String premium = objectPremium.getString("premium");
                        JSONArray jArray1 = objectPremium.getJSONArray("premium");

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

                            JSONObject object3 = jArray1.getJSONObject(i);
                            adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
                            Log.e("mylog",adresse);

                        }
</code>```

答:
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.

```<code>private void getJSON(final String urlWebService) {
    class GetJSON extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }

        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}
</code>```

You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.

Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.

Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.

Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.

For more details you can check this JSON Parsing in Android post.

Title: Parsing JSON string in Java android

Body:
I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.

    "place": [
            {
                "address": {
                    "country_code": "fr",
                    "country": "France",
                    "state": "Normandie",
                    "county": "Calvados"
                },
                "icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
                "importance": 0.74963706049207,
                "type": "administrative",
                "class": "boundary",
                "display_name": "Calvados, Normandie, France",
                "lon": "-0.24139500722798",
                "lat": "49.09076485",
                "boundingbox": [
                    "48.7516623",
                    "49.4298653",
                    "-1.1597713",
                    "0.4466332"
                ],
                "osm_id": "7453",
                "osm_type": "relation",
                "licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
                "place_id": "158910871"
            }
        ]

any help would be appreciated. thanks.

these is my android code :

JSONObject objectPremium = new JSONObject(String.valueOf(result));
                        String premium = objectPremium.getString("premium");
                        JSONArray jArray1 = objectPremium.getJSONArray("premium");

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

                            JSONObject object3 = jArray1.getJSONObject(i);
                            adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
                            Log.e("mylog",adresse);

                        }

Body:
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.

private void getJSON(final String urlWebService) {
    class GetJSON extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }

        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}

You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.

Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.

Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.

Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.

For more details you can check this JSON Parsing in Android post.


问:
How to count the objects in javascript?
I have a function which takes an array of many data types.

function count(totalObjs) {
    var count = 0;
    for (var i = 0; i <= arr.length; i++) {

        count++;
    }
    return count;
}
```

答:
To only count the objects in an array, you can't do this:

```<code>typeof x == "object"
</code>```

Because this returns true for an object, an array, or null.

It's best to check the toString - it'll return [object Object] for objects.

const arr = [1,{},[],null,null,'foo',3,4,5,{},{},{},'foo'];

const count = arrObj => arrObj.filter(e => e && e.toString() == "[object Object]").length;

console.log(count(arr));```

Title: How to count the objects in javascript?

Body:
To only count the objects in an array, you can't do this:

typeof x == "object"

Because this returns true for an object, an array, or null.

It's best to check the toString - it'll return [object Object] for objects.

const arr = [1,{},[],null,null,'foo',3,4,5,{},{},{},'foo'];

const count = arrObj => arrObj.filter(e => e && e.toString() == "[object Object]").length;

console.log(count(arr));


问:
There is a way to enforce referential integrity in MongoDB
When you search for referential integrity in relation to Mongo-DB the standard response is "MongoDB does not support this". The standard explanation is that MongoDB supports refs and populate, however there is nothing that prevents you changing the ref to an invalid value. This is a major deterrent for many developers coming from a SQL background.</p>

答:
THERE IS A SOLUTION!

Sure - there is no way to prevent someone changing a reference through Compass or another GUI but there is definitely a way to do it when you are developing your own API and in control of all read and write operations to the database.

I will illustrate with an example from some code I am currently working on. Firstly the UnitType.js defines a very simple collection with simply a name and an ID. The magic is in Unit.js - Have a look at the custom validator for unittype field. It issues an asynch request to the UnitType model to find the related UnitType by its _id field. If the ID provided on save or update is invalid, an error message will be returned "Invalid Object ID" otherwise record will be saved. In this way it is never possible to create or modify a record with an invalid UnitType record.

This process can be repeated if there are multiple references.

Provided you are using the same model throughout your application, there is no need to write additional code to support referential integrity

I hope this helps

```<code>// UnitType.js - MongoDB Schema
const mongoose = require('mongoose')
const UnitType = mongoose.model(
  'UnitType',
  new mongoose.Schema(
    {
      name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 40
      }
    },
    { collection: 'unittype' }
  )
)

exports.UnitType = UnitType

</code>```

```<code>// Unit.js - MongoDB Schema
const mongoose = require('mongoose')
const { UnitType } = require('./Unittype')
const Unit = mongoose.model(
  'Unit',
  new mongoose.Schema(
    {
      door: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10,
        index: true,
        unique: true
      },
      name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 40
      },
      location: {
        type: String
      },
      description: {
        type: String
      },
      unittype: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'UnitType',
        // Ensure that UnitType iD is valid (note isAsync is deprecated)
        validate: {
          validator: async function(v) {
            return await UnitType.findById(v, (err, rec) => rec !== null)
          },
          message: 'Invalid Object ID'
        }
      }
    },
    { collection: 'unit' }
  )
)

exports.Unit = Unit

</code>```

Body:
THERE IS A SOLUTION!

Sure - there is no way to prevent someone changing a reference through Compass or another GUI but there is definitely a way to do it when you are developing your own API and in control of all read and write operations to the database.

I will illustrate with an example from some code I am currently working on. Firstly the UnitType.js defines a very simple collection with simply a name and an ID. The magic is in Unit.js - Have a look at the custom validator for unittype field. It issues an asynch request to the UnitType model to find the related UnitType by its _id field. If the ID provided on save or update is invalid, an error message will be returned "Invalid Object ID" otherwise record will be saved. In this way it is never possible to create or modify a record with an invalid UnitType record.

This process can be repeated if there are multiple references.

Provided you are using the same model throughout your application, there is no need to write additional code to support referential integrity

I hope this helps

// UnitType.js - MongoDB Schema
const mongoose = require('mongoose')
const UnitType = mongoose.model(
  'UnitType',
  new mongoose.Schema(
    {
      name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 40
      }
    },
    { collection: 'unittype' }
  )
)

exports.UnitType = UnitType

// Unit.js - MongoDB Schema
const mongoose = require('mongoose')
const { UnitType } = require('./Unittype')
const Unit = mongoose.model(
  'Unit',
  new mongoose.Schema(
    {
      door: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10,
        index: true,
        unique: true
      },
      name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 40
      },
      location: {
        type: String
      },
      description: {
        type: String
      },
      unittype: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'UnitType',
        // Ensure that UnitType iD is valid (note isAsync is deprecated)
        validate: {
          validator: async function(v) {
            return await UnitType.findById(v, (err, rec) => rec !== null)
          },
          message: 'Invalid Object ID'
        }
      }
    },
    { collection: 'unit' }
  )
)

exports.Unit = Unit


问:
Is there a way to write generic code for any function such that it can be executed (asyncronously) and a return value obtained from a thread pool?
I have been trying to create a thread pool class(for personal experimentation/use/fun). I found a way to accept any function with any arguments/return type by using parameter packs (seen in code below) and binding the functions to std::function. This works without issue. The problem is that I want to attempt to make a member function to retrieve returned values from the jobs being executed. I do not know how to make the code generic while attempting to do this.

So far I have tried making a map, that uses the jobs ID as a key and will have the return value of that job stored in it. My struggle is
1. I cant figure out how to determine the type (I can with "typename std::invoke_result::type" but this breaks down if the type is void)
2. How to make a map that can have the Job ID as a key and any type so that I can put return types there.

class ThreadPool{
public:

    //getInstance to allow the second constructor to be called
    static ThreadPool& getInstance(int numThreads){
        static ThreadPool instance(numThreads);

        return instance;
    }

    //add any arg # function to queue
    template <typename Func, typename... Args >
    inline uint64_t push(Func& f, Args&&... args){
        auto funcToAdd = std::bind(f, args...);

        uint64_t newID = currentID++;
        std::unique_lock<std::mutex> lock(JobMutex);

        JobQueue.push(std::make_pair(funcToAdd, newID));
        thread.notify_one();
        return newID; //return the ID of the job in the queue
    }

    /* utility functions will go here*/
    inline void resize(int newTCount){

        int tmp = MAX_THREADS;
        if(newTCount > tmp || newTCount < 1){
            throw bad_thread_alloc("Cannot allocate " + std::to_string(newTCount) + " threads because it is greater than your systems maximum of " + std::to_string(tmp), __FILE__, __LINE__);
        }

        numThreads = (uint8_t)newTCount;
        Pool.resize(newTCount);
        DEBUG("New size is: " + std::to_string(Pool.size()));
    }

    inline uint8_t getThreadCount(){
        return numThreads;
    }

        //how i want the user to interact with this class is
        // int id = push(func, args);
        // auto value = getReturnValue(id); //blocks until return value is returned
    auto getReturnValue(uint64_t jobID) {
        //Not sure how to handle this
    }

private:

    uint64_t currentID;
    uint8_t numThreads;
    std::vector<std::thread> Pool; //the actual thread pool
    std::queue<std::pair<std::function<void()>, uint64_t>> JobQueue; //the jobs with their assigned ID
    std::condition_variable thread;
    std::mutex JobMutex;

    /* infinite loop function */
    void threadManager();

    /*  Constructors */
    ThreadPool(); //prevent default constructor from being called

    //real constructor that is used
    inline ThreadPool(uint8_t numThreads) : numThreads(numThreads) {
        currentID = 0; //initialize currentID
        int tmp = MAX_THREADS;
        if(numThreads > tmp){
            throw bad_thread_alloc("Cannot allocate " + std::to_string(numThreads) + " threads because it is greater than your systems maximum of " + std::to_string(tmp), __FILE__, __LINE__);
        }
        for(int i = 0; i != numThreads; ++i){
            Pool.push_back(std::thread(&ThreadPool::threadManager, this));
            Pool.back().detach();
            DEBUG("Thread " + std::to_string(i) + " allocated");
        }
        DEBUG("Number of threads being allocated " + std::to_string(numThreads));
    }
    /* end constructors */

NULL_COPY_AND_ASSIGN(ThreadPool);
}; /* end ThreadPool Class */

void ThreadPool::threadManager(){
    while (true) {

        std::unique_lock<std::mutex> lock(JobMutex);
        thread.wait(lock, [this] {return !JobQueue.empty(); });

        //strange bug where it will continue even if the job queue is empty
        if (JobQueue.size() < 1)
            continue;

        auto job = JobQueue.front().first;
        JobQueue.pop();
        job();
    }
}
```

Am I going about this all wrong? I didnt know any other way to generically store any type of function while also being able to get return types out of them.

答:
Provide a location to store the return value to the function that creates the job. If we provide the return location together with the other elements, then there's no uncertainty about where the job gets stored.

We can design this part of the interface relatively simply. If we package the arguments together with the function, we can store all queued jobs as std::function<void()>. This simplifies the implementation of the thread queue, since the thread queue only has to worry about one type of std::function, and doesn't have to care at all about the return value.

```<code>using job_t = std::function<void()>;

template<class Return, class Func, class... Args>
job_t createJob(Return& dest, Func&& func, Args&&... args) {
    return job_t([=]() {
        dest = func(std::forward<Args>(args)...);
    });
};
</code>```

This implementation makes it easy to start jobs asynchronously at will, without the thread pool worrying about where the return value gets stored. As an example, I wrote a function to run a job. The function starts the job on a new thread, and it marks an atomic_bool as true when the function completes. Because we don't have to worry about the return value, the function only has to return a shared_ptr to the atomic_bool we use to check if the function's finished.

```<code>using std::shared_ptr;
using std::atomic_bool;

shared_ptr<atomic_bool> run_job_async(std::function<void()> func) {
    shared_ptr<atomic_bool> is_complete = std::make_shared<atomic_bool>(false);
    std::thread t([f = std::move(func), =]() {
        f();
        *is_complete = true;
    });
    t.detach();
    return is_complete;
}
</code>```

Body:
I have been trying to create a thread pool class(for personal experimentation/use/fun). I found a way to accept any function with any arguments/return type by using parameter packs (seen in code below) and binding the functions to std::function. This works without issue. The problem is that I want to attempt to make a member function to retrieve returned values from the jobs being executed. I do not know how to make the code generic while attempting to do this.

So far I have tried making a map, that uses the jobs ID as a key and will have the return value of that job stored in it. My struggle is
1. I cant figure out how to determine the type (I can with "typename std::invoke_result::type" but this breaks down if the type is void)
2. How to make a map that can have the Job ID as a key and any type so that I can put return types there.

class ThreadPool{
public:

    //getInstance to allow the second constructor to be called
    static ThreadPool& getInstance(int numThreads){
        static ThreadPool instance(numThreads);

        return instance;
    }

    //add any arg # function to queue
    template <typename Func, typename... Args >
    inline uint64_t push(Func& f, Args&&... args){
        auto funcToAdd = std::bind(f, args...);

        uint64_t newID = currentID++;
        std::unique_lock<std::mutex> lock(JobMutex);

        JobQueue.push(std::make_pair(funcToAdd, newID));
        thread.notify_one();
        return newID; //return the ID of the job in the queue
    }

    /* utility functions will go here*/
    inline void resize(int newTCount){

        int tmp = MAX_THREADS;
        if(newTCount > tmp || newTCount < 1){
            throw bad_thread_alloc("Cannot allocate " + std::to_string(newTCount) + " threads because it is greater than your systems maximum of " + std::to_string(tmp), __FILE__, __LINE__);
        }

        numThreads = (uint8_t)newTCount;
        Pool.resize(newTCount);
        DEBUG("New size is: " + std::to_string(Pool.size()));
    }

    inline uint8_t getThreadCount(){
        return numThreads;
    }

        //how i want the user to interact with this class is
        // int id = push(func, args);
        // auto value = getReturnValue(id); //blocks until return value is returned
    auto getReturnValue(uint64_t jobID) {
        //Not sure how to handle this
    }

private:

    uint64_t currentID;
    uint8_t numThreads;
    std::vector<std::thread> Pool; //the actual thread pool
    std::queue<std::pair<std::function<void()>, uint64_t>> JobQueue; //the jobs with their assigned ID
    std::condition_variable thread;
    std::mutex JobMutex;

    /* infinite loop function */
    void threadManager();

    /*  Constructors */
    ThreadPool(); //prevent default constructor from being called

    //real constructor that is used
    inline ThreadPool(uint8_t numThreads) : numThreads(numThreads) {
        currentID = 0; //initialize currentID
        int tmp = MAX_THREADS;
        if(numThreads > tmp){
            throw bad_thread_alloc("Cannot allocate " + std::to_string(numThreads) + " threads because it is greater than your systems maximum of " + std::to_string(tmp), __FILE__, __LINE__);
        }
        for(int i = 0; i != numThreads; ++i){
            Pool.push_back(std::thread(&ThreadPool::threadManager, this));
            Pool.back().detach();
            DEBUG("Thread " + std::to_string(i) + " allocated");
        }
        DEBUG("Number of threads being allocated " + std::to_string(numThreads));
    }
    /* end constructors */

NULL_COPY_AND_ASSIGN(ThreadPool);
}; /* end ThreadPool Class */

void ThreadPool::threadManager(){
    while (true) {

        std::unique_lock<std::mutex> lock(JobMutex);
        thread.wait(lock, [this] {return !JobQueue.empty(); });

        //strange bug where it will continue even if the job queue is empty
        if (JobQueue.size() < 1)
            continue;

        auto job = JobQueue.front().first;
        JobQueue.pop();
        job();
    }
}

Am I going about this all wrong? I didnt know any other way to generically store any type of function while also being able to get return types out of them.

Body:
Provide a location to store the return value to the function that creates the job. If we provide the return location together with the other elements, then there's no uncertainty about where the job gets stored.

We can design this part of the interface relatively simply. If we package the arguments together with the function, we can store all queued jobs as std::function<void()>. This simplifies the implementation of the thread queue, since the thread queue only has to worry about one type of std::function, and doesn't have to care at all about the return value.

using job_t = std::function<void()>;

template<class Return, class Func, class... Args>
job_t createJob(Return& dest, Func&& func, Args&&... args) {
    return job_t([=]() {
        dest = func(std::forward<Args>(args)...);
    });
};

This implementation makes it easy to start jobs asynchronously at will, without the thread pool worrying about where the return value gets stored. As an example, I wrote a function to run a job. The function starts the job on a new thread, and it marks an atomic_bool as true when the function completes. Because we don't have to worry about the return value, the function only has to return a shared_ptr to the atomic_bool we use to check if the function's finished.

using std::shared_ptr;
using std::atomic_bool;

shared_ptr<atomic_bool> run_job_async(std::function<void()> func) {
    shared_ptr<atomic_bool> is_complete = std::make_shared<atomic_bool>(false);
    std::thread t([f = std::move(func), =]() {
        f();
        *is_complete = true;
    });
    t.detach();
    return is_complete;
}


问:
Find an element in a list of tuples
I have a list 'a'

```<code>a= [(1,2),(1,4),(3,5),(5,7)]
</code>```

I need to find all the tuples for a particular number. say for 1 it will be

```<code>result = [(1,2),(1,4)]
</code>```

How do I do that?

答:
if you want to search tuple for any number which is present in tuple then you can use

```<code>a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)
</code>```

You can also use if i==j[0] or i==j[index] if you want to search a number in particular index

Title: Find an element in a list of tuples

Body:
I have a list 'a'

a= [(1,2),(1,4),(3,5),(5,7)]

I need to find all the tuples for a particular number. say for 1 it will be

result = [(1,2),(1,4)]

How do I do that?

Body:
if you want to search tuple for any number which is present in tuple then you can use

a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)

You can also use if i==j[0] or i==j[index] if you want to search a number in particular index


问:
left and right objects are evaluated / resolved during runtime or compile-time?
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();
```

<p>...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...</p>

<pre class="lang-java prettyprint-override"><code>left.invoke (right);
</code>```

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right

答:
Actually, I think that the technically correct answer is "none of the above".

At compile time, you need to know the declared types of the left variable (Left) and the right variable (Right).  This will determine which method overload1 of the Left::invoke method is most applicable to a parameter of type Right.

At runtime, the actual type of left will determine which actual method gets called.

So the complete answer is:

E) based on compile-time AND runtime types of left and on the compile-time type of right.

However, I suspect that the point of this question in the textbook is to help you distinguish between compile-time resolution of non-overloaded methods and runtime method dispatching.  For that purpose, A) is "correct enough".

1 - To make the determination, the compiler needs to compare Right and its supertypes with the different method overloads of the invoke method declared by Left and its supertypes.   If there are multiple overloads, the compiler needs to choose the "most specific applicable" overload.

Body:
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();

...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...

left.invoke (right);

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right


问:
How to convert object into string in javascript?
I have a function that should take as an argument of the object and return a string

The code I wrote.

```<code>function check(obj) {
  return obj.toString();
}
</code>```

答:
If your object is like

```<code>const obj = { name: "John", age: 30, city: "New York" };
</code>```

Use the JavaScript function JSON.stringify() to convert it into a string.
Like this JSON.stringify(obj).
then you will get this string:

"{"name":"John","age":30,"city":"New York"}"

Body:
I have a function that should take as an argument of the object and return a string

The code I wrote.

function check(obj) {
  return obj.toString();
}

Body:
If your object is like

const obj = { name: "John", age: 30, city: "New York" };

Use the JavaScript function JSON.stringify() to convert it into a string.
Like this JSON.stringify(obj).
then you will get this string:

"{"name":"John","age":30,"city":"New York"}"


问:
Fluent NHibernate: How to map a db integer to a datetime column?
I have a class

```<code>public class Site {
  public DateTime SiteMonth {get; set;}
}
</code>```

in the database the SiteMonth is represented as an integer in yyyymm format.

Is there a way to map this in NHibernate without introducing a new property on my Site class?

答:
Yes - make a simple IUserType that maps between your integer format and a DateTime. Then set the type attribute on the property element to the AssemblyQualifiedName of that user type.

Ayende has an example on how to implement a user type.

Oh yeah, and if you are using Fluent NHibernate to do your mappings, you can do it like this:

```<code>Map(d => d.MyFunkyWeirdLegacyDateTime)
    .SetAttribute("type", typeof(MyCustomDateTime).AssemblyQualifiedName);
</code>```

OwnerDisplayName: George Mauer

ContentLicense: CC BY-SA 2.5

Body:
I have a class

public class Site {
  public DateTime SiteMonth {get; set;}
}

in the database the SiteMonth is represented as an integer in yyyymm format.

Is there a way to map this in NHibernate without introducing a new property on my Site class?

Body:
Yes - make a simple IUserType that maps between your integer format and a DateTime. Then set the type attribute on the property element to the AssemblyQualifiedName of that user type.

Ayende has an example on how to implement a user type.

Oh yeah, and if you are using Fluent NHibernate to do your mappings, you can do it like this:

Map(d => d.MyFunkyWeirdLegacyDateTime)
    .SetAttribute("type", typeof(MyCustomDateTime).AssemblyQualifiedName);

OwnerDisplayName: mookid

LastEditorDisplayName: mookid


问:
How to write artisan command to search for specific routes name in Laravel
I'm writing command for Laravel to search for a specific route pattern.

I created command with argument {route} which execute bash command and echo the result.

```<code>protected $signature = 'routes:find {route}';

  public function handle()
    {
        echo  exec('php artisan route:list | grep '.$this->argument('route'));
    }
</code>```

the problem is this command output the routes in one line and does not offer any formatting like default route:list command.

答:
If you exec that command, it won't work in Windows. Also it is not guaranteed that the grep command is present as well.

Why don't you go after the original route:list command implementation?

If you check RouteListCommand.php file (search it in your vendor directory), you'll find a better way to search for a route, starting from this

```<code>public function __construct(Router $router)
{
    parent::__construct();

    $this->router = $router;
    $this->routes = $router->getRoutes();
}
</code>```

The right approach is to delegate the Illuminate\Routing\Router object to provide routes for you.

Body:
I'm writing command for Laravel to search for a specific route pattern.

I created command with argument {route} which execute bash command and echo the result.

protected $signature = 'routes:find {route}';

  public function handle()
    {
        echo  exec('php artisan route:list | grep '.$this->argument('route'));
    }

the problem is this command output the routes in one line and does not offer any formatting like default route:list command.

Body:
If you exec that command, it won't work in Windows. Also it is not guaranteed that the grep command is present as well.

Why don't you go after the original route:list command implementation?

If you check RouteListCommand.php file (search it in your vendor directory), you'll find a better way to search for a route, starting from this

public function __construct(Router $router)
{
    parent::__construct();

    $this->router = $router;
    $this->routes = $router->getRoutes();
}

The right approach is to delegate the Illuminate\Routing\Router object to provide routes for you.


答:
You are using $result wrong in code
See

```<code>    if (isset($_POST['submit-search'])) {
        $search = mysqli_real_escape_string($conn, $_POST['search']);
       // $sql = 'SELECT * FROM professional, job, location WHERE J.JOB_ID = P.PROFESSIONAL_ID AND P.PROFESSIONAL_ID = L.LOCATION_ID AND PROFESSIONAL_NAME LIKE '%$search%'';
        $sql = "SELECT * FROM professional, job, location WHERE JOB_NAME LIKE '%$search%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
        $result = mysqli_query($conn, $sql);
        $queryResult = mysqli_num_rows($result);
        while($row=mysqli_fetch_assoc($result)){
                if ($row['JOB_NAME'] == '%computer%' || '%programmer%' || '%computer programmer%')
                {
                echo "
                <div class= 'expertise'>
                <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='computer_programmer.html'> Computer Programmer</a></h2>
                </div>";
                }
                else if ($row['JOB_NAME'] =='%data%' || '%analyst%' || '%data analyst%'){
                    echo "
                <div class= 'expertise'>
                <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='data_analyst.html'> Data Analyst</a></h2>
                </div>";
                }
        }

        } else {
            echo 'There are no results matching your search!';
        }
</code>```

Hope this helps you

Title: Why does my search query doesn't turn out well?

Body:
I am tring to make my search function works. It does work but, the result is not true. For example, I search for the word 'data' and it display 'computer programmer'. It suppose to display 'Data Analyst'.

if (isset($_POST['submit-search'])) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
   // $sql = 'SELECT * FROM professional, job, location WHERE J.JOB_ID = P.PROFESSIONAL_ID AND P.PROFESSIONAL_ID = L.LOCATION_ID AND PROFESSIONAL_NAME LIKE '%$search%'';
    $sql = "SELECT * FROM professional, job, location WHERE JOB_NAME LIKE '%$search%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);
    $row = mysqli_fetch_assoc($result);
    $new_result = $row["JOB_NAME"];

    function str_contains($phrase, $word) {
        return strpos($phrase, $word) !== false;
    }

    if (str_contains($new_result,'computer') || str_contains($new_result, 'programmer') || str_contains($new_result, 'computer programmer')) {
        echo "

 Computer Programmer

";
    } else if (str_contains($new_result, 'data') || str_contains($new_result, 'analyst') || str_contains($new_result, 'data analyst')) {
        echo "

 Data Analyst

";
    } else {
        echo 'There are no results matching your search!';
    }
}

Body:
You are using $result wrong in code
See

    if (isset($_POST['submit-search'])) {
        $search = mysqli_real_escape_string($conn, $_POST['search']);
       // $sql = 'SELECT * FROM professional, job, location WHERE J.JOB_ID = P.PROFESSIONAL_ID AND P.PROFESSIONAL_ID = L.LOCATION_ID AND PROFESSIONAL_NAME LIKE '%$search%'';
        $sql = "SELECT * FROM professional, job, location WHERE JOB_NAME LIKE '%$search%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
        $result = mysqli_query($conn, $sql);
        $queryResult = mysqli_num_rows($result);
        while($row=mysqli_fetch_assoc($result)){
                if ($row['JOB_NAME'] == '%computer%' || '%programmer%' || '%computer programmer%')
                {
                echo "
                <div class= 'expertise'>
                <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='computer_programmer.html'> Computer Programmer</a></h2>
                </div>";
                }
                else if ($row['JOB_NAME'] =='%data%' || '%analyst%' || '%data analyst%'){
                    echo "
                <div class= 'expertise'>
                <h2><i class='fa fa-briefcase' aria-hidden='true'></i><a href='data_analyst.html'> Data Analyst</a></h2>
                </div>";
                }
        }

        } else {
            echo 'There are no results matching your search!';
        }

Hope this helps you


问:
Checking if a table exists and if it does not exist, create it... iOS/SQLite
I currently have a table that exists which I'm able to pull data from.  What I would like to do is check if the table already exists in the bundle, and if it does not, I want to create the table and save it to the bundle (meaning the path would be in the main bundle).  I want the database to be checked and created at the top of the setInput method.  I've been scouring SO for something similar to this, but I haven't come up with anything yet.  Any help is very appreciated.  Here is my code:

```<code>-(IBAction)setInput:(id)sender
{
    NSString *strStoreNumber;
    NSString *strRegNumber;

    strStoreNumber = StoreNumber.text;
    strRegNumber = RegNumber.text;
    lblStoreNumber.text = strStoreNumber;
    lblRegNumber.text = strRegNumber;

    NSString* databasePath = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];

    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        NSLog(@"Opened sqlite database at %@", databasePath);
        sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS tblStore (ID INTEGER PRIMARY KEY AUTOINCREMENT, Message TEXT)", NULL, NULL, NULL);
        //...stuff
    }
    else
    {
        NSLog(@"Failed to open database at %@ with error %s", databasePath, sqlite3_errmsg(database));
        sqlite3_close (database);
    }
//
    NSString *querystring;

    // create your statement
    querystring = [NSString stringWithFormat:@"SELECT strStore, strReg FROM tblStore WHERE strStore = %@ AND strReg = %@;", strStoreNumber, strRegNumber];

    const char *sql = [querystring UTF8String];

    NSString *szStore = nil;
    NSString *szReg = nil;

    sqlite3_stmt *statement = nil;
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL)!=SQLITE_OK) //queryString = Statement
    {
        NSLog(@"sql problem occured with: %s", sql);
        NSLog(@"%s", sqlite3_errmsg(database));
    }
    else
    {
        // you could handle multiple rows here
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
            szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
        }

    }

    sqlite3_finalize(statement);

    lblStoreNumber.text = szStore;
    lblRegNumber.text = szReg;

//
}
</code>```

I'm still quite new to iOS and SQLite, so if I did not provide an accurate enough description of what I'm trying to do, let me know and I'll try to be more specific.  Thanks!

答:
Create table using sqlite swift</p>

```<code>func createTable(_ tableName:String) {
        sqlStatement = "CREATE TABLE \(tableName)(Id TEXT,Details BLOB,Type TEXT)"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_DONE {
                print("table created")
            }
            else {
                print("table could not be created")
            }
        }
        else {
            print("Create table statement could not be prepared")
        }
        sqlite3_finalize(compiledStatement)
    }
</code>```

Body:
I currently have a table that exists which I'm able to pull data from.  What I would like to do is check if the table already exists in the bundle, and if it does not, I want to create the table and save it to the bundle (meaning the path would be in the main bundle).  I want the database to be checked and created at the top of the setInput method.  I've been scouring SO for something similar to this, but I haven't come up with anything yet.  Any help is very appreciated.  Here is my code:

-(IBAction)setInput:(id)sender
{
    NSString *strStoreNumber;
    NSString *strRegNumber;

    strStoreNumber = StoreNumber.text;
    strRegNumber = RegNumber.text;
    lblStoreNumber.text = strStoreNumber;
    lblRegNumber.text = strRegNumber;

    NSString* databasePath = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];

    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        NSLog(@"Opened sqlite database at %@", databasePath);
        sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS tblStore (ID INTEGER PRIMARY KEY AUTOINCREMENT, Message TEXT)", NULL, NULL, NULL);
        //...stuff
    }
    else
    {
        NSLog(@"Failed to open database at %@ with error %s", databasePath, sqlite3_errmsg(database));
        sqlite3_close (database);
    }
//
    NSString *querystring;

    // create your statement
    querystring = [NSString stringWithFormat:@"SELECT strStore, strReg FROM tblStore WHERE strStore = %@ AND strReg = %@;", strStoreNumber, strRegNumber];

    const char *sql = [querystring UTF8String];

    NSString *szStore = nil;
    NSString *szReg = nil;

    sqlite3_stmt *statement = nil;
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL)!=SQLITE_OK) //queryString = Statement
    {
        NSLog(@"sql problem occured with: %s", sql);
        NSLog(@"%s", sqlite3_errmsg(database));
    }
    else
    {
        // you could handle multiple rows here
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
            szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
        }

    }

    sqlite3_finalize(statement);

    lblStoreNumber.text = szStore;
    lblRegNumber.text = szReg;

//
}

I'm still quite new to iOS and SQLite, so if I did not provide an accurate enough description of what I'm trying to do, let me know and I'll try to be more specific.  Thanks!

Body:
Create table using sqlite swift

func createTable(_ tableName:String) {
        sqlStatement = "CREATE TABLE \(tableName)(Id TEXT,Details BLOB,Type TEXT)"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_DONE {
                print("table created")
            }
            else {
                print("table could not be created")
            }
        }
        else {
            print("Create table statement could not be prepared")
        }
        sqlite3_finalize(compiledStatement)
    }


问:
Change article_custom so that 'past' doesn't exclude an event on the current date
I'm using textpattern and trying to display a list of upcoming events.  I'm using article_custom.

```<code><txp:article_custom
   form="eventshome"
   limit="4"
   time="future"
   sort="Posted
   section="events" />
</code>```

The issue I have is that this is supposed to show events coming up but using 'future' means that when an event is on the current date it's not showing (it's not future anymore).  Both 'past' and 'future' time options seem to exclude the current date. That means people coming on the site don't see an event on that day which is a bit of an issue.

I've had a quick look around the code but can't seem to work out how to change the SQL statement so that future includes the current date.

Any help appreciated.

答:
You can try plugin smd_calendar - http://stefdawson.com/sw/plugins/smd_calendar
it supports a lot of methods to display upcomming and past events. </p>

Body:
I'm using textpattern and trying to display a list of upcoming events.  I'm using article_custom.

<txp:article_custom
   form="eventshome"
   limit="4"
   time="future"
   sort="Posted
   section="events" />

The issue I have is that this is supposed to show events coming up but using 'future' means that when an event is on the current date it's not showing (it's not future anymore).  Both 'past' and 'future' time options seem to exclude the current date. That means people coming on the site don't see an event on that day which is a bit of an issue.

I've had a quick look around the code but can't seem to work out how to change the SQL statement so that future includes the current date.

Any help appreciated.


答:
If you wish to count up the number of occurrences without creating a nearly-unused intermediate array, you can use reduce:

const count = arr => arr.reduce((a, item) => a + (item && item.constructor === Object), 0);

console.log(count([1, [], null, 3, 4, 5, {}, {}, {}, 'foo']));```

Title: How to count the objects in javascript?

Body:
I have a function which takes an array of many data types.

function count(totalObjs) {
    var count = 0;
    for (var i = 0; i <= arr.length; i++) {

        count++;
    }
    return count;
}


问:
'ignite' is not recognized as an internal or external command
I recently discovered Ignite and followed the guide from here: https://github.com/infinitered/ignite to install it. I get a few warnings on install but nothing serious:

```<code>npm WARN deprecated cross-spawn-async@2.2.4: cross-spawn no longer requires a build toolchain, use it instead!
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
C:\Users\adrians\AppData\Roaming\npm\ignite -> C:\Users\adrians\AppData\Roaming\npm\node_modules\react-native-ignite\index.js
</code>```

and:

```<code>npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\adrians\AppData\Roaming\package.json'
npm WARN adrians No description
npm WARN adrians No repository field.
npm WARN adrians No README data
npm WARN adrians No license field.
</code>```

Then, when trying to run:

```<code>ignite new MyApplication
</code>```

I get the following error message:

```<code>'ignite' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I use Windows 10 by the way. Any ideea what to do next?
I already tried adding a system variable for the ignite folder but no luck so far.

答: Try to npm install -g react-native-ignite it worked from me.

Body:
I recently discovered Ignite and followed the guide from here: https://github.com/infinitered/ignite to install it. I get a few warnings on install but nothing serious:

npm WARN deprecated cross-spawn-async@2.2.4: cross-spawn no longer requires a build toolchain, use it instead!
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
C:\Users\adrians\AppData\Roaming\npm\ignite -> C:\Users\adrians\AppData\Roaming\npm\node_modules\react-native-ignite\index.js

and:

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\adrians\AppData\Roaming\package.json'
npm WARN adrians No description
npm WARN adrians No repository field.
npm WARN adrians No README data
npm WARN adrians No license field.

Then, when trying to run:

ignite new MyApplication

I get the following error message:

'ignite' is not recognized as an internal or external command,
operable program or batch file.

I use Windows 10 by the way. Any ideea what to do next?
I already tried adding a system variable for the ignite folder but no luck so far.


问:
Multi-column file parsing with Kotlin
I have a four columns text file and want to create two vectors with it.
I intend to use the first and second columns as a mixed index.
So the first and second columns are integer and 3rd and 4th are double.
In FORTRAN it would be:

```<code>10 READ("4Column_file.txt",*,END=20)N,M,T1,T2
   IG=(N*(N+1))/2+M+1
   CC(IG)=T1
   CS(IG)=T2
   GOTO 10
20 CONTINUE
</code>```

How I do it with Kotlin or Java?

The input is in the form:

```<code>5   5  -0.244048470535508183D+00  -0.129800076712784507D+01
6   0  -0.468652527040705080D+01   0.000000000000000000D+00
</code>```

The output would be CC[IG] and CS[IG] vectors loaded.

For example in the first line:
 IG=(5*(5+1))/2+5+1=21
so CC[21]=-0.244048470535508183D+00 and CS[21]=-0.129800076712784507D+01.

In the second line:
 IG=(6*(6+1))/2+5+1=27
so CC[27]=-0.468652527040705080D+01 and CS[27]=0.000000000000000000D+00

答:
You could use a library like univocity-parsers. There is a tutorial about parsing tab separated files:

https://www.univocity.com/pages/univocity_parsers_tsv.html#working-with-tsv

Since Kotlin is running on the JVM and is 100% interoperable with Java, you can simply include the univocity-parsers jar as dependency instead of coding it yourself - here the Maven coordinates:

<dependency>
  <groupId>com.univocity</groupId>
  <artifactId>univocity-parsers</artifactId>
  <version>2.8.2</version>
</dependency>
```

Title: Multi-column file parsing with Kotlin

Body:
I have a four columns text file and want to create two vectors with it.
I intend to use the first and second columns as a mixed index.
So the first and second columns are integer and 3rd and 4th are double.
In FORTRAN it would be:

10 READ("4Column_file.txt",*,END=20)N,M,T1,T2
   IG=(N*(N+1))/2+M+1
   CC(IG)=T1
   CS(IG)=T2
   GOTO 10
20 CONTINUE

How I do it with Kotlin or Java?

The input is in the form:

5   5  -0.244048470535508183D+00  -0.129800076712784507D+01
6   0  -0.468652527040705080D+01   0.000000000000000000D+00

The output would be CC[IG] and CS[IG] vectors loaded.

For example in the first line:
 IG=(5*(5+1))/2+5+1=21
so CC[21]=-0.244048470535508183D+00 and CS[21]=-0.129800076712784507D+01.

In the second line:
 IG=(6*(6+1))/2+5+1=27
so CC[27]=-0.468652527040705080D+01 and CS[27]=0.000000000000000000D+00


问:
saving the form in django
I want to save a simple form in Django2

But when I send the form data it gave me an error:

```<code> __init__() got an unexpected keyword argument 'name'
</code>```

this is my form

```<code>class Message(forms.Form):
name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
email = forms.EmailField(widget=forms.TextInput(
    attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
messages = forms.CharField(widget=forms.Textarea(
    attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))
</code>```

this is my view

```<code> def index(request):
if request.method == 'POST':
    form = Message(request.POST)
    if form.is_valid():
        new_messages = Message(name=request.POST['name'], email=request.POST['email'],
                               messages=request.POST['messages'])
        new_messages.save()
        return redirect('index')
    else:
        form = Message()
</code>```

and this is my model

```<code>class Message(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
messages = models.TextField()

def __str__(self):
    return self.name
</code>```

I try to change the name to anything you think but it did not work.

how can I fix this?

答:
You have to to do like this

```<code>data=form.cleaned_data
</code>```

And use this dictionary in message model , make sure you have name field in your message model

Title: saving the form in django

Body:
I want to save a simple form in Django2

But when I send the form data it gave me an error:

 __init__() got an unexpected keyword argument 'name'

this is my form

class Message(forms.Form):
name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
email = forms.EmailField(widget=forms.TextInput(
    attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
messages = forms.CharField(widget=forms.Textarea(
    attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))

this is my view

 def index(request):
if request.method == 'POST':
    form = Message(request.POST)
    if form.is_valid():
        new_messages = Message(name=request.POST['name'], email=request.POST['email'],
                               messages=request.POST['messages'])
        new_messages.save()
        return redirect('index')
    else:
        form = Message()

and this is my model

class Message(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
messages = models.TextField()

def __str__(self):
    return self.name

I try to change the name to anything you think but it did not work.

how can I fix this?

Body:
You have to to do like this

data=form.cleaned_data

And use this dictionary in message model , make sure you have name field in your message model


问:
How is the r-value reference being passed in here?
```<code>void test(vector<int> v) {
    for(int i:v) cout<< i<<" ";
}
int main()
{
    vector<int> v{ 1,2,3 };
    test(move(v));
    cout << "v is gone....";
}
</code>```

I am new to move semantics and rvalue references. In the code above, the vector is printed. Clearly the move worked.

What I don't understand is how it worked. Why don't I have to define a function that takes in an rvalue reference? My best guess is the compiler is generating this automatically:

```<code>void test(vector<int>&& v) {
    for(int i:v) cout<< i<<" ";
}
</code>```

答:
My best guess is the compiler is generating this automatically

The only code a compiler will generate automatically is for constructors, assignment operators and destructors. And those have caveats. What's happening here is not about auto generated code. When you write test(move(v)) (for some type V), that can be made to work in a couple of ways.

test accepts an argument of type V&&. That will happily bind to the rvalue reference you provided.

test accepts an argument of type V const&. Const lvlaue references bind to rvalue reference arguments too. That way old code that is not adjusted for move semantics can still work. A const lvlaue reference is a handy fallback.

test accepts a V. Here cases (1) and (2) can applied to the constructors of V.

In our specific case, std::vector has a move constructor ready to accept the reference you provided.

Body:
void test(vector<int> v) {
    for(int i:v) cout<< i<<" ";
}
int main()
{
    vector<int> v{ 1,2,3 };
    test(move(v));
    cout << "v is gone....";
}

I am new to move semantics and rvalue references. In the code above, the vector is printed. Clearly the move worked.

What I don't understand is how it worked. Why don't I have to define a function that takes in an rvalue reference? My best guess is the compiler is generating this automatically:

void test(vector<int>&& v) {
    for(int i:v) cout<< i<<" ";
}


问:
Strip tag with class in PHP
So I need to strip the span tags of class tip.
So that would be  and the corresponding , and everything inside it...

I suspect a regular expression is needed but I terribly suck at this.

Laugh...

```<code><?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>
</code>```

Gives no error... But

```<code><?php
$str = preg_replace('<span class="tip">.+</span>', "", '<span class="rss-title"></span><span class="rss-link">linkylink</span><span class="rss-id"></span><span class="rss-content"></span><span class=\"rss-newpost\"></span>');
echo $str;
?>
</code>```

Gives me the error:

```<code>Warning: preg_replace() [function.preg-replace]: Unknown modifier '.' in <A FILE> on line 4
</code>```

previously, the error was at the ); in the 2nd line, but now.... >.>

答:
A simple regular expression like:

```<code><span class="tip">.+</span>
</code>```

Wont work, the issue being that if another span was opened and closed inside the tip span, your regex will terminate with its ending, rather than the tip one. DOM Based tools like the one linked in the comments will really provide a more reliable answer.

As per my comment below, you need to add pattern delimiters when working with regular expressions in PHP.

```<code><?php
$str = preg_replace('\<span class="tip">.+</span>\', "", '<span class="rss-title"></span><span class="rss-link">linkylink</span><span class="rss-id"></span><span class="rss-content"></span><span class=\"rss-newpost\"></span>');
echo $str;
?>
</code>```

may be moderately more successful. Please take a look at the documentation page for the function in question.

Title: Strip tag with class in PHP

Body:
So I need to strip the span tags of class tip.
So that would be  and the corresponding , and everything inside it...

I suspect a regular expression is needed but I terribly suck at this.

Laugh...

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

Gives no error... But

<?php
$str = preg_replace('.+', "", 'linkylink');
echo $str;
?>

Gives me the error:

Warning: preg_replace() [function.preg-replace]: Unknown modifier '.' in  on line 4

previously, the error was at the ); in the 2nd line, but now.... >.>

Body:
A simple regular expression like:

<span class="tip">.+</span>

Wont work, the issue being that if another span was opened and closed inside the tip span, your regex will terminate with its ending, rather than the tip one. DOM Based tools like the one linked in the comments will really provide a more reliable answer.

As per my comment below, you need to add pattern delimiters when working with regular expressions in PHP.

<?php
$str = preg_replace('\<span class="tip">.+</span>\', "", '<span class="rss-title"></span><span class="rss-link">linkylink</span><span class="rss-id"></span><span class="rss-content"></span><span class=\"rss-newpost\"></span>');
echo $str;
?>

may be moderately more successful. Please take a look at the documentation page for the function in question.


问:
Can't render route with switch statements React router dom 5.0.0
I'm fairly new to React Router.. I'm using React-router-dom 5.0.0

My dashboard route isn't matching for some reason and nothing is rendered when I navigate to /dashboard

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

import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from './theme';

import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';

const MarketPlace = React.lazy(() => import('./marketplace/MarketPlace'));
const Dashboard = React.lazy(() => import('./dashboard/Dashboard'));

const mainApp = (
  <MuiThemeProvider theme={theme}>
    <BrowserRouter>
      <Switch>
        <Redirect exact from="/" to="/marketplace" />
        <Suspense fallback="Loading...">
          <Route component={MarketPlace} exact path="/marketplace" />
        </Suspense>
        <Suspense fallback="Loading...">
          <Route component={Dashboard} exact path="/dashboard" />
        </Suspense>
      </Switch>
    </BrowserRouter>
  </MuiThemeProvider>
);

ReactDOM.render(mainApp, document.getElementById('root'));
</code>```

Am I doing something incorrectly?

答:
The Suspense element should be outside of your switch block, like this:

```<code>const App: React.FC = (props) => (
  <BrowserRouter>
      <React.Suspense fallback="Loading...">
        <Switch>
          <Route path="/dashboard" component={Dashboard} />
          <Route path="/other" component={Other} />
          <Redirect to="/dashboard" />
        </Switch>
      </React.Suspense>
    </BrowserRouter>
);
</code>```

Example

Body:
I'm fairly new to React Router.. I'm using React-router-dom 5.0.0

My dashboard route isn't matching for some reason and nothing is rendered when I navigate to /dashboard

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

import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from './theme';

import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';

const MarketPlace = React.lazy(() => import('./marketplace/MarketPlace'));
const Dashboard = React.lazy(() => import('./dashboard/Dashboard'));

const mainApp = (
  <MuiThemeProvider theme={theme}>
    <BrowserRouter>
      <Switch>
        <Redirect exact from="/" to="/marketplace" />
        <Suspense fallback="Loading...">
          <Route component={MarketPlace} exact path="/marketplace" />
        </Suspense>
        <Suspense fallback="Loading...">
          <Route component={Dashboard} exact path="/dashboard" />
        </Suspense>
      </Switch>
    </BrowserRouter>
  </MuiThemeProvider>
);

ReactDOM.render(mainApp, document.getElementById('root'));

Am I doing something incorrectly?

Body:
The Suspense element should be outside of your switch block, like this:

const App: React.FC = (props) => (
  <BrowserRouter>
      <React.Suspense fallback="Loading...">
        <Switch>
          <Route path="/dashboard" component={Dashboard} />
          <Route path="/other" component={Other} />
          <Redirect to="/dashboard" />
        </Switch>
      </React.Suspense>
    </BrowserRouter>
);

Example