问:
Why Flask Application not running 2nd time?
I created a Flask application of object detection on video. In this application, I take video input from a user. This video is processed by our application, shows detection on screen and download the video after completion of the process. But when I pass the same video or another video on the same application with the same session it doesn't work. It doesn't show me any error. Here I attached the sample code of my project.

How can I pass another video after completing the process for the first video in this application?

```<code>from flask import Flask, render_template, request,  flash, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from PIL import Image
from os import listdir
import numpy as np
import pandas as pd
import cv2
import os
import matplotlib.pyplot as plt
import re
from pathlib import Path
app = Flask(__name__)
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
ALLOWED_EXTENSIONS = {'mp4'}
app.secret_key = 'random string'
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def my_func(filename):
    name = filename.split('/')[-1].split(".")[0]
    cap= cv2.VideoCapture(filename)
    i=0
    images = []
    while(cap.isOpened()):
        ret, frame = cap.read()
        if not ret: break
        font = cv2.FONT_HERSHEY_SIMPLEX
        org = (5,20)
        fontScale = 0.5
        color = (0, 0, 255)
        fontstroke = 2
        image1 = cv2.putText(frame, 'Done', org, font, fontScale, color, fontstroke)
        images.append(image1)
        i+=1
    height, width, channels = images[0].shape
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('downloads/' + name + '.mp4', fourcc, 20, (width, height))
    for pic in images:
        out.write(pic)
        cv2.imshow('video',pic)
        if (cv2.waitKey(150) & 0xFF) == ord('q'): # Hit `q` to exit
            break
    out.release()
    cv2.destroyAllWindows()
@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
           print('No file attached in request')
           return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            print('No file selected')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            my_func(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return render_template('index.html')
@app.route('/downloaded/<filename>', methods=['POST', 'GET'])
def uploaded_file(filename):
    return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename, as_attachment=True)
if __name__ == '__main__':
    app.run(debug = True)
</code>```

Here I mention the code of index.html file.

```<code><!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Model</title>
    </head>
    <body>
    <div align="center">
        <h1>Recognition</h1>
        <h2>Upload Video</h2>
        <form method="post" enctype=multipart/form-data>
            <p><input type=file name=file value="REFRESH">
                <input type=submit value=Upload></p>

        </form>
    </div>
    </body>
    </html>
</code>```

答:
Two possibilities:

Upload more than one file at a time

Redirect the user to the upload form after the first upload has been finished

You won't be able to handle a second file without any request trigger.

Regards, Thomas

Body:
I created a Flask application of object detection on video. In this application, I take video input from a user. This video is processed by our application, shows detection on screen and download the video after completion of the process. But when I pass the same video or another video on the same application with the same session it doesn't work. It doesn't show me any error. Here I attached the sample code of my project.

How can I pass another video after completing the process for the first video in this application?

from flask import Flask, render_template, request,  flash, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from PIL import Image
from os import listdir
import numpy as np
import pandas as pd
import cv2
import os
import matplotlib.pyplot as plt
import re
from pathlib import Path
app = Flask(__name__)
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
ALLOWED_EXTENSIONS = {'mp4'}
app.secret_key = 'random string'
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def my_func(filename):
    name = filename.split('/')[-1].split(".")[0]
    cap= cv2.VideoCapture(filename)
    i=0
    images = []
    while(cap.isOpened()):
        ret, frame = cap.read()
        if not ret: break
        font = cv2.FONT_HERSHEY_SIMPLEX
        org = (5,20)
        fontScale = 0.5
        color = (0, 0, 255)
        fontstroke = 2
        image1 = cv2.putText(frame, 'Done', org, font, fontScale, color, fontstroke)
        images.append(image1)
        i+=1
    height, width, channels = images[0].shape
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('downloads/' + name + '.mp4', fourcc, 20, (width, height))
    for pic in images:
        out.write(pic)
        cv2.imshow('video',pic)
        if (cv2.waitKey(150) & 0xFF) == ord('q'): # Hit `q` to exit
            break
    out.release()
    cv2.destroyAllWindows()
@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
           print('No file attached in request')
           return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            print('No file selected')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            my_func(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return render_template('index.html')
@app.route('/downloaded/<filename>', methods=['POST', 'GET'])
def uploaded_file(filename):
    return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename, as_attachment=True)
if __name__ == '__main__':
    app.run(debug = True)

Here I mention the code of index.html file.

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Model</title>

Recognition

Upload Video

        <form method="post" enctype=multipart/form-data>

<input type=file name=file value="REFRESH">
                <input type=submit value=Upload>

        </form>


来源: stackexchange

问:
Angular form control changing validation status without corresponding value change?
I have a mystery I am trying unravel with the following reactive form I am creating with the FormBuilder.

```<code>    this.form = this.fb.group({
      startDate: [this.startDate],
      startTime: [this.startTime],
      endDate: [this.endDate],
      endTime: [this.endTime]
    }, {validators: [this.validateDateRange()]});
</code>```

In my attempts to debug, after form creation, I add several key Observers as follows:

```<code>public ngAfterViewInit() {
    this.form.get('startDate').valueChanges
      .pipe(
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((val) => {
          console.log(`startDate new value ${val}`);
          this.startDate = val;
          this.combineDateAndTime(true);
        },
        (err) => {
          console.log(`startDate error! ${JSON.stringify(err)}`);
        },
        () => {
          console.log(`startDate completed!`);
        });

    this.form.get('startDate').statusChanges
      .pipe(
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((val) => {
         console.log(`startDate is now ${val} [${JSON.stringify(this.form.get('startDate').errors)}] startDate: ${this.form.get('startDate').value}`);
      });

  this.form.statusChanges
    .pipe(
      distinctUntilChanged(),
      takeUntil(this.destroy$)
    )
    .subscribe((val) => {
      console.log(`form is now ${val} [${JSON.stringify(this.form.get('startDate').errors)}]`);
    });
}
</code>```

Also, my cross field validator function looks like this:

```<code>  private validateDateRange(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
      const now = moment().add(1, 'second');  // slight wiggle room for now based operations
      const startDate = this.startDate;
      const endDate = this.endDate;
      let errors;
      if (!startDate && !endDate) {
        errors = this.setFormControlError(group, 'startDate', 'required');
        errors = this.setFormControlError(group, 'startTime', 'required');
        errors = this.setFormControlError(group, 'endDate', 'required');
        errors = this.setFormControlError(group, 'endTime', 'required');
        return errors;
      }

      if (startDate && startDate.valueOf() > now.valueOf()) {
        errors = this.setFormControlError(group, 'startDate', 'maxDate');
        errors = this.setFormControlError(group, 'startTime', 'maxDate');
      } else if (!startDate && this.startTime) {
        errors = this.setFormControlError(group, 'startDate', 'required');
      } else {
        this.clearFormControlErrors(group, 'startDate', ['required', 'maxDate']);
        this.clearFormControlErrors(group, 'startTime', ['required', 'maxDate']);
      }
      if (endDate && endDate.valueOf() > now.valueOf()) {
        errors = this.setFormControlError(group, 'endDate', 'maxDate');
        errors = this.setFormControlError(group, 'endTime', 'maxDate');
      } else if (!endDate && this.endTime) {
        errors = this.setFormControlError(group, 'endDate', 'required');
      } else {
        this.clearFormControlErrors(group, 'endDate', ['required', 'maxDate']);
        this.clearFormControlErrors(group, 'endTime', ['required', 'maxDate']);
      }

      if (startDate && endDate) {
        if (startDate >= endDate) {
          errors = this.setFormControlError(group, 'startDate', 'maxDate');
          errors = this.setFormControlError(group, 'startTime', 'maxDate');
          errors = this.setFormControlError(group, 'endDate', 'maxDate');
          errors = this.setFormControlError(group, 'endTime', 'maxDate');
        }
      }
      return errors;
    };
  }

  private setFormControlError(group: FormGroup, controlName: string, errorType: string): ValidationErrors {
    const errors = group.controls[controlName].errors || {};
    errors[errorType] = true;
    group.controls[controlName].setErrors(errors);
    group.controls[controlName].markAsTouched();
    this.changeDetectorRef.markForCheck();
    return isEmpty(errors) ? undefined : errors;
  }

  private clearFormControlErrors(group: FormGroup, controlName: string, errorTypes: string[]): void {
    if (group.controls[controlName].errors) {
      const errors = group.controls[controlName].errors;
      for (const error of errorTypes) {
        delete errors[error];
      }
      group.controls[controlName].setErrors(isEmpty(errors) ? undefined : errors);
      this.changeDetectorRef.markForCheck();
    }
  }
</code>```

With the above, I am expecting to, for example, have the startDate control be invalid after choosing a date that is beyond the endDate.  Further, I expect the control to be in INVALID status, to be marked as touched and to have a relevant 'maxDate' error set in it's associated errors.

However, this is not what I am seeing.  Surprisingly, my debugging efforts are yielding the following mystery that I am endeavoring to understand fully.  Upon choosing a startDate beyond endDate as described above, I observe the following sequence in my debugging efforts:
1) this.form.get('startDate').valueChanges observer is invoked with the new value as expected
2) this.form.get('startDate').statusChanges observer reflects the following as expected
    startDate is now PENDING [null] startDate: 1582907100000
3) the cross field validation function invokes and sets the expected error on the startDate control
4) this.form.get('startDate').statusChanges observer fires again and reports
    startDate is now INVALID [{"maxDate":true}] startDate: 1582907100000
