问:
getting Invalid Email or Password in my localhost website
i'm using php 7.2.31 .. i'v already imported my DB file in phpmyAdmin

when i'm trying to login in admin website page (or the others 2 users ) it's getting this message  :-

(Invalid Email or Password )

the email address and password already in the database and it's correct  .. ! !

here's my login-in code :-

```<code><?php session_start();?>

<link rel="stylesheet" href="popup_style.css">
<!DOCTYPE html>
<html lang="en">

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<title>Admin Panel</title>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="#">
<meta name="keywords" content="Admin , Responsive">
<meta name="author" content="Nikhil Bhalerao +919423979339.">

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="files/bower_components/bootstrap/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="files/assets/icon/themify-icons/themify-icons.css">

<link rel="stylesheet" type="text/css" href="files/assets/icon/icofont/css/icofont.css">

<link rel="stylesheet" type="text/css" href="files/assets/css/style.css">
</head>
<body class="fix-menu">

<?php
  include('connect.php');
  extract($_POST);
if(isset($_POST['btn_login']))
{
  $passw = hash('sha256', $_POST['password']);
  function createSalt()
  {
      return '2123293dsj2hu2nikhiljdsd';
  }
  $salt = createSalt();
  $pass = hash('sha256', $salt . $passw);
//echo $pass;
  if($_POST['user'] == 'admin'){
    $sql = "SELECT * FROM admin WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);
    $_SESSION["adminid"] = $row['id'];
     $_SESSION["id"] = $row['id'];
     $_SESSION["username"] = $row['username'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['fname'];
     $_SESSION["lname"] = $row['lname'];
     $_SESSION['image'] = $row['image'];
     $_SESSION['user'] = $_POST['user'];
  }else if($_POST['user'] == 'doctor'){
    $sql = "SELECT * FROM doctor WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);

    $_SESSION["doctorid"] = $row['doctorid'];
     $_SESSION["id"] = $row['doctorid'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['doctorname'];
     $_SESSION['user'] = $_POST['user'];
  }else if($_POST['user'] == 'patient'){
    $sql = "SELECT * FROM patient WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);
    $_SESSION["patientid"] = $row['patientid'];
     $_SESSION["id"] = $row['patientid'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['patientname'];
     $_SESSION['user'] = $_POST['user'];
  }
    //print_r($row);
     $count=mysqli_num_rows($result);
     if($count==1 && isset($_SESSION["email"]) && isset($_SESSION["password"])) {
    {
        ?>
         <div class="popup popup--icon -success js_success-popup popup--visible">
          <div class="popup__background"></div>
          <div class="popup__content">
            <h3 class="popup__content__title">
              Success
            </h3>
            <p>Login Successfully</p>
            <p>
             <!--  <a href="index.php"><button class="button button--success" data-for="js_success-popup"></button></a> -->
             <?php echo "<script>setTimeout(\"location.href = 'index.php';\",1500);</script>"; ?>
            </p>
          </div>
        </div>
   <!--   <script>
     window.location="index.php";
     </script> -->
     <?php
    }
}
else {?>
     <div class="popup popup--icon -error js_error-popup popup--visible">
      <div class="popup__background"></div>
      <div class="popup__content">
        <h3 class="popup__content__title">
          Error
        </h3>
        <p>Invalid Email or Password</p>
        <p>
          <a href="login.php"><button class="button button--error" data-for="js_error-popup">Close</button></a>
        </p>
      </div>
    </div>

<?php
      }

   }
?>

<?php
$que="select * from manage_website";
$query=$conn->query($que);
while($row=mysqli_fetch_array($query))
{
  //print_r($row);
  extract($row);
  $business_name = $row['business_name'];
  $business_email = $row['business_email'];
  $business_web = $row['business_web'];
  $portal_addr = $row['portal_addr'];
  $addr = $row['addr'];
  $curr_sym = $row['curr_sym'];
  $curr_position = $row['curr_position'];
  $front_end_en = $row['front_end_en'];
  $date_format = $row['date_format'];
  $def_tax = $row['def_tax'];
  $logo = $row['logo'];
}
?>

<section class="login-block">

<div class="container-fluid">
<div class="row">
<div class="col-sm-12">

<div class="auth-box card" >
  <div class="text-center">
<image class="profile-img" src="uploadImage/Logo/<?php echo $logo; ?>" style="width: 60%"></image>
</div>
<div class="card-block" >

<div class="row m-b-20">
<div class="col-md-12">
<h5 class="text-center txt-primary">Sign In</h5>
</div>
</div>
  <form method="POST" >
    <div class="form-group form-primary">
      <select name="user" class="form-control" required="">
        <option value="">-- Select One --</option>
        <option value="admin">Admin</option>
        <option value="doctor">Doctor</option>
        <option value="patient">Patient</option>
      </select>
      <span class="form-bar"></span>
    </div>
    <div class="form-group form-primary">
      <input type="email" name="email" class="form-control" required="" placeholder="Email">
      <span class="form-bar"></span>
    </div>
    <div class="form-group form-primary">
      <input type="password" name="password" class="form-control" required="" placeholder="Password">
      <span class="form-bar"></span>
    </div>
    <div class="row m-t-25 text-left">
      <div class="col-12">
        <div class="forgot-phone text-right f-right">
          <a href="forgot_password.php" class="text-right f-w-600"> Forgot Password?</a>
        </div>
      </div>
    </div>
    <div class="row m-t-30">
      <div class="col-md-12">
        <button type="submit" name="btn_login" class="btn btn-primary btn-md btn-block waves-effect text-center m-b-20">LOGIN</button>
      </div>
    </div>
  </form>

</div>
</div>

</div>

</div>
</div>
</div>
</section>

<script type="text/javascript" src="files/bower_components/jquery/js/jquery.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-ui/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="files/bower_components/popper.js/js/popper.min.js"></script>
<script type="text/javascript" src="files/bower_components/bootstrap/js/bootstrap.min.js"></script>

<script type="text/javascript" src="files/bower_components/jquery-slimscroll/js/jquery.slimscroll.js"></script>

<script type="text/javascript" src="files/bower_components/modernizr/js/modernizr.js"></script>
<script type="text/javascript" src="files/bower_components/modernizr/js/css-scrollbars.js"></script>

<script type="text/javascript" src="files/bower_components/i18next/js/i18next.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-xhr-backend/js/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-browser-languagedetector/js/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-i18next/js/jquery-i18next.min.js"></script>
<script type="text/javascript" src="files/assets/js/common-pages.js"></script>

</body>

<!-- for any PHP, Codeignitor or Laravel work contact me at mayuri.infospace@gmail.com -->
</html>

</code>```

and the check-login file :-

```<code>
<?php
session_start();
if((isset($_SESSION["email"]) && isset($_SESSION["password"]))){
    $myemail = $_SESSION['email'];
}else {
    header("location:login.php");
}
?>
</code>```

thanks !

答:
You are getting
invalid Email and password because the variable $email which you are using in your query has no email from the form. After this line:

```<code>$pass = hash('sha256', $salt . $passw);
</code>```

Add this line:

```<code>$email = $_POST['email'];
</code>```

This will solve your problem. But there are many other other problems in your code like it is open to SQL injection. You can use prepare statements.
PHP Prepared Statements. Always validate the data coming from users.

Do not store password as a plain text. See here password-encryption-storing-password-in-session

If you want to get only one record from a database always use LIMIT 1 in your code.

Body:
i'm using php 7.2.31 .. i'v already imported my DB file in phpmyAdmin

when i'm trying to login in admin website page (or the others 2 users ) it's getting this message  :-

(Invalid Email or Password )

the email address and password already in the database and it's correct  .. ! !

here's my login-in code :-

<?php session_start();?>