5) this.form.statusChanges observer fires and reports
    form is now INVALID [{"maxDate":true}]

All of the above appears to be as expected.  However, I then also see the following immediately thereafter which I cannot explain:
6) this.form.get('startDate').statusChanges fires again and reflects
    startDate is now VALID [null] startDate: 1582907100000

Please note that there are no this.form.get('startDate').valueChanges observer changes noted between 5) and 6) nor are there any other programmatic changes to the control.

What am I missing?  How can the control, which was correctly tagged as INVALID miraculously become VALID without any intervening value changes (nor any invocations to things such as
group.controls[controlName].setErrors, clearFormControlErrors(...), reset, etc. that could plausibly be expected to reset that status to VALID?

Thank you in advance for your assistance!

答:
Just wanted to report back that, as expected, this mystery can be traced back to other extraneous elements and incorrect assumptions.

Indeed the value of the form controls are not being changed.  However, other elements on the page triggered the changeDetector.  Triggering this caused the validators, including the formgroup validator to rerun.  Upon a subsequent rerun of the validator, the error messages are no longer applied to the individual controls (as they were in the first run) and only remain at the form/group level.  This gave the false appearance (due to *ngIf on display of error messages that only expected the error on the control itself - not accounting for the form/group level as well) that the value had changed resulting in the validation status change.

Mystery resolved.

ContentLicense: CC BY-SA 4.0

Body:
I have a mystery I am trying unravel with the following reactive form I am creating with the FormBuilder.

    this.form = this.fb.group({
      startDate: [this.startDate],
      startTime: [this.startTime],
      endDate: [this.endDate],
      endTime: [this.endTime]
    }, {validators: [this.validateDateRange()]});

In my attempts to debug, after form creation, I add several key Observers as follows:

public ngAfterViewInit() {
    this.form.get('startDate').valueChanges
      .pipe(
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((val) => {
          console.log(`startDate new value ${val}`);
          this.startDate = val;
          this.combineDateAndTime(true);
        },
        (err) => {
          console.log(`startDate error! ${JSON.stringify(err)}`);
        },
        () => {
          console.log(`startDate completed!`);
        });

    this.form.get('startDate').statusChanges
      .pipe(
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((val) => {
         console.log(`startDate is now ${val} [${JSON.stringify(this.form.get('startDate').errors)}] startDate: ${this.form.get('startDate').value}`);
      });

  this.form.statusChanges
    .pipe(
      distinctUntilChanged(),
      takeUntil(this.destroy$)
    )
    .subscribe((val) => {
      console.log(`form is now ${val} [${JSON.stringify(this.form.get('startDate').errors)}]`);
    });
}

Also, my cross field validator function looks like this:

  private validateDateRange(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
      const now = moment().add(1, 'second');  // slight wiggle room for now based operations
      const startDate = this.startDate;
      const endDate = this.endDate;
      let errors;
      if (!startDate && !endDate) {
        errors = this.setFormControlError(group, 'startDate', 'required');
        errors = this.setFormControlError(group, 'startTime', 'required');
        errors = this.setFormControlError(group, 'endDate', 'required');
        errors = this.setFormControlError(group, 'endTime', 'required');
        return errors;
      }

      if (startDate && startDate.valueOf() > now.valueOf()) {
        errors = this.setFormControlError(group, 'startDate', 'maxDate');
        errors = this.setFormControlError(group, 'startTime', 'maxDate');
      } else if (!startDate && this.startTime) {
        errors = this.setFormControlError(group, 'startDate', 'required');
      } else {
        this.clearFormControlErrors(group, 'startDate', ['required', 'maxDate']);
        this.clearFormControlErrors(group, 'startTime', ['required', 'maxDate']);
      }
      if (endDate && endDate.valueOf() > now.valueOf()) {
        errors = this.setFormControlError(group, 'endDate', 'maxDate');
        errors = this.setFormControlError(group, 'endTime', 'maxDate');
      } else if (!endDate && this.endTime) {
        errors = this.setFormControlError(group, 'endDate', 'required');
      } else {
        this.clearFormControlErrors(group, 'endDate', ['required', 'maxDate']);
        this.clearFormControlErrors(group, 'endTime', ['required', 'maxDate']);
      }

      if (startDate && endDate) {
        if (startDate >= endDate) {
          errors = this.setFormControlError(group, 'startDate', 'maxDate');
          errors = this.setFormControlError(group, 'startTime', 'maxDate');
          errors = this.setFormControlError(group, 'endDate', 'maxDate');
          errors = this.setFormControlError(group, 'endTime', 'maxDate');
        }
      }
      return errors;
    };
  }

  private setFormControlError(group: FormGroup, controlName: string, errorType: string): ValidationErrors {
    const errors = group.controls[controlName].errors || {};
    errors[errorType] = true;
    group.controls[controlName].setErrors(errors);
    group.controls[controlName].markAsTouched();
    this.changeDetectorRef.markForCheck();
    return isEmpty(errors) ? undefined : errors;
  }

  private clearFormControlErrors(group: FormGroup, controlName: string, errorTypes: string[]): void {
    if (group.controls[controlName].errors) {
      const errors = group.controls[controlName].errors;
      for (const error of errorTypes) {
        delete errors[error];
      }
      group.controls[controlName].setErrors(isEmpty(errors) ? undefined : errors);
      this.changeDetectorRef.markForCheck();
    }
  }

With the above, I am expecting to, for example, have the startDate control be invalid after choosing a date that is beyond the endDate.  Further, I expect the control to be in INVALID status, to be marked as touched and to have a relevant 'maxDate' error set in it's associated errors.

However, this is not what I am seeing.  Surprisingly, my debugging efforts are yielding the following mystery that I am endeavoring to understand fully.  Upon choosing a startDate beyond endDate as described above, I observe the following sequence in my debugging efforts:
1) this.form.get('startDate').valueChanges observer is invoked with the new value as expected
2) this.form.get('startDate').statusChanges observer reflects the following as expected
    startDate is now PENDING [null] startDate: 1582907100000
3) the cross field validation function invokes and sets the expected error on the startDate control
4) this.form.get('startDate').statusChanges observer fires again and reports
    startDate is now INVALID [{"maxDate":true}] startDate: 1582907100000
5) this.form.statusChanges observer fires and reports
    form is now INVALID [{"maxDate":true}]

All of the above appears to be as expected.  However, I then also see the following immediately thereafter which I cannot explain:
6) this.form.get('startDate').statusChanges fires again and reflects
    startDate is now VALID [null] startDate: 1582907100000

Please note that there are no this.form.get('startDate').valueChanges observer changes noted between 5) and 6) nor are there any other programmatic changes to the control.