<link rel="stylesheet" href="popup_style.css">
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<title>Admin Panel</title>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="#">
<meta name="keywords" content="Admin , Responsive">
<meta name="author" content="Nikhil Bhalerao +919423979339.">

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="files/bower_components/bootstrap/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="files/assets/icon/themify-icons/themify-icons.css">

<link rel="stylesheet" type="text/css" href="files/assets/icon/icofont/css/icofont.css">

<link rel="stylesheet" type="text/css" href="files/assets/css/style.css">

<?php
  include('connect.php');
  extract($_POST);
if(isset($_POST['btn_login']))
{
  $passw = hash('sha256', $_POST['password']);
  function createSalt()
  {
      return '2123293dsj2hu2nikhiljdsd';
  }
  $salt = createSalt();
  $pass = hash('sha256', $salt . $passw);
//echo $pass;
  if($_POST['user'] == 'admin'){
    $sql = "SELECT * FROM admin WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);
    $_SESSION["adminid"] = $row['id'];
     $_SESSION["id"] = $row['id'];
     $_SESSION["username"] = $row['username'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['fname'];
     $_SESSION["lname"] = $row['lname'];
     $_SESSION['image'] = $row['image'];
     $_SESSION['user'] = $_POST['user'];
  }else if($_POST['user'] == 'doctor'){
    $sql = "SELECT * FROM doctor WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);

    $_SESSION["doctorid"] = $row['doctorid'];
     $_SESSION["id"] = $row['doctorid'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['doctorname'];
     $_SESSION['user'] = $_POST['user'];
  }else if($_POST['user'] == 'patient'){
    $sql = "SELECT * FROM patient WHERE loginid='" .$email . "' and password = '". $pass."'";
    $result = mysqli_query($conn,$sql);
    $row  = mysqli_fetch_array($result);
    //print_r($row);
    $_SESSION["patientid"] = $row['patientid'];
     $_SESSION["id"] = $row['patientid'];
     $_SESSION["password"] = $row['password'];
     $_SESSION["email"] = $row['loginid'];
     $_SESSION["fname"] = $row['patientname'];
     $_SESSION['user'] = $_POST['user'];
  }
    //print_r($row);
     $count=mysqli_num_rows($result);
     if($count==1 && isset($_SESSION["email"]) && isset($_SESSION["password"])) {
    {
        ?>

              Success

Login Successfully

             <?php echo ""; ?>

     <?php
    }
}
else {?>

          Error

Invalid Email or Password

          <button class="button button--error" data-for="js_error-popup">Close</button>

<?php
      }

   }
?>

<?php
$que="select * from manage_website";
$query=$conn->query($que);
while($row=mysqli_fetch_array($query))
{
  //print_r($row);
  extract($row);
  $business_name = $row['business_name'];
  $business_email = $row['business_email'];
  $business_web = $row['business_web'];
  $portal_addr = $row['portal_addr'];
  $addr = $row['addr'];
  $curr_sym = $row['curr_sym'];
  $curr_position = $row['curr_position'];
  $front_end_en = $row['front_end_en'];
  $date_format = $row['date_format'];
  $def_tax = $row['def_tax'];
  $logo = $row['logo'];
}
?>

<image class="profile-img" src="uploadImage/Logo/<?php echo $logo; ?>" style="width: 60%"></image>

Sign In

  <form method="POST" >

      <select name="user" class="form-control" required="">
        <option value="">-- Select One --</option>
        <option value="admin">Admin</option>
        <option value="doctor">Doctor</option>
        <option value="patient">Patient</option>
      </select>

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

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

           Forgot Password?

        <button type="submit" name="btn_login" class="btn btn-primary btn-md btn-block waves-effect text-center m-b-20">LOGIN</button>

  </form>

and the check-login file :-

<?php
session_start();
if((isset($_SESSION["email"]) && isset($_SESSION["password"]))){
    $myemail = $_SESSION['email'];
}else {
    header("location:login.php");
}
?>

thanks !

Body:
You are getting
invalid Email and password because the variable $email which you are using in your query has no email from the form. After this line:

$pass = hash('sha256', $salt . $passw);

Add this line:

$email = $_POST['email'];

This will solve your problem. But there are many other other problems in your code like it is open to SQL injection. You can use prepare statements.
PHP Prepared Statements. Always validate the data coming from users.

Do not store password as a plain text. See here password-encryption-storing-password-in-session

If you want to get only one record from a database always use LIMIT 1 in your code.


来源: stackexchange

问:
Couldn't import library into AWS Lambda
I am trying to create an AWS Lambda function in Python 3.7. But facing an error while testing my function which is -

```<code>{
  "errorMessage": "Unable to import module 'lambda_function': No module named 's3fs'",
  "errorType": "Runtime.ImportModuleError"
}
</code>```

I know, by default Python environment doesn't have s3fs module imported. So I had to install the s3fs and some other packages in my local machine and zipped it. For zipping I used the following command.

Compress-Archive -Path dateutil, docutils, jmespath, s3fs, s3transfer, six.py ` -DestinationPath ..\..\..\pinpoint-importer.zip ;

(I followed the following documentation - https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-importing-data-create-python-package.html).

Then uploaded the .zip file in Lambda and cross-checked the Handler - "lambda_function.lambda_handler".

Please find the code below.

```<code>import os
import boto3
import s3fs
from botocore.exceptions import ClientError

input_archive_folder = "input_archive"
to_process_folder = "to_process"
file_row_limit = 50
file_delimiter = ','

# S3 bucket info
s3 = s3fs.S3FileSystem(anon=False)

def lambda_handler(event, context):
    print("Received event: \n" + str(event))
    for record in event['Records']:
        # Assign some variables that make it easier to work with the data in the
        # event record.
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        input_file = os.path.join(bucket,key)
        archive_path = os.path.join(bucket,input_archive_folder,os.path.basename(key))
        folder =  os.path.split(key)[0]
        s3_url = os.path.join(bucket,folder)
        output_file_template = os.path.splitext(os.path.basename(key))[0] + "__part"
        output_path = os.path.join(bucket,to_process_folder)

        # Set a variable that contains the number of files that this Lambda
        # function creates after it runs.
        num_files = file_count(s3.open(input_file, 'r'), file_delimiter, file_row_limit)

        # Split the input file into several files, each with 50 rows.
        split(s3.open(input_file, 'r'), file_delimiter, file_row_limit, output_file_template, output_path, True, num_files)

        # Send the unchanged input file to an archive folder.
        archive(input_file,archive_path)

# Determine the number of files that this Lambda function will create.
def file_count(file_handler, delimiter, row_limit):
    import csv
    reader = csv.reader(file_handler, delimiter=delimiter)
    # Figure out the number of files this function will generate.
    row_count = sum(1 for row in reader) - 1
    # If there's a remainder, always round up.
    file_count = int(row_count // row_limit) + (row_count % row_limit > 0)
    return file_count

# Split the input into several smaller files.
def split(filehandler, delimiter, row_limit, output_name_template, output_path, keep_headers, num_files):
    import csv
    reader = csv.reader(filehandler, delimiter=delimiter)

    current_piece = 1
    current_out_path = os.path.join(
         output_path,
         output_name_template + str(current_piece) + "__of" + str(num_files) + ".csv"
    )
    current_out_writer = csv.writer(s3.open(current_out_path, 'w'), delimiter=delimiter)
    current_limit = row_limit
    if keep_headers:
        headers = next(reader)
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
               output_path,
               output_name_template + str(current_piece) + "__of" + str(num_files) + ".csv"
            )
            current_out_writer = csv.writer(s3.open(current_out_path, 'w'), delimiter=delimiter)
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)

# Move the original input file into an archive folder.
def archive(input_file, archive_path):
    s3.copy_basic(input_file,archive_path)
    print("Moved " + input_file + " to " + archive_path)
    s3.rm(input_file)
</code>```

I followed this documentation - https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-importing-data-lambda-function-input-split.html

A screenshot -

Please let me know if I am missing something. Thanks.

答: It works if you add all the files that show up in the error message into the zip file, then manually uploading them at one shot. I think AWS needs to be notified about this as their guide doesn't mention any info about such errors.</p>

ContentLicense: CC BY-SA 4.0

Title: Couldn't import library into AWS Lambda

Body:
I am trying to create an AWS Lambda function in Python 3.7. But facing an error while testing my function which is -

{
  "errorMessage": "Unable to import module 'lambda_function': No module named 's3fs'",
  "errorType": "Runtime.ImportModuleError"
}

I know, by default Python environment doesn't have s3fs module imported. So I had to install the s3fs and some other packages in my local machine and zipped it. For zipping I used the following command.

Compress-Archive -Path dateutil, docutils, jmespath, s3fs, s3transfer, six.py ` -DestinationPath ..\..\..\pinpoint-importer.zip ;

(I followed the following documentation - https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-importing-data-create-python-package.html).

Then uploaded the .zip file in Lambda and cross-checked the Handler - "lambda_function.lambda_handler".

Please find the code below.

import os
import boto3
import s3fs
from botocore.exceptions import ClientError

input_archive_folder = "input_archive"
to_process_folder = "to_process"
file_row_limit = 50
file_delimiter = ','

# S3 bucket info
s3 = s3fs.S3FileSystem(anon=False)

def lambda_handler(event, context):
    print("Received event: \n" + str(event))
    for record in event['Records']:
        # Assign some variables that make it easier to work with the data in the
        # event record.
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        input_file = os.path.join(bucket,key)
        archive_path = os.path.join(bucket,input_archive_folder,os.path.basename(key))
        folder =  os.path.split(key)[0]
        s3_url = os.path.join(bucket,folder)
        output_file_template = os.path.splitext(os.path.basename(key))[0] + "__part"
        output_path = os.path.join(bucket,to_process_folder)

        # Set a variable that contains the number of files that this Lambda
        # function creates after it runs.
        num_files = file_count(s3.open(input_file, 'r'), file_delimiter, file_row_limit)

        # Split the input file into several files, each with 50 rows.
        split(s3.open(input_file, 'r'), file_delimiter, file_row_limit, output_file_template, output_path, True, num_files)

        # Send the unchanged input file to an archive folder.
        archive(input_file,archive_path)

# Determine the number of files that this Lambda function will create.
def file_count(file_handler, delimiter, row_limit):
    import csv
    reader = csv.reader(file_handler, delimiter=delimiter)
    # Figure out the number of files this function will generate.
    row_count = sum(1 for row in reader) - 1
    # If there's a remainder, always round up.
    file_count = int(row_count // row_limit) + (row_count % row_limit > 0)
    return file_count

# Split the input into several smaller files.
def split(filehandler, delimiter, row_limit, output_name_template, output_path, keep_headers, num_files):
    import csv
    reader = csv.reader(filehandler, delimiter=delimiter)

    current_piece = 1
    current_out_path = os.path.join(
         output_path,
         output_name_template + str(current_piece) + "__of" + str(num_files) + ".csv"
    )
    current_out_writer = csv.writer(s3.open(current_out_path, 'w'), delimiter=delimiter)
    current_limit = row_limit
    if keep_headers:
        headers = next(reader)
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
               output_path,
               output_name_template + str(current_piece) + "__of" + str(num_files) + ".csv"
            )
            current_out_writer = csv.writer(s3.open(current_out_path, 'w'), delimiter=delimiter)
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)