What am I missing?  How can the control, which was correctly tagged as INVALID miraculously become VALID without any intervening value changes (nor any invocations to things such as
group.controls[controlName].setErrors, clearFormControlErrors(...), reset, etc. that could plausibly be expected to reset that status to VALID?

Thank you in advance for your assistance!


问:
How can I implement a class template function with a std::enable_if metafunction?
I have used the std::enable_if metafunction in my class template to specify that it is only allowed to generate classes for variables that have GameCard as a base class. This works fine on its own when I implement the functions inline. However, if I want to implement the template functions outside the header body I run into the issue that I can't figure out how to correctly specify the function that I want to implement.

Cut down example code:

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

struct GameCard {};

template<class T, class = std::enable_if_t<std::is_base_of<GameCard, T>::value>>
struct CardStack {
  std::vector<T> cards;
  bool Test();
};
</code>```

My IDE generates this as the function specification:

```<code>template<class T, class>
bool CardStack<T, <unnamed>>::Test() {
  return false;
}
</code>```

This is obviously wrong since I'm getting compiler errors. But I don't have a clue on how to do it right. Do any of you know how to do this right?

答:
Out of class definition should be:

```<code>template<class T, class Enabler>
bool CardStack<T, Enabler>::Test() {
  return false;
}
</code>```

But currently, you class might be hijacked:

Whereas CardStack<int> or CardStack<int, void> won't compile thanks to SFINAE,

CardStack<int, char> would be "valid" (risk to not compile because of hard error produced by int in CardStack implementation).

static_assert seems enough in your case:

```<code>template<class T>
struct CardStack {
  static_assert(std::is_base_of<GameCard, T>::value);

  std::vector<T> cards;
  bool Test();
};
</code>```

With simpler out of class definition:

```<code>template<class T>
bool CardStack<T>::Test() {
  return false;
}
</code>```

Body:
I have used the std::enable_if metafunction in my class template to specify that it is only allowed to generate classes for variables that have GameCard as a base class. This works fine on its own when I implement the functions inline. However, if I want to implement the template functions outside the header body I run into the issue that I can't figure out how to correctly specify the function that I want to implement.

Cut down example code:

#include <string>
#include <memory>
#include <vector>

struct GameCard {};

template<class T, class = std::enable_if_t<std::is_base_of<GameCard, T>::value>>
struct CardStack {
  std::vector<T> cards;
  bool Test();
};

My IDE generates this as the function specification:

template<class T, class>
bool CardStack<T, <unnamed>>::Test() {
  return false;
}

This is obviously wrong since I'm getting compiler errors. But I don't have a clue on how to do it right. Do any of you know how to do this right?

Body:
Out of class definition should be:

template<class T, class Enabler>
bool CardStack<T, Enabler>::Test() {
  return false;
}

But currently, you class might be hijacked:

Whereas CardStack<int> or CardStack<int, void> won't compile thanks to SFINAE,

CardStack<int, char> would be "valid" (risk to not compile because of hard error produced by int in CardStack implementation).

static_assert seems enough in your case:

template<class T>
struct CardStack {
  static_assert(std::is_base_of<GameCard, T>::value);

  std::vector<T> cards;
  bool Test();
};

With simpler out of class definition:

template<class T>
bool CardStack<T>::Test() {
  return false;
}


问:
Merge dataframes based on columns and rbind matches
I have two dataframes as:

df <- data.frame(x=c("a","c"), y=c("111","222"))

df1 <- data.frame(x=c("a","b","b","c"), y=c("111","222","111","222"),z=c('xxx','yyy','ddd','ttt'))
```

<p>I want to merge these two dataframes based on column x, in such a way that the matched rows from df1 should be added as rows to df and now as columns as traditionally the merge function joins dataframes on columns. The resulting dataframe should look like:</p>

<pre class="lang-r prettyprint-override"><code>X  Y   Z
a 111 <NA>
a 111 xxx
c 222 <NA>
c 222 ttt
</code>```

I know it can be done through for loops but I was wondering if it is possible through one/two line of code instead of writing multiple for loops.

答:
```<code>library(dplyr)

df1 %>%
    semi_join(df, by = "x") %>%
    bind_rows(df)

  x   y    z
1 a 111  xxx
2 c 222  ttt
3 a 111 <NA>
4 c 222 <NA>
</code>```

Body:
I have two dataframes as:

df <- data.frame(x=c("a","c"), y=c("111","222"))

df1 <- data.frame(x=c("a","b","b","c"), y=c("111","222","111","222"),z=c('xxx','yyy','ddd','ttt'))

I want to merge these two dataframes based on column x, in such a way that the matched rows from df1 should be added as rows to df and now as columns as traditionally the merge function joins dataframes on columns. The resulting dataframe should look like:

X  Y   Z
a 111 <NA>
a 111 xxx
c 222 <NA>
c 222 ttt

I know it can be done through for loops but I was wondering if it is possible through one/two line of code instead of writing multiple for loops.


问:
What is meant by a type that denotes an implicit conversion
The scala language specification, section 7.2 is about implicit scope:
It explains that implicit scope are the modules associated in some way with the parts of type T. What the parts of T are is listed below. One of those points is

if T denotes an implicit conversion to a type with a method with
  argument types T1,…,Tn and result type U, the union of the parts of
  T1,…,Tn and U;

I can't make head or tails from this. I don't understand how a type T can denote an implicit conversion.

What is meant by this part of the specification of implicit scope?

答:
I believe this is referring to the following situation

```<code>case class Foo(v: Int)
object Foo {
  implicit def stringToFoo(s: String) = Foo(42)
}

def f[A](v: A)(implicit ev: A => Foo) = ev(v)

f("woohoo")
</code>```

where the implicit conversion type T = A => Foo, and Foo is the part associated with type parameter A, therefore object Foo becomes part of the implicit scope and stringToFoo implicit conversion is resolved without needing an import.

Body:
I believe this is referring to the following situation

case class Foo(v: Int)
object Foo {
  implicit def stringToFoo(s: String) = Foo(42)
}

def f[A](v: A)(implicit ev: A => Foo) = ev(v)

f("woohoo")

where the implicit conversion type T = A => Foo, and Foo is the part associated with type parameter A, therefore object Foo becomes part of the implicit scope and stringToFoo implicit conversion is resolved without needing an import.


问:
Problem in implementation of synchronization between producer and consumer using semaphores
Like everyone I was trying to understand linux OS better. I was implementing the producer consumer synchronization problem using semaphores.

i)There will be m producer processes and n consumer processes.

ii) A product is presented with a random number.

iii) The buffer is shared between all consumer and producer processes while in variable is shared between all producer processes and out variable is shared between all consumer processes.

iv)All processes will stop once CTRL+C is entered in the terminal.

Here are the codes:

1.shared.h

```<code>//assume all required headers included
#define buffer_size 5
#define empty_id 0
#define full_id 1
#define mutex_id 2
#define no_sem 3

struct sembuf signall = {0 , 1, 0};
struct sembuf wait = {0, -1, 0};

#define W(s) semop(s, &wait, 1);
#define S(s) semop(s, &signall, 1);
int shmid;
int *buffer;

union semun
{
                int val;
                struct semid_ds *buf;
                unsigned short  *array;
                struct seminfo  *__buf;

} setvalarg[3];

int *create_shared_mem_buffer()
{
        int *shmaddr;
        key_t key = ftok("/home/******/**/B", 1);
        shmid = shmget(key, buffer_size, IPC_CREAT|0660);
        shmaddr= (int *)shmat(shmid, NULL, 0);
        return shmaddr;
}

void clear_buffer()
{
        int i;
        for(i=0;i<buffer_size;i++)
                buffer[i]=0;
}

void releaseSHM(int signum)
{
        int status;
        clear_buffer();
        status = shmctl(shmid, IPC_RMID, NULL);

        status = kill(0, SIGKILL);
        exit(signum);
}

int create_semaphore_set()
{
        key_t key= ftok("/home/******/**/A", 1);

        int semid= semget(key, no_sem, IPC_CREAT|0600);

        setvalarg[0].val=buffer_size;
        semctl(semid, empty_id, SETVAL, setvalarg[0]);

        setvalarg[1].val=0;
        semctl(semid, full_id, SETVAL, setvalarg[1]);

        setvalarg[2].val=1;
        semctl(semid, mutex_id, SETVAL, setvalarg[2]);
        return semid;
}
</code>```

2.producer.c

```<code>#include "shared.h"

void insert_product(int item, int *in, int *buffer)
{
        *in=(*in+1)%buffer_size;
        buffer[*in]=item;
        printf("Producer produces item %d stored in posn %d  \n",item,*in);
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *in;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);

        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        in=(int *)shmat(shmid1, NULL, 0);
        *in=0;

        int m=5;

        for(i=0;i<m;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                item=rand();
                                wait.sem_num=0;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                insert_product(item, in, buffer);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=1;
                                S(semid);
                                sleep(2); //sleep has been introduced to slowdown the output.
                        }
                }
        }
        return 0;
}
</code>```

consumer.c

```<code>#include "shared.h"