# Move the original input file into an archive folder.
def archive(input_file, archive_path):
    s3.copy_basic(input_file,archive_path)
    print("Moved " + input_file + " to " + archive_path)
    s3.rm(input_file)

I followed this documentation - https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-importing-data-lambda-function-input-split.html

A screenshot -

Please let me know if I am missing something. Thanks.


问:
How do you add Tailwind CSS into an Blazor App?
In particular, I'm using Blazor (server hosted) with ASP.NET Core Preview 8. I tried adding it using LibMan, but that seems to be more about downloading files from a CDN. I'd like to introduce Tailwind to my build process.

Is this a case where I should use something like Webpack? If so, how do I make Webpack part of my build process?

答:
I recently asked myself the same question. I decided that I didn't like a package.json or the node_modules directory in the project. For these reasons I created a NuGet package with a new build action.

With this build action you can simply give your stylesheet the build action "TailwindCSS" and during the build process the stylesheet will be converted via PostCSS.

For more details you can take a look on its GitHub repo.


问:
Cannot access Cloud Firestore with Flutter Web
I am not able to acquire data from Firebase when running on the web.

I suppose to be able to read documents data but I always fail and the data always return null.

There is no error message or any debug message...

答:
I guess now it is supported under Firebase for Web

And this is how to use it.

Check it out. Hope this helps


问:
Can I use %PUBLIC% and other "special" folders on Azure?
I need to migrate a huge application to Windows Azure. The application uses SHGetSpecialFolderLocation() and related WinAPI functions to obtain path to "special folders" like %PUBLIC% ("c:\Users\Public\" by default on Windows 2008) and later stores stuff in that folder.

Can such special folders be accessed on Windows Azure?

答: You can definitely use the API and it will work just like normal Windows.  The API is not the issue, but rather what you do with it that could be an issue.  Unless you have a startup task or some other way to persist any changes that you write to these locations, they will be lost at the next service healing.  For instance, if you asked for %SYSTEMROOT%, you would get "D:\Windows" in Windows Azure.  That is great except when you go ahead and write a file you expect to persist into this location.  The same thing goes to changes to the registry.  The only way you can depend on these changes is to do it within a Startup task or some other mechanism to make sure that even after a service healing you would be back in the same state.</p>

ContentLicense: CC BY-SA 3.0


Title: Merge the centre value and all surrounding values of an array over a specific value in another array?

Body:
This question is quite abstract to explain in a title. So my apologies for that. I'm trying to merge a Gaussian kernel over two data points in an array for a kernel density estimation.

As the point of a kernel density estimation is to also sum any overlapping kernels. To make things simple, I've distributed the values evenly so two Gaussian kernels can fit aside each other without any overlapping.

After writing this, i've come to exceed the character limit for stack overflow so I've had to trim the arrays that you see below. To see each array in the full length, please visit this URL https://js.do/code/448834

Gaussian kernel values:

const kernel = [0.0000010012331378948806, 0.0000010722046681969416, 0.000001147899227196217, 0.0000012286082418128176, 0.0000013146394976171826, 0.0000014063179475064513, 0.0000015039865533165654, 0.000001608007161276116, 0.0000017187614122055291, 0.0000018366516873606909, 0.000001962102090813225, 0.0000020955594692504055, 0.0000022374944700657156, 0.0000023884026385964733, 0.0000025488055553473936, 0.0000027192520140183837, 0.0000029003192411310286, 0.000003092614158021121, 0.000003296774685933875, 0.000003513471094924077, 0.0000037434073972252973, 0.000003987322785709955, 0.0000042459931180157695, 0.000004520232446863388, 0.000004810894597034758, 0.000005118874789422127, 0.0000054451113124928115, 0.000005790587241445476, 0.000006156332205258995, 0.000006543424201755123, 0.000006952991460711095, 0.000007386214354967505, 0.000007844327359380673, 0.00000832862105736654, 0.00000884044419467562, 0.0000093812057799243, 0.000009952377231288787, 0.000010555494568641264, 0.000011192160650276806, 0.000011864047453240681, 0.000012572898396121833, 0.00001332053070302737, 0.000014108837807296342, 0.000014939791793347624, 0.000015815445874887996, 0.000016737936907530242, 0.000017709487933690657, 0.00001873241075744663, 0.000019809108546842802]

The highest y axis value of the kernel is 0.006531646276955685:

console.log(Math.max(...kernel))
> 0.006531646276955685

Which is at the index 256:

console.log(kernel.indexOf(Math.max(...kernel)))
> 256

The total length of the kernel values is 513:

console.log(kernel.length)
> 513

Below is the dataset i'm trying to merge with the kernel array. It's an array of booleans.

const data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...]

I know it's hard to see but there are actually two 1 boolean values inside this array. The first is at index 256 and the second is at index 769. The total length of the data array is 1026. So exactly the length of two Gaussian kernels.

The goal is to merge and align the centre value and all the surrounding values of a Gaussian kernel over each 1 boolean value in the data array. So in other words, each 1 boolean value contained in the data array will be replaced with 0.006531646276955685 (the max Gaussian kernel value), and all the surrounding 0 boolean values in the data array will be replaced by the surrounding Gaussian kernel values (which are basically just the values around the centre value of 0.006531646276955685) per Gaussian kernel.

Desired output:

Before merging

console.log(data)
> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...]

After merging:

console.log(data)
> [0.0000010012331378948806, 0.0000010722046681969416, 0.000001147899227196217, 0.0000012286082418128176, 0.0000013146394976171826, 0.0000014063179475064513, 0.0000015039865533165654, 0.000001608007161276116, 0.0000017187614122055291, 0.0000018366516873606909, 0.000001962102090813225, 0.0000020955594692504055, 0.0000022374944700657156, 0.0000023884026385964733, 0.0000025488055553473936, 0.0000027192520140183837, 0.0000029003192411310286, 0.000003092614158021121, 0.000003296774685933875, 0.000003513471094924077, 0.0000037434073972252973, 0.000003987322785709955, 0.0000042459931180157695, 0.000004520232446863388, 0.000004810894597034758, 0.000005118874789422127, 0.0000054451113124928115, 0.000005790587241445476, 0.000006156332205258995, 0.000006543424201755123, 0.000006952991460711095, 0.000007386214354967505, 0.000007844327359380673, 0.00000832862105736654, 0.00000884044419467562, 0.0000093812057799243, 0.000009952377231288787, 0.000010555494568641264, 0.000011192160650276806, 0.000011864047453240681, 0.000012572898396121833, 0.00001332053070302737, 0.000014108837807296342, 0.000014939791793347624, 0.000015815445874887996, 0.000016737936907530242, 0.000017709487933690657, 0.00001873241075744663, 0.000019809108546842802, 0.000020942078460934107, 0.000022133914298650234, 0.000023387309166355133, 0.000024705058160760758, 0.000026090061063633177, 0.000027545325044505026, 0.00002907396736737866, 0.00003067921809717081, 0.00003236442280141311, 0.000034133045242481636, 0.00003598867005538605, 0.00003793500540590263, 0.00003997588562358771, 0.00004211527380395883, 0.00004435726437388044, 0.00004670608561394057, 0.000049166102131353454, 0.00005174181727667466, 0.000054437875497365937, 0.000057259064621001416, 0.00006021031806066359, 0.0000632967169348375, 0.00006652349209387734, 0.00006989602604488875, 0.0000734198547666476, 0.00007710066940595766, 0.00008094431784664176, 0.00008495680614216054, 0.00008914429980266232, 0.0000935131249270873, 0.0000980697691707815, 0.00010282088253892102, 0.00010777327799590268, 0.00011293393188073315, 0.00011830998411833384, 0.0001239087382165863, 0.0001297376610388642, 0.00013580438234174052, 0.00014211669406751854, 0.00014868254938122047, 0.000155510061441668, 0.00016260750189632018, 0.00016998329908958149, 0.00017764603597437197, 0.0001856044477168515, 0.00019386741898431967, 0.000202443980906469, 0.00021134330770035376, 0.00022057471294965238, 0.00023014764552904443, 0.0002400716851648001, 0.00025035653762298576, 0.0002610120295170303, 0.00027204810272676725, 0.00028347480842147536, 0.00029530230067987634, 0.00030754082970052636, 0.0003202007345965395, 0.00033329243576913194, 0.00034682642685504166, 0.00036081326624350226, 0.0003752635681590851, 0.0003901879933074129, 0.0004055972390814562, 0.0004215020293268802, 0.00043791310366568303, 0.0004548412063781893, 0.00047229707484430675, 0.000490291427545827, 0.0005088349516324718, 0.0005279382900553109, 0.0005476120282721495, 0.0005678666805304793, 0.0005887126757345975, 0.000610160342904543, 0.0006322198962355656, 0.0006549014197679224, 0.000678214851677903, 0.0007021699682020994, 0.0007267763672080761, 0.0007520434514257304, 0.0007779804113547997, 0.0008045962078651243, 0.0008318995545074433, 0.0008598988995536758, 0.00088860240778679, 0.0009180179420615469, 0.0009481530446585413, 0.0009790149184551221, 0.0010106104079379032, 0.0010429459800826869, 0.0010760277051287263, 0.0011098612372753278, 0.0011444517953298284, 0.001179804143337022, 0.001215922571221075, 0.0012528108754719263, 0.0012904723399090798, 0.001328909716556553, 0.0013681252066635658, 0.0014081204419063235, 0.001448896465806959, 0.0014904537154063501, 0.001532792003228134, 0.0015759104995717557, 0.0016198077151728775, 0.001664481484269838, 0.0017099289481152002, 0.0017561465389716584, 0.0018031299646317446, 0.001850874193500863, 0.00189937344028318, 0.0019486211523098193, 0.0019986099965486354, 0.0020493318473345863, 0.002100777774859358, 0.0021529380344584683, 0.002205802056733524, 0.0022593584385466716, 0.0023135949349235526, 0.0023684984519002548, 0.002424055040348798, 0.002480249890814702, 0.0025370673293990485, 0.0025944908147162216, 0.002652502935957217, 0.002711085412086988, 0.002770219092202801, 0.0028298839570789673, 0.0028900591219216502, 0.002950722840355647, 0.003011852509663206, 0.0030734246772929894, 0.0031354150486552538, 0.003197798496217239, 0.0032605490699105675, 0.0033236400088602082, 0.0033870437544422536, 0.003450731964675389, 0.0035146755299484836, 0.0035788445900842712, 0.003643208552736542, 0.003707736113115715, 0.003772395275035007, 0.003837153373266842, 0.003901977097196419, 0.003966832515756696, 0.004031685103626371, 0.004096499768669685, 0.004161240880594242, 0.004225872300800272, 0.004290357413392126, 0.0043546591573201225, 0.004418740059618208, 0.0044825622697003175, 0.004546087594675734, 0.004609277535641261, 0.004672093324905533, 0.004734495964098392, 0.004796446263115965, 0.0048579048798497474, 0.0049188323606459035, 0.0049791891814388225, 0.005038935789501051, 0.005098032645749755, 0.00515644026754812, 0.005214119271938399, 0.005271030419241745, 0.005327134656958544, 0.005382393163901616, 0.005436767394493506, 0.0054902191231579744, 0.005542710488734978, 0.005594204038847548, 0.005644662774148459, 0.005694050192374033, 0.005742330332132143, 0.005789467816351291, 0.005835427895317638, 0.005880176489227022, 0.005923680230179243...]

Here's a visual example. The "value" in the diagram just represents a 1 boolean value (the decimal was a typo). And of course in the actual array, 1 boolean values are surrounded by 0 boolean values to complete each kernel length.

UPDATE

To offer more clarity. Although overlapping is excluded from this task. The goal will be to apply this method to cases with overlapping. I don't expect to work that out here, but it's important that the goal of merging is achieved in the manner described. Or at least along those lines.

Body:
I hope this is what you searching for. I also made an visual presentation how the result looks like