int remove_product(int *out, int *buffer)
{
        int item;
        *out=(*out+1)%buffer_size;
        item=buffer[*out];
        buffer[*out]=0;
        return item;
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *out;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);
        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        out=(int *)shmat(shmid1, NULL, 0);
        *out=-1;

        clear_buffer(buffer);

        int n=2;

        for(i=0;i<n;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                wait.sem_num=1;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                item=remove_product(out, buffer);
                                printf("Consumer consumes the product %d \n", item);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=0;
                                S(semid);
                                sleep(2); //sleep has been introduced to slow down the output
                        }
                }
        }
        return 0;
}
</code>```

The output is somewhat like this:

```<code>Producer produces item 1681692777 stored in posn 2
Producer produces item 1681692777 stored in posn 3
Producer produces item 1681692777 stored in posn 4
Producer produces item 1804289383 stored in posn 1
Producer produces item 1804289383 stored in posn 2
Producer produces item 1804289383 stored in posn 3
Producer produces item 1804289383 stored in posn 0
Producer produces item 1804289383 stored in posn 0
Producer produces item 1681692777 stored in posn 0
Producer produces item 1714636915 stored in posn 1
Producer produces item 1714636915 stored in posn 2
Producer produces item 1714636915 stored in posn 3
Producer produces item 846930886 stored in posn 1
Producer produces item 1714636915 stored in posn 4
Producer produces item 846930886 stored in posn 2
Producer produces item 1714636915 stored in posn 0
Producer produces item 846930886 stored in posn 3
Producer produces item 846930886 stored in posn 4
Producer produces item 846930886 stored in posn 0
Producer produces item 1681692777 stored in posn 1
</code>```

```<code>Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 596516649
Consumer consumes the product 596516649
</code>```

As you can see, the same product is produced more than once and same product is consumed more than once.

i)What is the problem? How to resolve it?

ii) Also the processes donot stop when CTRL+C is entered.

I have done it all by myself and I need someone to review it. If further information needed, drop a comment below.

答:
It's a little hard to understand your intended purpose for the apparently three semaphores that you're using in your logic.  However, the problem is that you're "racing" for pulling off the numbers.  And your logic is too complex.

Basically, you need this:

A semaphore which counts the number of numbers that are waiting to be consumed.  post() the semaphore when you add a number; wait() to get one.

A mutex which controls access to the list itself, so that only one thread at a time can actually be inserting or removing values from the segment.

You might also need another semaphore which limits the number of entries that can be added to the segment ... you wait() for permission to add the entry, and as the other processes remove the entry (thus freeing up a slot) they post() to let anyone who's waiting proceed.

Finally:  what you're doing here is an exercise.  In real life there are "pipes" and other IPC mechanisms available "off the shelf" which will take care of these details for you.

Body:
Like everyone I was trying to understand linux OS better. I was implementing the producer consumer synchronization problem using semaphores.

i)There will be m producer processes and n consumer processes.

ii) A product is presented with a random number.

iii) The buffer is shared between all consumer and producer processes while in variable is shared between all producer processes and out variable is shared between all consumer processes.

iv)All processes will stop once CTRL+C is entered in the terminal.

Here are the codes:

1.shared.h

//assume all required headers included
#define buffer_size 5
#define empty_id 0
#define full_id 1
#define mutex_id 2
#define no_sem 3

struct sembuf signall = {0 , 1, 0};
struct sembuf wait = {0, -1, 0};

#define W(s) semop(s, &wait, 1);
#define S(s) semop(s, &signall, 1);
int shmid;
int *buffer;

union semun
{
                int val;
                struct semid_ds *buf;
                unsigned short  *array;
                struct seminfo  *__buf;

} setvalarg[3];

int *create_shared_mem_buffer()
{
        int *shmaddr;
        key_t key = ftok("/home/******/**/B", 1);
        shmid = shmget(key, buffer_size, IPC_CREAT|0660);
        shmaddr= (int *)shmat(shmid, NULL, 0);
        return shmaddr;
}

void clear_buffer()
{
        int i;
        for(i=0;i<buffer_size;i++)
                buffer[i]=0;
}

void releaseSHM(int signum)
{
        int status;
        clear_buffer();
        status = shmctl(shmid, IPC_RMID, NULL);

        status = kill(0, SIGKILL);
        exit(signum);
}

int create_semaphore_set()
{
        key_t key= ftok("/home/******/**/A", 1);

        int semid= semget(key, no_sem, IPC_CREAT|0600);

        setvalarg[0].val=buffer_size;
        semctl(semid, empty_id, SETVAL, setvalarg[0]);

        setvalarg[1].val=0;
        semctl(semid, full_id, SETVAL, setvalarg[1]);

        setvalarg[2].val=1;
        semctl(semid, mutex_id, SETVAL, setvalarg[2]);
        return semid;
}

2.producer.c

#include "shared.h"

void insert_product(int item, int *in, int *buffer)
{
        *in=(*in+1)%buffer_size;
        buffer[*in]=item;
        printf("Producer produces item %d stored in posn %d  \n",item,*in);
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *in;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);

        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        in=(int *)shmat(shmid1, NULL, 0);
        *in=0;

        int m=5;

        for(i=0;i<m;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                item=rand();
                                wait.sem_num=0;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                insert_product(item, in, buffer);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=1;
                                S(semid);
                                sleep(2); //sleep has been introduced to slowdown the output.
                        }
                }
        }
        return 0;
}

consumer.c

#include "shared.h"

int remove_product(int *out, int *buffer)
{
        int item;
        *out=(*out+1)%buffer_size;
        item=buffer[*out];
        buffer[*out]=0;
        return item;
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *out;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);
        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        out=(int *)shmat(shmid1, NULL, 0);
        *out=-1;

        clear_buffer(buffer);

        int n=2;

        for(i=0;i<n;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                wait.sem_num=1;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                item=remove_product(out, buffer);
                                printf("Consumer consumes the product %d \n", item);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=0;
                                S(semid);
                                sleep(2); //sleep has been introduced to slow down the output
                        }
                }
        }
        return 0;
}

The output is somewhat like this:

Producer produces item 1681692777 stored in posn 2
Producer produces item 1681692777 stored in posn 3
Producer produces item 1681692777 stored in posn 4
Producer produces item 1804289383 stored in posn 1
Producer produces item 1804289383 stored in posn 2
Producer produces item 1804289383 stored in posn 3
Producer produces item 1804289383 stored in posn 0
Producer produces item 1804289383 stored in posn 0
Producer produces item 1681692777 stored in posn 0
Producer produces item 1714636915 stored in posn 1
Producer produces item 1714636915 stored in posn 2
Producer produces item 1714636915 stored in posn 3
Producer produces item 846930886 stored in posn 1
Producer produces item 1714636915 stored in posn 4
Producer produces item 846930886 stored in posn 2
Producer produces item 1714636915 stored in posn 0
Producer produces item 846930886 stored in posn 3
Producer produces item 846930886 stored in posn 4
Producer produces item 846930886 stored in posn 0
Producer produces item 1681692777 stored in posn 1

Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 596516649
Consumer consumes the product 596516649

As you can see, the same product is produced more than once and same product is consumed more than once.

i)What is the problem? How to resolve it?

ii) Also the processes donot stop when CTRL+C is entered.

I have done it all by myself and I need someone to review it. If further information needed, drop a comment below.


问:
Nginx location with regex in the middle of path
i'm trying to configure Nginx to parse correctly two similar paths with a regex in it.

I have 2 services:

/api/v1/myservice/{var}/client

/api/v1/myservice/{var}/client/detail

{var} is a variable I'm reading which is working

Here my code (not using the var here):

```<code>location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}

location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}
</code>```

When I run curl like the following:

```<code>curl http://localhost/api/v1/myservice/623723852/client/detail
</code>```

I see the response from the first location:
"Service 1"

What Am I doing wrong?
thanks

答:
No need to have nested locations as in the other answer. The nested locations in NGINX often give a false impression about directives' inheritance. More often than not, they are not inherited, because NGINX chooses one specific location anyway. For these reasons, if you can, avoid nested locations.

You can simply change the order of locations so that the more specific one goes first. NGINX will match the one that appears first in the config (if they both match):

```<code>location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}

location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}
</code>```

Alternatively, somewhat better (for performance reasons), you can adjust your regexes for more exact matching. Then the placement in configuration won't matter:

```<code>location ~ ^/api/v1/myservice/(.*)/client$ {
     return 200 "service 1 ";
}

location ~ ^/api/v1/myservice/(.*)/client/detail$ {
     return 200 "service 2";
}
</code>```

Body:
i'm trying to configure Nginx to parse correctly two similar paths with a regex in it.

I have 2 services:

/api/v1/myservice/{var}/client

/api/v1/myservice/{var}/client/detail

{var} is a variable I'm reading which is working

Here my code (not using the var here):

location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}

location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}

When I run curl like the following:

curl http://localhost/api/v1/myservice/623723852/client/detail

I see the response from the first location:
"Service 1"

What Am I doing wrong?
thanks

Body:
No need to have nested locations as in the other answer. The nested locations in NGINX often give a false impression about directives' inheritance. More often than not, they are not inherited, because NGINX chooses one specific location anyway. For these reasons, if you can, avoid nested locations.

You can simply change the order of locations so that the more specific one goes first. NGINX will match the one that appears first in the config (if they both match):

location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}

location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}

Alternatively, somewhat better (for performance reasons), you can adjust your regexes for more exact matching. Then the placement in configuration won't matter:

location ~ ^/api/v1/myservice/(.*)/client$ {
     return 200 "service 1 ";
}

location ~ ^/api/v1/myservice/(.*)/client/detail$ {
     return 200 "service 2";
}


问:
Extract pkcs7 (byte[]) from a pdf file using IText or ITextSharp or BouncyCastle
How can I extract, from a pdf signed file, the PKCS7 package encoded, using either IText or BouncyCastle, so i can either store or validate in another framework?
In fact, how can I get, at all, a PKCS7 encoded package from a pdf signed file?</p>

答:
A friend of mine helped me on getting the answer.

```<code>public static byte[] ExtractPKCS7From(string path)
{
    AcroFields acroFields = new PdfReader(path).AcroFields;
    List<string> names = acroFields.GetSignatureNames();

    foreach(var name in names)
    {
        PdfDictionary dict = acroFields.GetSignatureDictionary(name);
        PdfString contents =
            (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));

        return contents.GetOriginalBytes();
    }
    return null;
}
</code>```

Pretty straight forward, isn't it?

ContentLicense: CC BY-SA 3.0

Body:
A friend of mine helped me on getting the answer.

public static byte[] ExtractPKCS7From(string path)
{
    AcroFields acroFields = new PdfReader(path).AcroFields;
    List<string> names = acroFields.GetSignatureNames();

    foreach(var name in names)
    {
        PdfDictionary dict = acroFields.GetSignatureDictionary(name);
        PdfString contents =
            (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));

        return contents.GetOriginalBytes();
    }
    return null;
}

Pretty straight forward, isn't it?


问:
The method presentations.batchUpdate throws "Internal error encountered"
I'm working on generation of Google Presentation and sometimes batchUpdate throws the error:

```<code>{
  "error": {
    "code": 500,
    "message": "Internal error encountered.",
    "status": "INTERNAL"
  }
}
</code>```

Here's the example of the request body

答:
Issue:

Your request body is huge. You are requesting many updates in the presentation with a single call. Since you are getting a 500 error, the server is most likely having problems while processing this huge amount of requests.

It's certainly not a question of write request limits, since you are only making one single (large) write request (and HTTP status is not the appropriate one either).

Solution:

In any case, I would suggest you to split your call into as many parts as necessary so that you never get this error. Group the requests into different request bodies and call batchUpdate several successive times. This should fix your problem.

Reference:

presentations.batchUpdate

Slides API: Usage Limits

500 Internal Server Error

Body:
I'm working on generation of Google Presentation and sometimes batchUpdate throws the error:

{
  "error": {
    "code": 500,
    "message": "Internal error encountered.",
    "status": "INTERNAL"
  }
}

Here's the example of the request body


问:
CronTab Run only ONCE in a year
Here is my job

```<code>45 5 5 2 WED /usr/bin/python3 /home/pi/Saqib/RaspBerryPiAdhan/www/commands/player.py "/static/media/fajr1.mp3" "Office Ustairs speaker"
</code>```

Jobs looks fine, as I want it to run only once in a year...however i am using a module called "croniter"...and it seems like it has a bug.

my job is SET to fire only on wed at 5 45, Feb of 5th. however when i use the get_next() method, it returns the next fire date of coming/next wednesday as well.

I need to fire it only ONCE.

my system is Linux Debian kernal.

Anyway around this?

答:
@Romeo Ninov has the right idea!

Check https://crontab.guru/#45_5_5_2_*

45 5 5 2 * = “At 05:45 on day-of-month 5 in February.”

Title: CronTab Run only ONCE in a year

Body:
Here is my job

45 5 5 2 WED /usr/bin/python3 /home/pi/Saqib/RaspBerryPiAdhan/www/commands/player.py "/static/media/fajr1.mp3" "Office Ustairs speaker"

Jobs looks fine, as I want it to run only once in a year...however i am using a module called "croniter"...and it seems like it has a bug.

my job is SET to fire only on wed at 5 45, Feb of 5th. however when i use the get_next() method, it returns the next fire date of coming/next wednesday as well.

I need to fire it only ONCE.

my system is Linux Debian kernal.

Anyway around this?


问:
is it possible to reduce delete code size with templates in C++
I have a lot of items, I am deleting. For each item, I am calling the following lines of related codes:

```<code>if (item) {
   delete item;
   item=nullptr;
}
</code>```

so, instead, I am considering of using templates by defining a single function:

```<code>template <typename T>
void delete_it(T &item) {
    if (item) {
       delete item;
       item=nullptr;
    }
}
</code>```

from this on, the following lines work fine:

```<code>delete_it(an_item);
delete_it(another_item);
</code>```

I have checked it by allocating a character array dynamically and it seemed to work fine.
However, I haven't seen it used in anywhere. Is it an appropriate way of deleting?Is there a library(std for example) function doing just that? Thank you,

答:
```<code> if (item) {
       delete item;
</code>```

The if here is useless. You don't need it.

I have checked it by allocating a character array dynamically
  ...
  Is it an appropriate way of deleting?

delete is not an appropriate way of deleting a dynamic array created with new[]. Only delete[] is.

I haven't seen it used in anywhere

delete is typically only used in the destructor of a RAII class. In such context, setting the pointer to null is redundant, because the pointer is about to stop existing. This is probably why you haven't seen what you're doing elsewhere.

Even further, best practice is to apply the single responsibility principle, and use a smart pointer or a container instead of new'ing and deleting manually. There is a standard container for dynamic arrays: std::vector as well as a standard container for character arrays that represent strings: std::string.

Bonus reminder: Avoid unnecessary dynamic allocation.

Body:
I have a lot of items, I am deleting. For each item, I am calling the following lines of related codes:

if (item) {
   delete item;
   item=nullptr;
}

so, instead, I am considering of using templates by defining a single function:

template <typename T>
void delete_it(T &item) {
    if (item) {
       delete item;
       item=nullptr;
    }
}

from this on, the following lines work fine:

delete_it(an_item);
delete_it(another_item);

I have checked it by allocating a character array dynamically and it seemed to work fine.
However, I haven't seen it used in anywhere. Is it an appropriate way of deleting?Is there a library(std for example) function doing just that? Thank you,

Body:
 if (item) {
       delete item;

The if here is useless. You don't need it.

I have checked it by allocating a character array dynamically
  ...
  Is it an appropriate way of deleting?

delete is not an appropriate way of deleting a dynamic array created with new[]. Only delete[] is.

I haven't seen it used in anywhere

delete is typically only used in the destructor of a RAII class. In such context, setting the pointer to null is redundant, because the pointer is about to stop existing. This is probably why you haven't seen what you're doing elsewhere.

Even further, best practice is to apply the single responsibility principle, and use a smart pointer or a container instead of new'ing and deleting manually. There is a standard container for dynamic arrays: std::vector as well as a standard container for character arrays that represent strings: std::string.

Bonus reminder: Avoid unnecessary dynamic allocation.


问:
Firebase Firestore Query Performance
extra question to:
Queries scale with the size of your result set, not the size of your data set

Maybe this is a bit old but I still want to ask this. What is about the document size?

Is it equally fast to query 10x 1mb results out of 1000 AND querying 10x 1kb results out of 1000? I am curious about this on the Cloud Functions backend side. So I only want a part of the data from my collection query result using cloud functions and creating an API that queries the entire result (10x 1mb) and returns to the client only a part of the data. Or is it faster to store the partial documents in a separate collection and querying on this collection?

So would it be the same performance without taking the data transfer to the client in consideration?

答:
The query performance is dependent on the size of the result. Since 10Mb is larger than 10Kb, it will be slower to get 10Mb than it is to get 10Kb. That applies both to the transfer over the network as to the reading of the data from disk or memory. Reading more data simply takes more time.

The guarantee Firestore makes is that the amount of data in the collection has no effect on the query performance. So if you get 10Mb of data from 10Gb of data in the collection, it will take the same amount of time as when you that the same 10Mb from a 10Tb collection.

Title: Firebase Firestore Query Performance


问:
Why index is not used when ordering?
I have this table structure:

```<code>CREATE TABLE users
(
uid bigint NOT NULL,
first_name character varying,
last_name character varying,
email character varying,
login_count integer,
CONSTRAINT users_pkey PRIMARY KEY (uid)
)
</code>```

with this index:

```<code>CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);
</code>```

The login_count column may consists of NULL values and i need to select all users ordered descending by login_count and need NULLs to be at the end.

Unfortunately this query:

```<code>SELECT * FROM users ORDER BY login_count DESC LIMIT 30;
</code>```

won't use the index, so NULLs are at the beggining, why?

答:
Your query is effectively ORDER BY login_count DESCNULLS FIRSTLIMIT 30 as explained here. On this page it describes how an index can satisfy an ordering:

An index stored in ascending order
  with nulls first can satisfy either
  ORDER BY x ASC NULLS FIRST or ORDER BY x DESC NULLS LAST
  depending on which direction it is scanned in.

So your index is the same - it can satisfy ASC NULLS FIRST and DESC NULLS LAST, but your query is DESC NULLS FIRST.

Title: Why index is not used when ordering?

Body:
I have this table structure:

CREATE TABLE users
(
uid bigint NOT NULL,
first_name character varying,
last_name character varying,
email character varying,
login_count integer,
CONSTRAINT users_pkey PRIMARY KEY (uid)
)

with this index:

CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);

The login_count column may consists of NULL values and i need to select all users ordered descending by login_count and need NULLs to be at the end.

Unfortunately this query:

SELECT * FROM users ORDER BY login_count DESC LIMIT 30;

won't use the index, so NULLs are at the beggining, why?


问:
In ElasticSearch 7+ how do you search all text fields?
I want to search for a word in documents I have stored in Elasticsearch 7.3

An example of what I would like on previous versions of Elasticsearch that worked is:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_all": "oliver"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}
</code>```

But this query will not work on Elasticsearch 7+ because _all has been removed. How can I write the query to accomplish the same thing now that the _all field is gone?

Note: I've read the suggestions to use copy_to to copy all fields into a custom field but that requires explicitly writing out each field to include in the all_fields field. Since I have lots of little fields I am trying to avoid this and instead replicate the behavior that being able to query _all allowed.

答:
I have run into a similar situation. As far as I can tell, there are two ways you can search all text fields in a world without the _all field.

The most optimal way is probably to use a simple_query_string or query_string query. By default these will search all string (text or keyword) fields.

If, for some reason, you needed an explicit field that contained all text tokens like the _all field, you can create your own. You can use "copy_to": "_all" on explicitly mapped text or keyword fields to include known fields, but this only solves half the problem. To include unknown fields in this field, you would additionally need to create a dynamic template with the "copy_to": "_all" mapping. Dynamic templates specifically match dynamic fields, so if you combine this with the copy_to's on the explicitly mapped fields, you should have a field that contains all text tokens from both known and unknown fields. The reason this is less optimal is because this can have a significant impact on the size of your database. Here is a simple mapping example that should accomplish what you want:

```<code>  {
    "mappings": {
      "dynamic_templates": [
        {
          "all_text": {
            "match_mapping_type": "string",
            "mapping": {
              "copy_to": "_all",
              "type": "text"
            }
          }
        }
      ],
      "properties": {
        "_all": {
          "type": "text"
        },
        "email": {
          "type": "text",
          "copy_to": [
            "_all"
          ]
        },
        "name": {
          "type": "keyword",
          "copy_to": [
            "_all"
          ]
        }
      }
    }
  }
</code>```

Body:
I want to search for a word in documents I have stored in Elasticsearch 7.3

An example of what I would like on previous versions of Elasticsearch that worked is:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_all": "oliver"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}

But this query will not work on Elasticsearch 7+ because _all has been removed. How can I write the query to accomplish the same thing now that the _all field is gone?

Note: I've read the suggestions to use copy_to to copy all fields into a custom field but that requires explicitly writing out each field to include in the all_fields field. Since I have lots of little fields I am trying to avoid this and instead replicate the behavior that being able to query _all allowed.

Body:
I have run into a similar situation. As far as I can tell, there are two ways you can search all text fields in a world without the _all field.

The most optimal way is probably to use a simple_query_string or query_string query. By default these will search all string (text or keyword) fields.