const kernel = [0.0000010012331378948806, 0.0000010722046681969416, 0.000001147899227196217, 0.0000012286082418128176, 0.0000013146394976171826, 0.0000014063179475064513, 0.0000015039865533165654, 0.000001608007161276116, 0.0000017187614122055291, 0.0000018366516873606909, 0.000001962102090813225, 0.0000020955594692504055, 0.0000022374944700657156, 0.0000023884026385964733, 0.0000025488055553473936, 0.0000027192520140183837, 0.0000029003192411310286, 0.000003092614158021121, 0.000003296774685933875, 0.000003513471094924077, 0.0000037434073972252973, 0.000003987322785709955, 0.0000042459931180157695, 0.000004520232446863388, 0.000004810894597034758, 0.000005118874789422127, 0.0000054451113124928115, 0.000005790587241445476, 0.000006156332205258995, 0.000006543424201755123, 0.000006952991460711095, 0.000007386214354967505, 0.000007844327359380673, 0.00000832862105736654, 0.00000884044419467562, 0.0000093812057799243, 0.000009952377231288787, 0.000010555494568641264, 0.000011192160650276806, 0.000011864047453240681, 0.000012572898396121833, 0.00001332053070302737, 0.000014108837807296342, 0.000014939791793347624, 0.000015815445874887996, 0.000016737936907530242, 0.000017709487933690657, 0.00001873241075744663, 0.000019809108546842802]
const data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

function mergeArr(arr1, arr2){
   let arr2Copy = arr2.map(el => el);
   let max = Math.max(...arr1);
   let indexMax = arr2Copy.indexOf(1);
   let sortedKernel = arr1.sort((a,b) => a - b);
   arr2Copy[indexMax] = max;
   let indexPosition = sortedKernel.length - 1;
   for(let i = indexMax; i >= 0; i--){
      if(indexPosition == 0){
         arr2Copy[i] = sortedKernel[indexPosition];
         continue;
      }
      arr2Copy[i] = sortedKernel[indexPosition];
      indexPosition--;
   }
   let reversedKernel = sortedKernel.reverse();
   for(let i = indexMax; i < arr2Copy.length; i++){
     if(indexPosition == arr2Copy.length - 1){
        break;
     }
     arr2Copy[i] = reversedKernel[indexPosition];
     indexPosition++;

   }
   return arr2Copy;
}

let result = mergeArr(kernel, data);
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: data,
        datasets: [{
            label: 'Kernel',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: result
        }]
    },

    // Configuration options go here
    options: {}
});

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart"></canvas>


问:
Wrong number of items by the list creation
I'm creating a list of documents that consists of tuples, each tuple consists of a list of tuples and a string, so it looks like this:

```<code>[([('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'M'),
('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'F'), ...]
</code>```

I'm using nltk to generate the list:

```<code>from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), gender)
    for gender in [f[47] for f in corpus.fileids()]
    for fileid in corpus.fileids()]
</code>```

The problem is, len(corpus.fileids()) is 84 (what is correct), but len(documents) is 7056. So, somehow, I managed to square the number of documents. I'd like the list to have only 84 items.

I noticed that documents[0] and documents[84] are identical (so do documents[1] and documents[85] etc., of course). I could slice the full list of 7056 items, of course, but this does not explain anything... I'm new to Python and programming, so any help would be appreciated.

答:
If I'm reading your program correctly you are trying to store the list for every document in a tuple, together with the 'gender' of the document, which is the element at index 47 of the fileid.

The list comprehension you use to construct documents first iterates over the inner list comprehension, and then over corpus.fileids(). When a Python list comprehension iterates over two iterables it will, for every value of the first, iterate over the entire second iterable. We can see this with an example:

>>> print([(a, b) for a in [1, 2] for b in [1, 2]])
[(1, 1), (1, 2), (2, 1), (2, 2)]
```

<p>Instead, it seems in this case we can avoid the double iteration by instead  applying the <code>f[47]</code> to the fileid we draw from <code>corpus.fileids()</code>. This way every fileid will only be considered once.</p>

<pre class="lang-py prettyprint-override"><code>documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]
</code>```

The entire program thus becomes

from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]
```

Body:
I'm creating a list of documents that consists of tuples, each tuple consists of a list of tuples and a string, so it looks like this:

[([('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'M'),
('NOUN', 'ADP'), ('ADP', 'NOUN'), ('NOUN', 'PROPN'), ('PROPN', 'ADJ'), ('ADJ', 'DET')], 'F'), ...]

I'm using nltk to generate the list:

from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), gender)
    for gender in [f[47] for f in corpus.fileids()]
    for fileid in corpus.fileids()]

The problem is, len(corpus.fileids()) is 84 (what is correct), but len(documents) is 7056. So, somehow, I managed to square the number of documents. I'd like the list to have only 84 items.

I noticed that documents[0] and documents[84] are identical (so do documents[1] and documents[85] etc., of course). I could slice the full list of 7056 items, of course, but this does not explain anything... I'm new to Python and programming, so any help would be appreciated.

Body:
If I'm reading your program correctly you are trying to store the list for every document in a tuple, together with the 'gender' of the document, which is the element at index 47 of the fileid.

The list comprehension you use to construct documents first iterates over the inner list comprehension, and then over corpus.fileids(). When a Python list comprehension iterates over two iterables it will, for every value of the first, iterate over the entire second iterable. We can see this with an example:

>>> print([(a, b) for a in [1, 2] for b in [1, 2]])
[(1, 1), (1, 2), (2, 1), (2, 2)]

Instead, it seems in this case we can avoid the double iteration by instead  applying the f[47] to the fileid we draw from corpus.fileids(). This way every fileid will only be considered once.

documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]

The entire program thus becomes

from nltk.corpus import PlaintextCorpusReader
corpus = PlaintextCorpusReader('C:\CorpusData\Polit_Speeches_by_Gender_POS', '.*\.txt')
documents = [(list(ngrams(corpus.words(fileid), 2)), fileid[47]) for fileid in corpus.fileids()]


问:
Why is my service not updating on my app component?
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

```<code>import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}
</code>```

app.component.ts (I am using getUser() function in order to get the current user information)

```<code>import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}
</code>```

app.component.html (here I want to show the user information, the same code is working in every component except this)

```<code><ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>
</code>```

答:
It appears the userData variable is assigned a new value in functions loadStoredTokens() and login(). I don't see login() function called anywhere and the loadStoreTokens() function is wrongfully invoked synchronously. It handles data asynchronously, and the data flow should be asynchronous as well.

Service

export class AuthService {
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens().subscribe(
      accessToken => {
        let decoded = helper.decodeToken(accessToken);
        this.userData.next(decoded);
      },
    );
  }

  loadStoredTokens() {
    const result = new Subject<any>();
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          result.next(accessToken);
        } else {
          this.access = null;
          result.next(null);
        }
      })
    );

  return result.asObservable();
}
```

<p>Also if you're using <code>getValue()</code> function of <code>BehaviorSubject</code> there isn't any use of the multicast observable. Instead you could skip the <code>getValue()</code> in the service and subscribe to it in the component.</p>

<p>Service</p>

<pre class="lang-js prettyprint-override"><code>getUser() {
  return this.userData.asObservable();
}
</code>```

Component

ngOnInit() {
  this.auth.getUser().subscribe(
    user => { this.user = user }
  );
}
```

<p>Use safe navigation operator <code>?.</code> in the template to check if the <code>user</code> variable is defined before trying to access it's properties. Because initially the value is <code>null</code> as specified from the default value of the <code>BehaviorSubject</code>.</p>

<pre class="lang-html prettyprint-override"><code><ion-note *ngIf="user">{{ user?.email }} </ion-note>
</code>```

Or alternatively you could skip the subscription in the component controller and use async pipe in the template.

Component

ngOnInit() {
  this.user = this.auth.getUser();
}
```