If, for some reason, you needed an explicit field that contained all text tokens like the _all field, you can create your own. You can use "copy_to": "_all" on explicitly mapped text or keyword fields to include known fields, but this only solves half the problem. To include unknown fields in this field, you would additionally need to create a dynamic template with the "copy_to": "_all" mapping. Dynamic templates specifically match dynamic fields, so if you combine this with the copy_to's on the explicitly mapped fields, you should have a field that contains all text tokens from both known and unknown fields. The reason this is less optimal is because this can have a significant impact on the size of your database. Here is a simple mapping example that should accomplish what you want:

  {
    "mappings": {
      "dynamic_templates": [
        {
          "all_text": {
            "match_mapping_type": "string",
            "mapping": {
              "copy_to": "_all",
              "type": "text"
            }
          }
        }
      ],
      "properties": {
        "_all": {
          "type": "text"
        },
        "email": {
          "type": "text",
          "copy_to": [
            "_all"
          ]
        },
        "name": {
          "type": "keyword",
          "copy_to": [
            "_all"
          ]
        }
      }
    }
  }


问:
Why are the statements after if statement not running as expected in a synchronized method
I have a simple class with two synchronized methods. One which should withdraw cash and one which should deposit cash.

And then I have another main class with an inner class. Both the main class and the inner class are implementing Runnable, where the main class is running the "withdraw"-method and the inner class running the "deposit"-method.

When that is done I am creating two Threads to run (i.e. start) the separate methods in the separate "Runnable"-classes.

The class with the synchronized methods have these methods:

```<code>package test;

public class ThreadClass {

int amount = 10;

synchronized void withdraw(int amount) {
    System.out.println("going to withdraw...");

    if(this.amount < amount) {
        System.out.println("Less balance..");
        try {
            wait();

        }
        catch(Exception e) {
            e.printStackTrace();
        }

    }
    this.amount+=amount;
    System.out.println("withdrawal completed");
}

synchronized void deposit(int amount) {
    System.out.println("going to deposit...");
    this.amount+=amount;
    System.out.println("deposit completed");
    notify();
 }
}
</code>```

and the class which is responsible for implementing Runnable and also running the example application looks like this:

```<code>package test;

public class ThreadTest implements Runnable {

@Override
public void run() {

    ThreadClass withDraw = new ThreadClass();
    withDraw.withdraw(20);

}

class Threadtest2 implements Runnable{

@Override
public void run() {
    ThreadClass t10 = new ThreadClass();
    t10.deposit(60);

 }

}

public static void main(String[] args) throws InterruptedException {

    ThreadTest tester = new ThreadTest();
    ThreadTest.Threadtest2 tester2 = tester.new Threadtest2();

    Thread t1 = new Thread(tester);
    t1.start();

    Thread t2 = new Thread(tester2);
    t2.start();

 }

}
</code>```

So when I run this program I am expecting that the notify()-call in the deposit method should notify the withdraw()-method so that the last lines also get executed, i.e.

```<code>    this.amount+=amount;
    System.out.println("withdrawal completed");
</code>```

..but the application is keeping running and never get to that line so I have to manually terminate it. Is this not the right way of doing it?

答:
The synchronized methods are synchronized on the current instance of the object. So wait() and notify() should be called on the exact same object. But you create two different instances of the ThreadClass object, so you call wait() and notify() on different objects.

You should create a single instance of ThreadClass and pass it to the threads, e.g. via a constructor:

```<code>public class ThreadTest implements Runnable {

    private ThreadClass account;

    public ThreadTest(ThreadClass account) {
        this.account = account;
    }

    @Override
    public void run() {
        account.withdraw(20);
    }

}

class Threadtest2 implements Runnable{

    private ThreadClass account;

    public Threadtest2(ThreadClass account) {
        this.account = account;
    }

    @Override
    public void run() {
        account.deposit(60);
    }

}

</code>```

And then initialize them like so:

```<code>ThreadClass account = new ThreadClass();

ThreadTest tester = new ThreadTest(account);
ThreadTest.Threadtest2 tester2 = tester.new Threadtest2(account);

</code>```

Also note that after wait() the condition this.amount < amount could still be true, if the deposit amount was insufficient. So you should check the amount and call wait() in cycle, until this condition is satisfied.

Body:
I have a simple class with two synchronized methods. One which should withdraw cash and one which should deposit cash.

And then I have another main class with an inner class. Both the main class and the inner class are implementing Runnable, where the main class is running the "withdraw"-method and the inner class running the "deposit"-method.

When that is done I am creating two Threads to run (i.e. start) the separate methods in the separate "Runnable"-classes.

The class with the synchronized methods have these methods:

package test;

public class ThreadClass {

int amount = 10;

synchronized void withdraw(int amount) {
    System.out.println("going to withdraw...");

    if(this.amount < amount) {
        System.out.println("Less balance..");
        try {
            wait();

        }
        catch(Exception e) {
            e.printStackTrace();
        }

    }
    this.amount+=amount;
    System.out.println("withdrawal completed");
}

synchronized void deposit(int amount) {
    System.out.println("going to deposit...");
    this.amount+=amount;
    System.out.println("deposit completed");
    notify();
 }
}

and the class which is responsible for implementing Runnable and also running the example application looks like this:

package test;

public class ThreadTest implements Runnable {

@Override
public void run() {

    ThreadClass withDraw = new ThreadClass();
    withDraw.withdraw(20);

}

class Threadtest2 implements Runnable{

@Override
public void run() {
    ThreadClass t10 = new ThreadClass();
    t10.deposit(60);

 }

}

public static void main(String[] args) throws InterruptedException {

    ThreadTest tester = new ThreadTest();
    ThreadTest.Threadtest2 tester2 = tester.new Threadtest2();

    Thread t1 = new Thread(tester);
    t1.start();

    Thread t2 = new Thread(tester2);
    t2.start();

 }

}

So when I run this program I am expecting that the notify()-call in the deposit method should notify the withdraw()-method so that the last lines also get executed, i.e.

    this.amount+=amount;
    System.out.println("withdrawal completed");

..but the application is keeping running and never get to that line so I have to manually terminate it. Is this not the right way of doing it?

Body:
The synchronized methods are synchronized on the current instance of the object. So wait() and notify() should be called on the exact same object. But you create two different instances of the ThreadClass object, so you call wait() and notify() on different objects.

You should create a single instance of ThreadClass and pass it to the threads, e.g. via a constructor:

public class ThreadTest implements Runnable {

    private ThreadClass account;

    public ThreadTest(ThreadClass account) {
        this.account = account;
    }

    @Override
    public void run() {
        account.withdraw(20);
    }

}

class Threadtest2 implements Runnable{

    private ThreadClass account;

    public Threadtest2(ThreadClass account) {
        this.account = account;
    }

    @Override
    public void run() {
        account.deposit(60);
    }

}

And then initialize them like so:

ThreadClass account = new ThreadClass();

ThreadTest tester = new ThreadTest(account);
ThreadTest.Threadtest2 tester2 = tester.new Threadtest2(account);

Also note that after wait() the condition this.amount < amount could still be true, if the deposit amount was insufficient. So you should check the amount and call wait() in cycle, until this condition is satisfied.


问:
Sidebar partials for multilevel user in Codeigniter
what is the best code for sidebar partial for multilevel?

Is it just do in Controller like :

```<code>public function tambahNota()
{
    $head['title'] = 'Tambah Nota';

    if($this->session->userdata('userLevel') == 1){
        $this->load->view('partials/sidebarAdmin');
    } elseif($this->session->userdata('userLevel') == 2){
        $this->load->view('partials/sidebarUser');
    }

    $this->load->view('partials/footer');
    $this->load->view('nota/tambahNota');
</code>```

.. or in View partials/sidebar?

```<code><?php if ($this->session->userdata('userLevel') == 1) {?>
     ..script of admin sidebar..
<?php } else if($this->session->userdata('userLevel') == 2) {?>
     ..script of user sidebar..
<?php } ?>
</code>```

Thank you.

答:
Both the process is good. It up to you to choose yours.

As it is templating, I like to keep it the view. so, later on, I can easily find the file for edit.

Body:
what is the best code for sidebar partial for multilevel?

Is it just do in Controller like :