<p>Template</p>

<pre class="lang-html prettyprint-override"><code><ion-note *ngIf="user">{{ (user | async)?.email }} </ion-note>
</code>```

Body:
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}

app.component.ts (I am using getUser() function in order to get the current user information)

import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}

app.component.html (here I want to show the user information, the same code is working in every component except this)

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Body:
It appears the userData variable is assigned a new value in functions loadStoredTokens() and login(). I don't see login() function called anywhere and the loadStoreTokens() function is wrongfully invoked synchronously. It handles data asynchronously, and the data flow should be asynchronous as well.

Service

export class AuthService {
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens().subscribe(
      accessToken => {
        let decoded = helper.decodeToken(accessToken);
        this.userData.next(decoded);
      },
    );
  }

  loadStoredTokens() {
    const result = new Subject<any>();
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          result.next(accessToken);
        } else {
          this.access = null;
          result.next(null);
        }
      })
    );

  return result.asObservable();
}

Also if you're using getValue() function of BehaviorSubject there isn't any use of the multicast observable. Instead you could skip the getValue() in the service and subscribe to it in the component.

Service

getUser() {
  return this.userData.asObservable();
}

Component

ngOnInit() {
  this.auth.getUser().subscribe(
    user => { this.user = user }
  );
}

Use safe navigation operator ?. in the template to check if the user variable is defined before trying to access it's properties. Because initially the value is null as specified from the default value of the BehaviorSubject.

<ion-note *ngIf="user">{{ user?.email }} </ion-note>

Or alternatively you could skip the subscription in the component controller and use async pipe in the template.

Component

ngOnInit() {
  this.user = this.auth.getUser();
}

Template

<ion-note *ngIf="user">{{ (user | async)?.email }} </ion-note>


问:
Process same file in two threads using ifstream
I have an input file in my application that contains a vast amount of information. Reading over it sequentially, and at only a single file offset at a time is not sufficient for my application's usage. Ideally, I'd like to have two threads, that have separate and distinct ifstreams reading from two unique file offsets of the same file. I can't just start one ifstream up, and then make a copy of it using its copy constructor (since its uncopyable). So, how do I handle this?

Immediately I can think of two ways,

Construct a new ifstream for the second thread, open it on the same file.

Share a single instance of an open ifstream across both threads (using for instance boost::shared_ptr<>). Seek to the appropriate file offset that current thread is currently interested in, when the thread gets a time slice.

Is one of these two methods preferred?

Is there a third (or fourth) option that I have not yet thought of?

Obviously I am ultimately limited by the hard drive having to spin back and forth, but what I am interested in taking advantage of (if possible), is some OS level disk caching at both file offsets simultaneously.

Thanks.

答:
Between the two, I would prefer the second. Having two openings of the same file might cause an inconsistent view between the files, depending on the underlying OS.

For a third option, pass a reference or raw pointer into the other thread. So long as the semantics are that one thread "owns" the istream, the raw pointer or reference are fine.

Finally note that on the vast majority of hardware, the disk is the bottleneck, not CPU, when loading large files. Using two threads will make this worse because you're turning a sequential file access into a random access. Typical hard disks can do maybe 100MB/s sequentially, but top out at 3 or 4 MB/s random access.


问:
Logging system failed to initialize using configuration from 'classpath:logger/logback-spring.xml'
I use Spring boot 2.3.0.RELEASE.

application.properties

spring.profiles.active=dev

logging.config=classpath:logger/logback-spring.xml

logging.file.dir=reception-electronic-docs
logging.file.name.var=reception-electronic-docs.log
logging.file.archive.format.name=reception-electronic-docs.%d{dd-MM-yyyy}.log
```

<p><img src="https://i.stack.imgur.com/bqSPc.png" alt="enter image description here"></p>

<p><strong>Previously this code worked</strong> (Srping boot 2.2.5.RELEASE).</p>

<p>I use multi module structure in the project. But there, the Central pom does not manage the entire project. I create microservices.</p>

<p>During start up an application encounter an error:</p>

<pre class="lang-java prettyprint-override"><code>Logging system failed to initialize using configuration from 'classpath:logger/logback-spring.xml'
java.io.FileNotFoundException: class path resource [logger/logback-spring.xml] cannot be resolved to URL because it does not exist
    at org.springframework.util.ResourceUtils.getURL(ResourceUtils.java:137)
</code>```

What are any ideas to correct this?

答:
I add an dependencies

     <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
            <version>3.1.2</version>
        </dependency>
```

But I don't understand reason.

After I removed the dependency. But my app runs without errors. I'm at a loss.

Body:
I use Spring boot 2.3.0.RELEASE.

application.properties

spring.profiles.active=dev

logging.config=classpath:logger/logback-spring.xml

logging.file.dir=reception-electronic-docs
logging.file.name.var=reception-electronic-docs.log
logging.file.archive.format.name=reception-electronic-docs.%d{dd-MM-yyyy}.log

Previously this code worked (Srping boot 2.2.5.RELEASE).

I use multi module structure in the project. But there, the Central pom does not manage the entire project. I create microservices.

During start up an application encounter an error:

Logging system failed to initialize using configuration from 'classpath:logger/logback-spring.xml'
java.io.FileNotFoundException: class path resource [logger/logback-spring.xml] cannot be resolved to URL because it does not exist
    at org.springframework.util.ResourceUtils.getURL(ResourceUtils.java:137)

What are any ideas to correct this?

Body:
I add an dependencies

     <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
            <version>3.1.2</version>
        </dependency>

But I don't understand reason.

After I removed the dependency. But my app runs without errors. I'm at a loss.


问:
Python for loop save only last value of area?
I Used blow lines of code for contour detection and its corresponding area calculation and during printing the area all values are printed but while saving only last value got saved in CSV file</p>

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd

img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)

    cv2.drawContours(img, contours, -1, (0,255,0),2)

    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    df = pd.DataFrame()
    df['Area'] = area
    df.to_csv("C:\pfm\dataframe_csv\L501.csv")
</code>```

答:
In your code, in each loop you reset the df dataframe.

Try this code:

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd

img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))

area_list = []
df = pd.DataFrame()

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)

    cv2.drawContours(img, contours, -1, (0,255,0),2)

    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    area_list.append(area)

df['Area'] = area_list
df.to_csv("C:\pfm\dataframe_csv\L501.csv")
</code>```

Instead of append the area to the df dataframe in each loop, I append it in a list area_list. Note that I create this empty list before the for loop, to initialize it, as well as the df dataframe. When all loops are concluded, I create the 'Area' column of the dataframe by saving in it the list previously generated. In this way the df is not empty and the code is more efficient.

Body:
I Used blow lines of code for contour detection and its corresponding area calculation and during printing the area all values are printed but while saving only last value got saved in CSV file

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd

img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)

    cv2.drawContours(img, contours, -1, (0,255,0),2)

    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    df = pd.DataFrame()
    df['Area'] = area
    df.to_csv("C:\pfm\dataframe_csv\L501.csv")

Body:
In your code, in each loop you reset the df dataframe.

Try this code:

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
import pandas as pd

img = cv2.imread('C:\pfm\segmented/L501.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

from scipy import ndimage as nd
gaussian_img = nd.gaussian_filter(image, sigma=3)

ret, thresh = cv2.threshold(gaussian_img, 127,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#print ('No of shapes:', format(len(contours)))

area_list = []
df = pd.DataFrame()

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)

    cv2.drawContours(img, contours, -1, (0,255,0),2)

    plt.imshow(img)
    plt.imsave("C:\pfm\dataframe_csv\L501.jpg", img)

    area = cv2.contourArea(cnt)

    print(area)

    area_list.append(area)

df['Area'] = area_list
df.to_csv("C:\pfm\dataframe_csv\L501.csv")

Instead of append the area to the df dataframe in each loop, I append it in a list area_list. Note that I create this empty list before the for loop, to initialize it, as well as the df dataframe. When all loops are concluded, I create the 'Area' column of the dataframe by saving in it the list previously generated. In this way the df is not empty and the code is more efficient.


问:
Flutter Title center-allignment
I made a custom app bar with the Container, but i need the title to be placed in the center of the row and the back button to be placed on the edge of left side.
I did try it out by adding the spacer, mainaxisallignment everything but it is not properly getting placed as required. So is there any approach i could make use of? Thanks in advance.</p>

```<code>Widget header() {
    return new Container(
      height: 140,
      decoration: BoxDecoration(
          color: Color(0xFFAFDCEC),
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(20),
              bottomRight: Radius.circular(20))),
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 60,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(icon: Icon(Icons.arrow_back_ios, color: Colors.white,),),
              Text(
                'To-Do List',
                style: TextStyle(color: Colors.white, fontSize: 25),
              )
            ],
          )
        ],
      ),
    );
  }
</code>```

答:
Row(
    // mainAxisAlignment: MainAxisAlignment.spaceAround,

    children: <Widget>[

      SizedBox(width:10), //if you want to have some space (like 10px) from left edge for back button use this or wrapping IconButton with Padding with only left prameter

      IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
          onPressed: () {}),

      Expanded(
        child: Center(
          child: Text(
            'To-Do List',
            style: TextStyle(color: Colors.white, fontSize: 25),
          ),
        ),
      ),

    ],
)
```

Title: Flutter Title center-allignment

Body:
I made a custom app bar with the Container, but i need the title to be placed in the center of the row and the back button to be placed on the edge of left side.
I did try it out by adding the spacer, mainaxisallignment everything but it is not properly getting placed as required. So is there any approach i could make use of? Thanks in advance.

Widget header() {
    return new Container(
      height: 140,
      decoration: BoxDecoration(
          color: Color(0xFFAFDCEC),
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(20),
              bottomRight: Radius.circular(20))),
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 60,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(icon: Icon(Icons.arrow_back_ios, color: Colors.white,),),
              Text(
                'To-Do List',
                style: TextStyle(color: Colors.white, fontSize: 25),
              )
            ],
          )
        ],
      ),
    );
  }


问:
Android - Dynamically Add Views into View
I have a layout for a view -

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>
</code>```

What I want to do, is in my main activity with a layout like this

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>
</code>```

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

答:
Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

```<code>LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
</code>```

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

Body:
I have a layout for a view -

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>

What I want to do, is in my main activity with a layout like this

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

Body:
Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.


问:
Why the small number string is greater than big number string
When the smaller number string when compared with the larger number string - the result is true.

How is it possible?

document.write(`Why the result of '2'>'10' is ${'2'>'10'}`)```

Any expert here?

答:
You're comparing strings, so a lexical comparison is performed instead of a numerical comparison.

Lexically, 2 comes after 1.

Body:
When the smaller number string when compared with the larger number string - the result is true.

How is it possible?

document.write(`Why the result of '2'>'10' is ${'2'>'10'}`)

Any expert here?


问:
Rancher - How to expose my services publicly?
I have a running Rancher setup as the following:

Host machine (running rancher/rancher container) on a public IP;

Nodes in an exclusive network (10.1.1.0/24) not accessible from the Internet.

My goal is to serve a web application using the Rancher Load Balancing or whatever similar stuff.
For that, I've perfomed the following steps:

Deploy workload using the "rancher/hello-world" image on 3 pods mapping port 80/tcp as a NodePort (listening port is random) named "web-app";

Add Ingress named "hello" in same namespace selecting "Automatically generate a .xip.io hostname" and adding route "/" to the "web-app" on port 80.

This works on the local network, since I get an address like http://hello.gabriel-milan.10.1.1.14.xip.io/ that would resolve to 10.1.1.14, which is local.

I wanted to expose this service for one of my public IPs. How can I do that?

答:
You have to create a svc with type:LoadBalancer. It will give a public IP for your deployment. kubectl create service loadbalancer <deployment-name> --tcp=80:8000

once you create svc, you have to create ingress and pass above created svc in ingress. You have to define host: as a url of the domain and path where you want to map it.

Point the LB's IP in DNS provider.


问:
How to make rounded border for dropdownbutton in flutter?
How to Add Rounded Rectangle Border?
Below Code didn't result in any border on screen.   </p>

```<code>Container(margin: EdgeInsets.only(top: 10.0, right: 10.0, left: 10.0),
 width: double.infinity,
 // decoration: ShapeDecoration(
 //  shape: RoundedRectangleBorder(
 //   borderRadius:BorderRadius.all(Radius.circular(5.0)),
 //                             ),

 child: DropdownButtonHideUnderline(
  child: Container(
   margin: EdgeInsets.only(
    left: 10.0, right: 10.0),
     child: new DropdownButton<UserTest>(...),
                           ),
                          ),
                   ),
</code>```

答:
With the form field variant, you can use the OutlineInputBorder InputBorder, used normally for input text fields:

DropdownButtonFormField(
  ...
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
  ),
),
```
<p>The way the form field does this can be replicated and used with the regular <code>DropdownButton</code>:</p>
<pre class="lang-dart prettyprint-override"><code>InputDecorator(
  decoration: const InputDecoration(border: OutlineInputBorder()),
  child: DropdownButtonHideUnderline(
    child: DropdownButton(
      ...
    ),
  ),
),
</code>```

Body:
How to Add Rounded Rectangle Border?
Below Code didn't result in any border on screen.

Container(margin: EdgeInsets.only(top: 10.0, right: 10.0, left: 10.0),
 width: double.infinity,
 // decoration: ShapeDecoration(
 //  shape: RoundedRectangleBorder(
 //   borderRadius:BorderRadius.all(Radius.circular(5.0)),
 //                             ),

 child: DropdownButtonHideUnderline(
  child: Container(
   margin: EdgeInsets.only(
    left: 10.0, right: 10.0),
     child: new DropdownButton<UserTest>(...),
                           ),
                          ),
                   ),

Body:
With the form field variant, you can use the OutlineInputBorder InputBorder, used normally for input text fields:

DropdownButtonFormField(
  ...
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
  ),
),

The way the form field does this can be replicated and used with the regular DropdownButton:

InputDecorator(
  decoration: const InputDecoration(border: OutlineInputBorder()),
  child: DropdownButtonHideUnderline(
    child: DropdownButton(
      ...
    ),
  ),
),


问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

答:
You could use list comprehension:</p>

```<code>a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

result = [ (second - a[i+1][1], third - a[i+1][2] )   for i, (first, second, third) in enumerate(a[:-1]) ]
print(result)
</code>```

Body:
You could use list comprehension:

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

result = [ (second - a[i+1][1], third - a[i+1][2] )   for i, (first, second, third) in enumerate(a[:-1]) ]
print(result)


问:
in Qbasic, How can I make my centimeter number display to one decimal place. 73.53 instead of 73.53315
```<code>CLS
REM Declare Varibles
DIM MILES, YARDS, FEET, INCHES AS DOUBLE
DIM KM, METER, TINCH AS DOUBLE
DIM CM, TMETER AS DOUBLE
REM INPUT THE DATA
INPUT "ENTER THE DISTANCE IN MILES", MILES
INPUT "ENTER THE DISTANCE IN YARDS", YARDS
INPUT "ENTER THE DISTANCE IN FEET", FEET
INPUT "ENTER THE DISTANCE IN INCHES", INCHES
REM CONVERT INTO TOTAL INCHES
TINCH = 63360 * MILES + 36 * YARDS + 12 * FEET + INCHES
REM CONVERT INTO TOTAL METER
TMETER = TINCH / 39.37
REM CONVERT TO KILOMETER
KM = INT(TMETER / 1000)
REM CONVERT TO METER
METER = INT(TMETER - KM * 1000)
REM CONVERT TO CENTIMETER
CM = (TMETER - (KM * 1000) - METER) * 100
REM PRINT DETAILS
PRINT "KILOMETER", KM
PRINT "METER", METER
PRINT "CENTIMETER", CM;
</code>```