public function tambahNota()
{
    $head['title'] = 'Tambah Nota';

    if($this->session->userdata('userLevel') == 1){
        $this->load->view('partials/sidebarAdmin');
    } elseif($this->session->userdata('userLevel') == 2){
        $this->load->view('partials/sidebarUser');
    }

    $this->load->view('partials/footer');
    $this->load->view('nota/tambahNota');

.. or in View partials/sidebar?

<?php if ($this->session->userdata('userLevel') == 1) {?>
     ..script of admin sidebar..
<?php } else if($this->session->userdata('userLevel') == 2) {?>
     ..script of user sidebar..
<?php } ?>

Thank you.


问:
Azure Function Unit Testing with FunctionStartup
I am writing a unit test project for the azure functions which is using Startup class inheriting the FunctionStartUp. In this Startup class I am loading my all dependencies and configuration with Enviornment variables loading.

Problem is while running the unit test method I am getting the Enviornment variables values as null (because Startup class was not called hence Enviornment variables are not Set).

Can anyone suggest me how load Enviornment variables which are set in local.Setting.json and appsetting.json file?

答: In your unit test code, you have to set the variables using Environment.SetEnvironmentVariable("key", "value");


问:
use a C++ class with Rcpp to modify it from C or R
I'm starting to play with rcpp and I'd like to make an object in which I can modify the variables from R or rcpp.
It seems that making a class is somehow a good solution, as I can modify the fields using the '$' from R, or directly using Rcpp functions. My problem is that when I try to modify a variable of my class from rcpp with a class method, R simply crashes...

below is a small example. The class contains some variables of different types, plus a constructor and two functions, one to print values (to test if changes are trully done when I do something), and one to change the variables of the class.

```<code>library(Rcpp)
library(RcppArmadillo)

# ODEs can also be described using Rcpp
Rcpp::sourceCpp(code = '

#include <Rcpp.h>
//#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
class parameters{
public:
  NumericMatrix mat;
  double val;
  int n;
  NumericVector dB;

  parameters(double x):
    val(x) {}

  NumericVector changes(){
    dB[0] = val;
    dB[1] = 12;
    //dB[1] = mean(mat(1,_));
  }

  void print(){
    Rcout << "val:"  << std::endl << val << std::endl;
    Rcout << "mat:"  << std::endl << mat << std::endl;
  }
};

RCPP_MODULE(ParamModule){
using namespace Rcpp;
  class_<parameters>("parameters")

  .constructor<double>("constructor")

  .method("changes", &parameters::changes)
  .method("print", &parameters::print)

  .field("val", &parameters::val)
  .field("mat", &parameters::mat)
  .field("n", &parameters::n)
  .field("dB", &parameters::dB)
  ;
}

// [[Rcpp::export]]
NumericMatrix addVal(NumericMatrix mat, double val, int n){
  int i = 0;
  for (i=0; i<n; i++){
    mat(i, 1) = mat(i,1) + val;
  }

  return mat;
}

')
</code>```

and here is the code that I use to test it:

```<code>p = new(parameters,5)
str(p) # constructor initialise the field val, ok
p$mat = matrix(5, nrow = 5, ncol = 5)
p$print()  # field mat initialised, ok
p$mat = matrix(0.1, nrow = 5, ncol = 5)
p$print()  # field mat changed, ok
addVal(p$mat, 2, 5)
p$print() # sounds like p is a pointer, ok
p$changes() #...
</code>```

This last line is where the problem occurs (no error message, as R simply crashes).

When I compile the class I have this warning:

```<code>Warning message:
No function found for Rcpp::export attribute at file215bf0ef501.cpp:8
</code>```

Also, I saw here that I might need to use these two lines:

```<code>ParamModule = Module("ParamModule")
parameters = ParamModule$parameters
</code>```

but I obtain an error message when I run the last one:

```<code>Error in Module(module, mustStart = TRUE) :
  Failed to initialize module pointer: Error in FUN(X[[i]], ...): no such symbol _rcpp_module_boot_ParamModule in package .GlobalEnv
</code>```

(ParamModule is present as an environment in the global environment).

So, my questions are:

1) Why the function p$changes() is not working

2) Do I need to load paramModule? It doesn't seem to change anything...

Thanks!

答:
A small edition of the problematic method resolved the issue. I basically made two (stupid) mistakes:

1) I did not return something, even if when the function was expected to return a numeric vector (I'm surprised that this compiled)

2) I used db[0] instead of db(0)

so the new edited function is:

```<code>NumericVector changes(){
    dB(0) = val;
    dB(1) = 12;
    //dB[1] = mean(mat(1,_));
    return dB;
  }

</code>```

coatless and Dirk, Thanks for your answers, but it seems that there is no need to use them in a package (as what I did is working correctly). Did I miss something?

Body:
I'm starting to play with rcpp and I'd like to make an object in which I can modify the variables from R or rcpp.
It seems that making a class is somehow a good solution, as I can modify the fields using the '$' from R, or directly using Rcpp functions. My problem is that when I try to modify a variable of my class from rcpp with a class method, R simply crashes...

below is a small example. The class contains some variables of different types, plus a constructor and two functions, one to print values (to test if changes are trully done when I do something), and one to change the variables of the class.

library(Rcpp)
library(RcppArmadillo)

# ODEs can also be described using Rcpp
Rcpp::sourceCpp(code = '

#include <Rcpp.h>
//#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
class parameters{
public:
  NumericMatrix mat;
  double val;
  int n;
  NumericVector dB;

  parameters(double x):
    val(x) {}

  NumericVector changes(){
    dB[0] = val;
    dB[1] = 12;
    //dB[1] = mean(mat(1,_));
  }

  void print(){
    Rcout << "val:"  << std::endl << val << std::endl;
    Rcout << "mat:"  << std::endl << mat << std::endl;
  }
};

RCPP_MODULE(ParamModule){
using namespace Rcpp;
  class_<parameters>("parameters")

  .constructor<double>("constructor")

  .method("changes", &parameters::changes)
  .method("print", &parameters::print)

  .field("val", &parameters::val)
  .field("mat", &parameters::mat)
  .field("n", &parameters::n)
  .field("dB", &parameters::dB)
  ;
}

// [[Rcpp::export]]
NumericMatrix addVal(NumericMatrix mat, double val, int n){
  int i = 0;
  for (i=0; i<n; i++){
    mat(i, 1) = mat(i,1) + val;
  }

  return mat;
}

')

and here is the code that I use to test it:

p = new(parameters,5)
str(p) # constructor initialise the field val, ok
p$mat = matrix(5, nrow = 5, ncol = 5)
p$print()  # field mat initialised, ok
p$mat = matrix(0.1, nrow = 5, ncol = 5)
p$print()  # field mat changed, ok
addVal(p$mat, 2, 5)
p$print() # sounds like p is a pointer, ok
p$changes() #...

This last line is where the problem occurs (no error message, as R simply crashes).

When I compile the class I have this warning:

Warning message:
No function found for Rcpp::export attribute at file215bf0ef501.cpp:8

Also, I saw here that I might need to use these two lines:

ParamModule = Module("ParamModule")
parameters = ParamModule$parameters

but I obtain an error message when I run the last one:

Error in Module(module, mustStart = TRUE) :
  Failed to initialize module pointer: Error in FUN(X[[i]], ...): no such symbol _rcpp_module_boot_ParamModule in package .GlobalEnv

(ParamModule is present as an environment in the global environment).

So, my questions are:

1) Why the function p$changes() is not working

2) Do I need to load paramModule? It doesn't seem to change anything...

Thanks!

Body:
A small edition of the problematic method resolved the issue. I basically made two (stupid) mistakes:

1) I did not return something, even if when the function was expected to return a numeric vector (I'm surprised that this compiled)

2) I used db[0] instead of db(0)

so the new edited function is:

NumericVector changes(){
    dB(0) = val;
    dB(1) = 12;
    //dB[1] = mean(mat(1,_));
    return dB;
  }

coatless and Dirk, Thanks for your answers, but it seems that there is no need to use them in a package (as what I did is working correctly). Did I miss something?


问:
How do I Select Manual Medoids in PAM Clustering in r?
I am trying to specify my own medoids in a PAM algorithm, but no matter what I specify, it chooses its own.

Using dummy data below, if I put the data into cluster::pam and try to specify rows 1 and 5 (or any other options) as the medoids, it picks different rows as an output.

```<code># Dummy Data
data <- data.frame(age = 1:10, height = 1:10, weight = 10:1, size = 10:1)

# Cluster
library(cluster)
pam_fit <- pam(data, metric = "euclidean", k = 2, medoids = c(1, 5))

# Output
pam_fit$medoids
     age height weight size
[1,]   2      2      9    9
[2,]   7      7      4    4
</code>```

What am I doing wrong? What is the input for Medoids if not row numbers? Thanks in advance

答:
1) Add first the clustering output to your data

data2 <- mutate(data, cluster = pam_fit$clustering)

2) Then select the rows while applying the fit medoids:

data2[pam_fit$medoids,]

Body:
I am trying to specify my own medoids in a PAM algorithm, but no matter what I specify, it chooses its own.

Using dummy data below, if I put the data into cluster::pam and try to specify rows 1 and 5 (or any other options) as the medoids, it picks different rows as an output.

# Dummy Data
data <- data.frame(age = 1:10, height = 1:10, weight = 10:1, size = 10:1)

# Cluster
library(cluster)
pam_fit <- pam(data, metric = "euclidean", k = 2, medoids = c(1, 5))

# Output
pam_fit$medoids
     age height weight size
[1,]   2      2      9    9
[2,]   7      7      4    4

What am I doing wrong? What is the input for Medoids if not row numbers? Thanks in advance


问:
Iterate every 2 elements from list at a time
Having list as ,

```<code>l = [1,2,3,4,5,6,7,8,9,0]
</code>```

How can i iterate every two elements at a time ?

I am trying this ,

```<code>for v, w in zip(l[:-1],l[1:]):
    print [v, w]
</code>```

and getting output is like ,

```<code>[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]
</code>```

Expected output is

```<code>[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]
</code>```

答:
Another solution with map (with slightly different syntax than other answers). In a list with an odd number of elements, the last element is paired with None:

```<code>>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> map(None, a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, None)]
</code>```

You can modify the function to return e.g. lists instead of tuples:

```<code>>>> map(lambda x,y:[x,y], a[::2], a[1::2])
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, None]]

>>> for e in map(lambda x,y:[x,y], a[::2], a[1::2]):
...     print e
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, None]
</code>```

Edit: this solution only works on Python 2.x.