答:
If I remember correctly, you can use the PRINT USING statement.

```<code>cm_number = 73.53315
PRINT USING "##.##"; cm_number
OUTPUT: 73.53
</code>```

"#" - represent digits,
"." - represents the decimal point position

Click here for a more detailed explanation.

Body:
If I remember correctly, you can use the PRINT USING statement.

cm_number = 73.53315
PRINT USING "##.##"; cm_number
OUTPUT: 73.53

"#" - represent digits,
"." - represents the decimal point position

Click here for a more detailed explanation.


问:
Can't use Jupyter Notebook: jsonschema apparently missing
When using an Anaconda environment, I can't start Jupyter to work in a notebook.  I can do so without the environment, but I need to be able to use the environment.  Here's what I do and the errors I get:

```<code>ben@ben-K60IJ:~/surveillance_sound_classifier/surveillance_sound_classifier$ source activate EECS352
discarding /home/ben/anaconda/bin from PATH
prepending /home/ben/anaconda/envs/EECS352/bin to PATH
(EECS352)ben@ben-K60IJ:~/surveillance_sound_classifier/surveillance_sound_classifier$ jupyter notebook
Traceback (most recent call last):
  File "/home/ben/anaconda/envs/EECS352/bin/jupyter-notebook", line 4, in <module>
import notebook.notebookapp
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/notebook/notebookapp.py", line 61, in <module>
from .services.contents.manager import ContentsManager
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/notebook/services/contents/manager.py", line 16, in <module>
from nbformat import sign, validate, ValidationError
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/nbformat/__init__.py", line 33, in <module>
from .validator import validate, ValidationError
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/nbformat/validator.py", line 21, in <module>
raise ImportError(str(e) + verbose_msg)
ImportError: No module named functools32

Jupyter notebook format depends on the jsonschema package:

    https://pypi.python.org/pypi/jsonschema

Please install it first.
</code>```

Yes, I've done pip install jsonschema and conda install jsonschema AND pip install functools32 and conda install functools32 from within the EECS352 environment to no avail; I arrive at an almost identical error, except this time, functools32 is replaced with _version.

I've reinstalled Anaconda, updated all its packages, created a new environment in the same way I created this one, and still I get this error. I'm using Ubuntu 15.10 32-bit.  I used to be able to use this environment with no problems until roughly a week ago.

If this is a duplicate, please point me to the original; however, I haven't yet found anything that seems really relevant.  The only thing that might be relevant is that this error did pop up after I modified some .conf file because I was having issues updating my computer's software using sudo apt-get upgrade.  I don't recall what I had done and to which file, but if it's likely the source of this issue, I can spend some time trying to track it down.  Please let me know if I should spend my time to do this, and I will.

答:
i also got the same error and none of the above mentioned procedures worked for me so i've checked the documentation of anaconda and found something useful

conda install -c conda-forge/label/cf201901 jsonschema

conda install jupyter

jupyter notebook

this worked for me,thanks to anaconda documentation

Body:
When using an Anaconda environment, I can't start Jupyter to work in a notebook.  I can do so without the environment, but I need to be able to use the environment.  Here's what I do and the errors I get:

ben@ben-K60IJ:~/surveillance_sound_classifier/surveillance_sound_classifier$ source activate EECS352
discarding /home/ben/anaconda/bin from PATH
prepending /home/ben/anaconda/envs/EECS352/bin to PATH
(EECS352)ben@ben-K60IJ:~/surveillance_sound_classifier/surveillance_sound_classifier$ jupyter notebook
Traceback (most recent call last):
  File "/home/ben/anaconda/envs/EECS352/bin/jupyter-notebook", line 4, in <module>
import notebook.notebookapp
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/notebook/notebookapp.py", line 61, in <module>
from .services.contents.manager import ContentsManager
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/notebook/services/contents/manager.py", line 16, in <module>
from nbformat import sign, validate, ValidationError
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/nbformat/__init__.py", line 33, in <module>
from .validator import validate, ValidationError
  File "/home/ben/anaconda/envs/EECS352/lib/python2.7/site-packages/nbformat/validator.py", line 21, in <module>
raise ImportError(str(e) + verbose_msg)
ImportError: No module named functools32

Jupyter notebook format depends on the jsonschema package:

    https://pypi.python.org/pypi/jsonschema

Please install it first.

Yes, I've done pip install jsonschema and conda install jsonschema AND pip install functools32 and conda install functools32 from within the EECS352 environment to no avail; I arrive at an almost identical error, except this time, functools32 is replaced with _version.

I've reinstalled Anaconda, updated all its packages, created a new environment in the same way I created this one, and still I get this error. I'm using Ubuntu 15.10 32-bit.  I used to be able to use this environment with no problems until roughly a week ago.

If this is a duplicate, please point me to the original; however, I haven't yet found anything that seems really relevant.  The only thing that might be relevant is that this error did pop up after I modified some .conf file because I was having issues updating my computer's software using sudo apt-get upgrade.  I don't recall what I had done and to which file, but if it's likely the source of this issue, I can spend some time trying to track it down.  Please let me know if I should spend my time to do this, and I will.


问:
PickerView Remove Placeholder label swift
Is there any way to remove Select string from top of the UIPickerView screen shot given below:

Code:

```<code>var pickerVWUserList = UIPickerView()

    //MARK:- Setup Picker View For TextField
func setupForPickerViewForTxtFld() {
    pickerVWUserList.delegate = self
    pickerVWUserList.dataSource = self
    txtfldAllGroup.inputView = pickerVWUserList
}

//MARK:- Extension for picker View
extension VC:UIPickerViewDataSource,UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return listOfAllTypesGroups.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return listOfAllTypesGroups[row].groupName
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    slctedGroupId = listOfAllTypesGroups[row].groupId
}
</code>```

Thank you

答:
Try this code in AppDelegate didFinishLaunchingWithOptions</p>

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

     IQKeyboardManager.shared.enable = true
     IQKeyboardManager.shared.shouldShowToolbarPlaceholder = false

     return true
 }
</code>```

Body:
Is there any way to remove Select string from top of the UIPickerView screen shot given below:

Code:

var pickerVWUserList = UIPickerView()

    //MARK:- Setup Picker View For TextField
func setupForPickerViewForTxtFld() {
    pickerVWUserList.delegate = self
    pickerVWUserList.dataSource = self
    txtfldAllGroup.inputView = pickerVWUserList
}

//MARK:- Extension for picker View
extension VC:UIPickerViewDataSource,UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return listOfAllTypesGroups.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return listOfAllTypesGroups[row].groupName
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    slctedGroupId = listOfAllTypesGroups[row].groupId
}

Thank you

Body:
Try this code in AppDelegate didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

     IQKeyboardManager.shared.enable = true
     IQKeyboardManager.shared.shouldShowToolbarPlaceholder = false

     return true
 }


问:
grails acegi security constraints bypassed on forward
After googeling i found references that states that acegi security constraints isn't uphold upon forward.

I tested it in my application, and i can confirm that i suffer from this issue.

Does anyone know if the same issue is found in the recommended spring security plugin? If not, then it seems like it's time for me to start upgrading from acegi.

答:
Spring Security is implemented using Servlet filters, so doing a server-side forward won't be checked since no filters are involved. A redirect would work (although it might not be appropriate for this use case) since it will result in a new request.

Although this works the same in both the Acegi and Spring Security Core plugins (both wrap Spring Security) you should still upgrade - no more work is being done for the old plugin and the new one is actively maintained.