Body:
Having list as ,

l = [1,2,3,4,5,6,7,8,9,0]

How can i iterate every two elements at a time ?

I am trying this ,

for v, w in zip(l[:-1],l[1:]):
    print [v, w]

and getting output is like ,

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]

Expected output is

[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]

Body:
Another solution with map (with slightly different syntax than other answers). In a list with an odd number of elements, the last element is paired with None:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> map(None, a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, None)]

You can modify the function to return e.g. lists instead of tuples:

>>> map(lambda x,y:[x,y], a[::2], a[1::2])
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, None]]

>>> for e in map(lambda x,y:[x,y], a[::2], a[1::2]):
...     print e
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, None]

Edit: this solution only works on Python 2.x.


问:
Get all documents where document ID contains my string
I have a Firebase collection, and my documents ID are like this :

User1-User2

User1-User3

User2-User4

User4-User1

In my Flutter app, I want to get only the documents where the document ID contains "User1".

Is it possible to do it?

答:
I finally decided to use Algolia, which is an external service allowing to do what I wanted to do. It's really easy to use and really practical ^^ I posted samples of my data into Algolia, and the research worked perfectly ^^

Thank you for your help! :)


问:
How to Iterate through HashMap containing Arraylist
Can you send the implementation how to Iterate through HashMap containing ArrayList, here is my code, I created 2 ArrayLists and added to Hashmap and I need to iterate through</p>

```<code>public class t {

public static void main(String[] args) {

    ArrayList<String> a = new ArrayList<String>();
    ArrayList<String> b = new ArrayList<String>();

    a.add("a");
    a.add("b");
    a.add("c");

    b.add("d");
    b.add("e");
    b.add("r");

    HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

    hm.put("Tomek", a);
    hm.put("KOT", b);

    for (Entry<String, ArrayList<String> m : hm.entrySet()) {

        // code to type....
    }

}
</code>```

答:
You can use the below code to print all the elements in the lists :

```<code>hm.forEach((key, arr) -> {
            arr.forEach( arrayListElement -> System.out.println(arrayListElement));
});
</code>```

We are iterating through each element in map which provides us the array list element and then iterate through the list element to get the items in the list.

Body:
Can you send the implementation how to Iterate through HashMap containing ArrayList, here is my code, I created 2 ArrayLists and added to Hashmap and I need to iterate through

public class t {

public static void main(String[] args) {

    ArrayList<String> a = new ArrayList<String>();
    ArrayList<String> b = new ArrayList<String>();

    a.add("a");
    a.add("b");
    a.add("c");

    b.add("d");
    b.add("e");
    b.add("r");

    HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

    hm.put("Tomek", a);
    hm.put("KOT", b);

    for (Entry<String, ArrayList<String> m : hm.entrySet()) {

        // code to type....
    }

}

Body:
You can use the below code to print all the elements in the lists :

hm.forEach((key, arr) -> {
            arr.forEach( arrayListElement -> System.out.println(arrayListElement));
});

We are iterating through each element in map which provides us the array list element and then iterate through the list element to get the items in the list.


问:
two slider values on same page
I'm trying to put two different sliders on the same page. If I just do the below for one slider, it works:

```<code><h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
</code>```

But if I try to do add a second slider with the coding below, the value display on the second does not work:

```<code><h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<h3><i>New</i> Strength of Belief in Negative Cognition</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief2_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}
</script>
</code>```

Here is the CSS if it matters:

```<code>.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #fff;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}
</code>```

Any ideas what I'm doing wrong? I am new to javascript, so my error is probably pretty embarrassing.

答:
Upon running it, I didn't see the problem. After adding the css, I noticed that the text did disappear. However, after selecting everything, I figured out the problem: your text was colored #fff, which is white. #000 is black. When I put that in the color attribute, it was fixed.

.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #000000;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<h3><i>New</i> Strength of Belief in Negative Cognition</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief2_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}
</script></code>```

Title: two slider values on same page

Body:
I'm trying to put two different sliders on the same page. If I just do the below for one slider, it works:

Strength of Belief

    %

    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">

But if I try to do add a second slider with the coding below, the value display on the second does not work:

Strength of Belief

    %

    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">

New Strength of Belief in Negative Cognition

    %

    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">

Here is the CSS if it matters:

.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #fff;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}

Any ideas what I'm doing wrong? I am new to javascript, so my error is probably pretty embarrassing.

Body:
Upon running it, I didn't see the problem. After adding the css, I noticed that the text did disappear. However, after selecting everything, I figured out the problem: your text was colored #fff, which is white. #000 is black. When I put that in the color attribute, it was fixed.

.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #000000;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}

<h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<h3><i>New</i> Strength of Belief in Negative Cognition</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief2_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}
</script>


问:
Button Click issue in Webdriverio tool
I'm trying to learn automation with webdriverio tool using typescript. I am able to launch the browser and hit the URL. But unable to click the button in the initial screen.

Can someone help? Details below

front code for the button is

<button rfs-button-primary="" ng-attr-id="{{vm.generateButtonId(button)}}" type="button" ng-click="vm.startIvoConfig()" ng-disabled="vm.nextButtonDisabled" class="ng-binding" id="Bereken_uw_premie">Bereken uw premie</button>
```

<p>I am writing the code as below in webdriverio tool</p>

<pre class="lang-javascript prettyprint-override"><code>browser.maximizeWindow();
const button = $('#Bereken_uw_premie');
button.waitForDisplayed();
button.click();
</code>```

But the button is not clicked. Any other solution?

答:
You can try use xpath i think that can be work:

```<code>"//button[@id='Bereken_uw_premie']" or
"//div//button[@id='Bereken_uw_premie']"
</code>```

it can be look like:

```<code>browser.maximizeWindow();
const xpathButton = "//button[@id='Bereken_uw_premie']";
$(xpathButton).waitForDisplayed();
$(xpathButton).click();
</code>```

If that dont work please check maybe you should wait after click sometimes the application responds to a click for a long time.

Title: Button Click issue in Webdriverio tool

Body:
I'm trying to learn automation with webdriverio tool using typescript. I am able to launch the browser and hit the URL. But unable to click the button in the initial screen.

Can someone help? Details below

front code for the button is

<button rfs-button-primary="" ng-attr-id="{{vm.generateButtonId(button)}}" type="button" ng-click="vm.startIvoConfig()" ng-disabled="vm.nextButtonDisabled" class="ng-binding" id="Bereken_uw_premie">Bereken uw premie</button>

I am writing the code as below in webdriverio tool

browser.maximizeWindow();
const button = $('#Bereken_uw_premie');
button.waitForDisplayed();
button.click();

But the button is not clicked. Any other solution?

Body:
You can try use xpath i think that can be work:

"//button[@id='Bereken_uw_premie']" or
"//div//button[@id='Bereken_uw_premie']"

it can be look like:

browser.maximizeWindow();
const xpathButton = "//button[@id='Bereken_uw_premie']";
$(xpathButton).waitForDisplayed();
$(xpathButton).click();

If that dont work please check maybe you should wait after click sometimes the application responds to a click for a long time.


问:
Why Retrofit doesn't send POST request to the server?
In API declaration I have this code:

```<code>@FormUrlEncoded
@POST("loginByPass/")
fun loginByPassword(@Field("login") login: String,
                    @Field("password") password: String,
                    @Field("phone") phone: String) : Observable<AuthResponse>
</code>```

Retrofit object I create this way:

```<code>class API {
    companion object {
        fun getRetrofitAPI() : IAPI {
            val interceptor = HttpLoggingInterceptor()
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

            val client = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addNetworkInterceptor(interceptor)
                .build()

            val retrofit = Retrofit.Builder()
                .baseUrl(SERVER_ADDRESS)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()

            return retrofit.create(IAPI::class.java)
        }
    }
}
</code>```

And request:

```<code>api.loginByPassword(login, password, "")
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe({
                Log.w("USER_DB", "CODE: " + it.code)
            }, {
                this.sayError(it.localizedMessage)
            }).dispose()
</code>```

And I have no response at all! In logs it seems like I haven't sent any request. Also I have seen sent packages - from emulator was sent nothing. I'm calling to server IP address by HTTP.
Could you give me piece of advice, what's the problem?

答: According to @DrawnRaccoon 's answer, .dispose() destroys the request, so I should use CompositeDisposable to collect all requests and dispose them in onDestroy() method. </p>

Body:
In API declaration I have this code:

@FormUrlEncoded
@POST("loginByPass/")
fun loginByPassword(@Field("login") login: String,
                    @Field("password") password: String,
                    @Field("phone") phone: String) : Observable<AuthResponse>

Retrofit object I create this way:

class API {
    companion object {
        fun getRetrofitAPI() : IAPI {
            val interceptor = HttpLoggingInterceptor()
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

            val client = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addNetworkInterceptor(interceptor)
                .build()

            val retrofit = Retrofit.Builder()
                .baseUrl(SERVER_ADDRESS)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()

            return retrofit.create(IAPI::class.java)
        }
    }
}

And request:

api.loginByPassword(login, password, "")
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe({
                Log.w("USER_DB", "CODE: " + it.code)
            }, {
                this.sayError(it.localizedMessage)
            }).dispose()

And I have no response at all! In logs it seems like I haven't sent any request. Also I have seen sent packages - from emulator was sent nothing. I'm calling to server IP address by HTTP.
Could you give me piece of advice, what's the problem?