问:
Flask Not updating data from new sql data - Nginx, Uwsgi, Centos7, Mysql
I have a web reporting tool that I've create with flask that connects to a mysql database which receives it's data from a phone system throughout the day. I had this reporting tool working perfectly fine (Updating numbers as you refreshed the screen or as you logged in.) but now ever since I've added 2 queries and changed my code slightly I'm able to still reach the site but it just doesn't update it's numbers as it used to. The numbers are correct upon restarting my uwsgi service and nginx, but the numbers don't update as time goes on and call come in until the service and nginx are restarted. I'm a noob when it comes to deployments and server maintenance. I'm not sure if I need to close my sql connection somewhere in my code and establish the connection again so we receive updated numbers?
Here is my code, I'll show the uwsgi.py, some parts of my main.py (Especially where I added my 2 queries) and also my nginx.conf ... Here you go...
This is just a bare bones of the project. I really don't think it's in my code buy I could be wrong.
Main.py

```<code>app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root@localhost:3306/asteriskcdrdb"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
engine = db.engine
connection = engine.connect()

location_to_phone = {
    "TX-Billing": "5123597546",
    "TX-Bee Cave": "5123668568",
    "TX-Central Austin": "5124543781",
    "TX-North Austin": "5128373376",
    "TX-Pflugerville": "5122523700",
    "TX-San Antonio": "2106160448",
    "TX-Steiner Ranch": "5122660007",
    "LA-Baton Rouge": "2553039500",
    "LA-Bossier City": "3187425124",
    "La-Lafayette": "3378392773",
    "La-Old Metairie": "5048362050",
    "La-Shreveport": "3186862021",
    "LA-Uptown": "5048975899"
}

location_to_center = {
    "TX-Billing": {"Front Desk": "7000", "Medical": "7001"},
    "TX-Bee Cave": {"Front Desk": "7040", "Medical": "7041"},
    "TX-Central Austin": {"Front Desk": "7050", "Medical": "7051"},
    "TX-North Austin": {"Front Desk": "6000", "Medical": "7031"},
    "Tx-Pflugerville": {"Front Desk": "7070", "Medical": "7071"},
    "Tx-San Antonio": {"Front Desk": "7060", "Medical": "7061"},
    "Tx-Steiner Ranch": {"Front Desk": "7120", "Medical": "7121"},
    "LA-Baton Rouge": {"Front Desk": "7080", "Medical": "7081"},
    "LA-Bossier City": {"Front Desk": "0", "Medical": "0"},
    "La-Lafayette": {"Front Desk": "7100", "Medical": "7101"},
    "La-Old Metairie": {"Front Desk": "0", "Medical": "0"},
    "La-Shreveport": {"Front Desk": "0", "Medical": "0"},
    "LA-Uptown": {"Front Desk": "0", "Medical": "0"}
}

def reports():
    if current_user.is_authenticated:
        print("Authenticated")
    else:
        return redirect(url_for('login'))

    form = ReportConfig(prefix='a')
    form2 = Details(prefix='b')
    form3 = ReportConfig2(prefix='c')

    start_date = datetime.today().strftime('%Y-%m-%d')
    end_date = datetime.now().strftime("%Y-%m-%d")

    totals = []
    answered = []
    no_answer = []
    average = []
    client_num = []
    medicals = []
    fronts = []

    calls = 0
    notan = 0
    ans = 0

    for (loc, num), (site, data) in zip(location_to_phone.items(),location_to_center.items()):
        md = data['Medical']
        fd = data['Front Desk']
        test = num

        totalcalls = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        answered_count = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' AND disposition='ANSWERED' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        no = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' AND disposition='NO ANSWER' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        av = connection.execute(f"SELECT duration from cdr WHERE did='{test}' AND NOT lastapp='background' AND calldate between '{start_date} 08:00:00' AND '{end_date} 23:59:59'")
        medical = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and dst='{md}' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        front_desk = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and dst='{fd}' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        answer_num = [row[0] for row in answered_count]

        nono = [row[0] for row in no]

        total = [row[0] for row in totalcalls]

        med = [row[0] for row in medical]
        front = [row[0] for row in front_desk]

        sum = 0
        count = total[0]

        calls = calls + total[0]
        notan = notan + nono[0]
        ans = ans + answer_num[0]
        for x in av:
            sum = sum + x[0]

        try:
            avg = (sum/count)
        except:
            avg = 0
        # avg = (sum/count)
        average.append(round(avg, 2))
        totals.append(total[0])
        answered.append(answer_num[0])
        no_answer.append(nono[0])
        client_num.append(test)
        medicals.append(med[0])
        fronts.append(front[0])

return render_template('reports.html', start_date = start_date, month_date = start_date, assign=assign, form=form, form2=form2,  form3=form3, end_date = end_date, all_calls=calls, all_answered=ans, not_answered=notan, location=zip(totals, location_to_phone, answered, no_answer, average, client_num, medicals, fronts))
</code>```

wsgi.py

```<code>from main import app as application

if __name__ == '__main__':
    application.run()
</code>```

itinapinch_rep.ini

```<code>[uwsgi]
module = wsgi

master = true
processes = 5

socket = itinapinch_rep.sock
chmod-socket = 660
vacuum = true

die-on-term = true
</code>```

itinapinch_rep.service

```<code>[Unit]
Description=uWSGI instance to serve itinapinch_rep
After=network.target

[Service]
User=reports
Group=nginx
WorkingDirectory=/home/reports/itinapinch_rep
Environment="PATH=/home/reports/itinapinch_rep/it_venv/bin"
ExecStart=/home/reports/itinapinch_rep/it_venv/bin/uwsgi --ini itinapinch_rep.ini

[Install]
WantedBy=multi-user.target
</code>```

答:
According to the docs for sqlalchemy.engine.Connection:

The Connection object represents a single dbapi connection checked out from the connection pool. In this state, the connection pool has no affect upon the connection, including its expiration or timeout state. For the connection pool to properly manage connections, connections should be returned to the connection pool (i.e. connection.close()) whenever the connection is not in use_.

So rather than being created as a global at import time, connections should be created and closed within the life-cycle of each request.

Body:
I have a web reporting tool that I've create with flask that connects to a mysql database which receives it's data from a phone system throughout the day. I had this reporting tool working perfectly fine (Updating numbers as you refreshed the screen or as you logged in.) but now ever since I've added 2 queries and changed my code slightly I'm able to still reach the site but it just doesn't update it's numbers as it used to. The numbers are correct upon restarting my uwsgi service and nginx, but the numbers don't update as time goes on and call come in until the service and nginx are restarted. I'm a noob when it comes to deployments and server maintenance. I'm not sure if I need to close my sql connection somewhere in my code and establish the connection again so we receive updated numbers?
Here is my code, I'll show the uwsgi.py, some parts of my main.py (Especially where I added my 2 queries) and also my nginx.conf ... Here you go...
This is just a bare bones of the project. I really don't think it's in my code buy I could be wrong.
Main.py

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root@localhost:3306/asteriskcdrdb"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
engine = db.engine
connection = engine.connect()

location_to_phone = {
    "TX-Billing": "5123597546",
    "TX-Bee Cave": "5123668568",
    "TX-Central Austin": "5124543781",
    "TX-North Austin": "5128373376",
    "TX-Pflugerville": "5122523700",
    "TX-San Antonio": "2106160448",
    "TX-Steiner Ranch": "5122660007",
    "LA-Baton Rouge": "2553039500",
    "LA-Bossier City": "3187425124",
    "La-Lafayette": "3378392773",
    "La-Old Metairie": "5048362050",
    "La-Shreveport": "3186862021",
    "LA-Uptown": "5048975899"
}

location_to_center = {
    "TX-Billing": {"Front Desk": "7000", "Medical": "7001"},
    "TX-Bee Cave": {"Front Desk": "7040", "Medical": "7041"},
    "TX-Central Austin": {"Front Desk": "7050", "Medical": "7051"},
    "TX-North Austin": {"Front Desk": "6000", "Medical": "7031"},
    "Tx-Pflugerville": {"Front Desk": "7070", "Medical": "7071"},
    "Tx-San Antonio": {"Front Desk": "7060", "Medical": "7061"},
    "Tx-Steiner Ranch": {"Front Desk": "7120", "Medical": "7121"},
    "LA-Baton Rouge": {"Front Desk": "7080", "Medical": "7081"},
    "LA-Bossier City": {"Front Desk": "0", "Medical": "0"},
    "La-Lafayette": {"Front Desk": "7100", "Medical": "7101"},
    "La-Old Metairie": {"Front Desk": "0", "Medical": "0"},
    "La-Shreveport": {"Front Desk": "0", "Medical": "0"},
    "LA-Uptown": {"Front Desk": "0", "Medical": "0"}
}

def reports():
    if current_user.is_authenticated:
        print("Authenticated")
    else:
        return redirect(url_for('login'))

    form = ReportConfig(prefix='a')
    form2 = Details(prefix='b')
    form3 = ReportConfig2(prefix='c')

    start_date = datetime.today().strftime('%Y-%m-%d')
    end_date = datetime.now().strftime("%Y-%m-%d")

    totals = []
    answered = []
    no_answer = []
    average = []
    client_num = []
    medicals = []
    fronts = []

    calls = 0
    notan = 0
    ans = 0

    for (loc, num), (site, data) in zip(location_to_phone.items(),location_to_center.items()):
        md = data['Medical']
        fd = data['Front Desk']
        test = num

        totalcalls = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        answered_count = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' AND disposition='ANSWERED' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        no = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' AND disposition='NO ANSWER' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        av = connection.execute(f"SELECT duration from cdr WHERE did='{test}' AND NOT lastapp='background' AND calldate between '{start_date} 08:00:00' AND '{end_date} 23:59:59'")
        medical = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and dst='{md}' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        front_desk = connection.execute(f"SELECT COUNT(calldate) FROM cdr WHERE did='{test}' AND NOT lastapp='background' and dst='{fd}' and calldate between '{start_date} 08:00:00' and '{end_date} 23:59:59'")
        answer_num = [row[0] for row in answered_count]

        nono = [row[0] for row in no]

        total = [row[0] for row in totalcalls]

        med = [row[0] for row in medical]
        front = [row[0] for row in front_desk]

        sum = 0
        count = total[0]

        calls = calls + total[0]
        notan = notan + nono[0]
        ans = ans + answer_num[0]
        for x in av:
            sum = sum + x[0]

        try:
            avg = (sum/count)
        except:
            avg = 0
        # avg = (sum/count)
        average.append(round(avg, 2))
        totals.append(total[0])
        answered.append(answer_num[0])
        no_answer.append(nono[0])
        client_num.append(test)
        medicals.append(med[0])
        fronts.append(front[0])

return render_template('reports.html', start_date = start_date, month_date = start_date, assign=assign, form=form, form2=form2,  form3=form3, end_date = end_date, all_calls=calls, all_answered=ans, not_answered=notan, location=zip(totals, location_to_phone, answered, no_answer, average, client_num, medicals, fronts))

wsgi.py

from main import app as application

if __name__ == '__main__':
    application.run()

itinapinch_rep.ini

[uwsgi]
module = wsgi

master = true
processes = 5

socket = itinapinch_rep.sock
chmod-socket = 660
vacuum = true

die-on-term = true

itinapinch_rep.service

[Unit]
Description=uWSGI instance to serve itinapinch_rep
After=network.target

[Service]
User=reports
Group=nginx
WorkingDirectory=/home/reports/itinapinch_rep
Environment="PATH=/home/reports/itinapinch_rep/it_venv/bin"
ExecStart=/home/reports/itinapinch_rep/it_venv/bin/uwsgi --ini itinapinch_rep.ini

[Install]
WantedBy=multi-user.target


来源: stackexchange

问:
How to read the content of multiple json with Newtonsoft?
I'm using Newtonsoft.Json for read the content of a json file that have this structure:

```<code>{"Timestamp":"2018-01-26T21:11:07.2629540+01:00","Level":"Error","MessageTemplate":"Foo"}
{"Timestamp":"2018-01-26T21:21:18.8747758+01:00","Level":"Error","MessageTemplate":"Foo1"}
</code>```

as you can see there are two json object in my example.json file. I'm trying to read this in the following way:

first I've created the class model:

```<code> public class RootObject
 {
    public DateTime Timestamp { get; set; }
    public string Level { get; set; }
    public string MessageTemplate { get; set; }
 }
</code>```

then I save the content of the file in a string: string content = File.ReadAllText(@"example.json");

now I get an error on the next line:

```<code>var json = JsonConvert.DeserializeObject<RootObject>(content);
</code>```

in particular:

'Additional text encountered after finished reading JSON content: {. Path '', line 2, position 0.'

how can I handle this situation?

Thanks.

答:
This is possible if you use a JsonSerializer and a JsonTextReader instead of JsonConvert.

The trick is to enable JsonTextReader.SupportMultipleContent.

var objects = new List<RootObject>();

var serializer = new JsonSerializer();

using (var stringReader = new StringReader(content))
using (var jsonReader = new JsonTextReader(stringReader))
{
    jsonReader.SupportMultipleContent = true;

    while (jsonReader.Read())
    {
        var json = serializer.Deserialize<RootObject>(jsonReader);

        objects.Add(json);
    }
}
```

This is more robust than File.ReadAllLines because JsonTextReader doesn't care about whitespace or line breaks.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Newtonsoft.Json for read the content of a json file that have this structure:

{"Timestamp":"2018-01-26T21:11:07.2629540+01:00","Level":"Error","MessageTemplate":"Foo"}
{"Timestamp":"2018-01-26T21:21:18.8747758+01:00","Level":"Error","MessageTemplate":"Foo1"}

as you can see there are two json object in my example.json file. I'm trying to read this in the following way:

first I've created the class model:

 public class RootObject
 {
    public DateTime Timestamp { get; set; }
    public string Level { get; set; }
    public string MessageTemplate { get; set; }
 }

then I save the content of the file in a string: string content = File.ReadAllText(@"example.json");

now I get an error on the next line:

var json = JsonConvert.DeserializeObject<RootObject>(content);

in particular:

'Additional text encountered after finished reading JSON content: {. Path '', line 2, position 0.'

how can I handle this situation?

Thanks.

Body:
This is possible if you use a JsonSerializer and a JsonTextReader instead of JsonConvert.

The trick is to enable JsonTextReader.SupportMultipleContent.

var objects = new List<RootObject>();

var serializer = new JsonSerializer();

using (var stringReader = new StringReader(content))
using (var jsonReader = new JsonTextReader(stringReader))
{
    jsonReader.SupportMultipleContent = true;

    while (jsonReader.Read())
    {
        var json = serializer.Deserialize<RootObject>(jsonReader);

        objects.Add(json);
    }
}

This is more robust than File.ReadAllLines because JsonTextReader doesn't care about whitespace or line breaks.

ContentLicense: CC BY-SA 4.0


问:
Red-black trees, relation between black and red nodes
One of the questions from my homework was to find exact lower bound of

```<code>(#black nodes)/(#red nodes)
</code>```

in rb-tree. the bound must be not asymptotic.
Any suggestions?

Your help would be very appreciated.

答:
Assuming this is a homework:

Let's review some properties of RedBlack Trees from Wikipedia:

...

The root is black.

All leaves are black.

Both children of every red node are black.

...

To get a lower bound on #B/#R you want to construct a tree that has as many red nodes as possible. (Unfortunately, due to 2,3,4 you cannot construct an all red tree)

Some questions worth thinking about:

can you fit more red nodes in balanced or not-so-balanced trees?

does even or odd maximal height make a difference?

given that a tree contains 3, 7, ..., (2^n)-1 back nodes how many red ones can you fit in?

Body:
One of the questions from my homework was to find exact lower bound of

(#black nodes)/(#red nodes)

in rb-tree. the bound must be not asymptotic.
Any suggestions?

Your help would be very appreciated.


问:
Angular and Laravel - Display and save into database based on login and user Id
I am developing a result management application using Laravel Endpoint and Angular7 Frontend. When I save into the database, I want to save the login/user Id. Also, it will display data based on Login Id. That is, if UserId is 1 (the user is Admin) it will display all the data, but if user Id is any other number apart from 1, it will display the data based on login/user Id in the table

I have developed these table:

User: id, username, email, password

Exam: id, exam_name, user_id

Result: id, exam_id, user_id, score.

Also, I have developed Laravel Endpoint and Angular7 Frontend.

Laravel Endpoint: Controller

```<code>    public function login(Request $request)
    {
        $credentials = $request->json()->all();

        try
        {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error' => 'invalid_credentials'], 400);
            } else {
                // Generate token from user
                $token = JWTAuth::attempt($credentials);
                //return response()->json(compact('token'));
                return response()->json(                [
                    'access_token' => $token,
                    'token_type' => 'bearer'
                ]   );

            }
        }
        catch(JWTException $e)
        {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }
    }
</code>```

Exam: Laravel EndPoint

```<code>    public function index()
    {
        $exams = Exam::all();
        return response()->json($exams);
    }

    public function store(Request $request)
    {
        $request->validate([
            'exam_name' => 'required'
        ]);

        $exam = Exam::create($request->all());

        return response()->json([
            'message' => 'Great success! New Exam created',
            'exam => $exam
        ]);
    }

    public function show(Exam $exam)
    {
        return $exam;
    }
</code>```

api

```<code>Route::get('/exams', 'ExamController@index')->name('exams.index');

Route::post('/exams', 'ExamController@store')->name('exams.store');

Route::get('/exams/{exam}', 'ExamController@show')->name('exams.show');
</code>```

Angular: exam.service.ts

```<code>const apiUrl = "http://localhost/schoolbackend/public/api/exams";

  getExams (): Observable<Exam[]> {
    return this.http.get<Exam[]>(apiUrl)
      .pipe(
        tap(exams => console.log('Fetch exams')),
        catchError(this.handleError('getExams', []))
      );
  }

  addExam (exam): Observable<Exam> {
    return this.http.post<Exam>(apiUrl, exam, httpOptions).pipe(
      tap((exam: Exam) => console.log(`added exam w/ id=${exam._id}`)),
      catchError(this.handleError<Exam>('addExam'))
    );
  }
</code>```

exam-display.component.ts

```<code>  ngOnInit() {

    this.api.getExams()
      .subscribe(res => {
        this.data = res;
        console.log(this.data);
        this.isLoadingResults = false;
      }, err => {
        console.log(err);
        this.isLoadingResults = false;
      });
  }
</code>```

exam-add.component.ts

```<code>  onFormSubmit(form:NgForm) {
    this.isLoadingResults = true;
    this.api.addExam(form)
      .subscribe(res => {
         // let id = res['_id'];
          this.isLoadingResults = false;
          this.router.navigate(['/examlist']);
        }, (err) => {
          console.log(err);
          this.isLoadingResults = false;
        });
  }
</code>```

When a user logs in:

If user_id is 1, then he is an Admin and should be able to view everything in exam-display.ts, else only his exam should be seen (based on his user_id).

When a user saves into the database from exam-add.component.ts, his login/user_id should be saved into exam table

答:
Well first of all, I think you should create a separate column like is_admin(boolean) in user table. Directly finding out from id is not a good idea.

When you login with Laravel you can take the user object from
auth::user() function.

Basis on that result you can check if a user is admin or not.

If it is admin you can fetch all the data, otherwise fetch with user_id.

Similarly, when storing in exam table you can again get the user from auth.

Example:

```<code>// exam controller

// for fetching exams
public function index()
{
    $userId = auth()->id();

    if ($userId == 1) {
       $exams = Exam::all();
    } else {
       $exams = Exam::where('user_id', $userId)->get();
    }

    return response()->json($exams);
}

// for creating new exam
public function store(Request $request)
{
    $request->validate([
        'exam_name' => 'required'
    ]);

    $exam = new Exam;
    $exam->exam_name = $request->exam_name;
    $exam->user_id = auth()->id()
    $exam->save();

    return response()->json([
        'message' => 'Great success! New Exam created',
        'exam => $exam
    ]);
}
</code>```

Body:
I am developing a result management application using Laravel Endpoint and Angular7 Frontend. When I save into the database, I want to save the login/user Id. Also, it will display data based on Login Id. That is, if UserId is 1 (the user is Admin) it will display all the data, but if user Id is any other number apart from 1, it will display the data based on login/user Id in the table

I have developed these table:

User: id, username, email, password

Exam: id, exam_name, user_id

Result: id, exam_id, user_id, score.

Also, I have developed Laravel Endpoint and Angular7 Frontend.

Laravel Endpoint: Controller

    public function login(Request $request)
    {
        $credentials = $request->json()->all();

        try
        {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error' => 'invalid_credentials'], 400);
            } else {
                // Generate token from user
                $token = JWTAuth::attempt($credentials);
                //return response()->json(compact('token'));
                return response()->json(                [
                    'access_token' => $token,
                    'token_type' => 'bearer'
                ]   );

            }
        }
        catch(JWTException $e)
        {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }
    }

Exam: Laravel EndPoint

    public function index()
    {
        $exams = Exam::all();
        return response()->json($exams);
    }

    public function store(Request $request)
    {
        $request->validate([
            'exam_name' => 'required'
        ]);

        $exam = Exam::create($request->all());

        return response()->json([
            'message' => 'Great success! New Exam created',
            'exam => $exam
        ]);
    }

    public function show(Exam $exam)
    {
        return $exam;
    }

api

Route::get('/exams', 'ExamController@index')->name('exams.index');

Route::post('/exams', 'ExamController@store')->name('exams.store');

Route::get('/exams/{exam}', 'ExamController@show')->name('exams.show');

Angular: exam.service.ts

const apiUrl = "http://localhost/schoolbackend/public/api/exams";

  getExams (): Observable<Exam[]> {
    return this.http.get<Exam[]>(apiUrl)
      .pipe(
        tap(exams => console.log('Fetch exams')),
        catchError(this.handleError('getExams', []))
      );
  }

  addExam (exam): Observable<Exam> {
    return this.http.post<Exam>(apiUrl, exam, httpOptions).pipe(
      tap((exam: Exam) => console.log(`added exam w/ id=${exam._id}`)),
      catchError(this.handleError<Exam>('addExam'))
    );
  }

exam-display.component.ts

  ngOnInit() {

    this.api.getExams()
      .subscribe(res => {
        this.data = res;
        console.log(this.data);
        this.isLoadingResults = false;
      }, err => {
        console.log(err);
        this.isLoadingResults = false;
      });
  }

exam-add.component.ts

  onFormSubmit(form:NgForm) {
    this.isLoadingResults = true;
    this.api.addExam(form)
      .subscribe(res => {
         // let id = res['_id'];
          this.isLoadingResults = false;
          this.router.navigate(['/examlist']);
        }, (err) => {
          console.log(err);
          this.isLoadingResults = false;
        });
  }

When a user logs in:

If user_id is 1, then he is an Admin and should be able to view everything in exam-display.ts, else only his exam should be seen (based on his user_id).

When a user saves into the database from exam-add.component.ts, his login/user_id should be saved into exam table

Body:
Well first of all, I think you should create a separate column like is_admin(boolean) in user table. Directly finding out from id is not a good idea.

When you login with Laravel you can take the user object from
auth::user() function.

Basis on that result you can check if a user is admin or not.

If it is admin you can fetch all the data, otherwise fetch with user_id.

Similarly, when storing in exam table you can again get the user from auth.

Example:

// exam controller

// for fetching exams
public function index()
{
    $userId = auth()->id();

    if ($userId == 1) {
       $exams = Exam::all();
    } else {
       $exams = Exam::where('user_id', $userId)->get();
    }

    return response()->json($exams);
}

// for creating new exam
public function store(Request $request)
{
    $request->validate([
        'exam_name' => 'required'
    ]);

    $exam = new Exam;
    $exam->exam_name = $request->exam_name;
    $exam->user_id = auth()->id()
    $exam->save();

    return response()->json([
        'message' => 'Great success! New Exam created',
        'exam => $exam
    ]);
}


问:
How to make orbit of a planet by using python
I have already written the code for the general equation of orbit for 'r'(Radius) value, and trying to plot graph for x=r*cos(theta) and  y=r*sin(theta) but my code giving me the same value of 'x' for different value of 'r'.So i'm endingenter code here up with a straight line instead of an ellipse.

```<code>from numpy import *
import matplotlib.pyplot as plt
import pprint

L = 9.11*10**38     #L = angular momentum
m = 3.28*10**23     #m = mass of mercury
M = 1.99*10**30     #M = mass of sun
a = 5.8*10**7       #a = semi-major axis
G = 6.674*10**-11   #G = Gravitationl constant
k = G*M*m
E = -k/(2*a)        #E = energy
p = L**2/(m*k)
c = 1 + (2*E*L**2)/m*k**2
e = sqrt(-c)        #e = eccentricity

def fx(x):
    r = p/(1 + e*cos(x))
    return r

n = 1000
phi =linspace(0,2*pi,n)
radius = zeros([n])
theta = zeros([n])
x = zeros([n])
y = zeros([n])

for i in range(0,n):
    radius[i] = fx(phi[i])
    theta[i] = 180*phi[i]/pi

for i in range(0,n):
    x[i] = radius[i]*cos(phi[i])

for i in range(0,n):
    y[i] = radius[i]*sin(phi[i])

print('r =',radius)
print('x =',x)
print('y =',y)
plt.plot(x,y)
plt.show()
</code>```

Here is a screenshot of my maths book:

答:
There are (at least) two problems with your code:

1) a = 5.8*10**7 should be a = 5.8*10**10 since (given your G) you need that distance in meters rather then kilometers.

2) As pointed out by @JohnO, you need 1 + (2*E*L**2)/(m*k**2) rather than 1 + (2*E*L**2)/m*k**2

If you make these two changes, you get a reasonable ellipse:

Body:
I have already written the code for the general equation of orbit for 'r'(Radius) value, and trying to plot graph for x=r*cos(theta) and  y=r*sin(theta) but my code giving me the same value of 'x' for different value of 'r'.So i'm endingenter code here up with a straight line instead of an ellipse.

from numpy import *
import matplotlib.pyplot as plt
import pprint

L = 9.11*10**38     #L = angular momentum
m = 3.28*10**23     #m = mass of mercury
M = 1.99*10**30     #M = mass of sun
a = 5.8*10**7       #a = semi-major axis
G = 6.674*10**-11   #G = Gravitationl constant
k = G*M*m
E = -k/(2*a)        #E = energy
p = L**2/(m*k)
c = 1 + (2*E*L**2)/m*k**2
e = sqrt(-c)        #e = eccentricity

def fx(x):
    r = p/(1 + e*cos(x))
    return r

n = 1000
phi =linspace(0,2*pi,n)
radius = zeros([n])
theta = zeros([n])
x = zeros([n])
y = zeros([n])

for i in range(0,n):
    radius[i] = fx(phi[i])
    theta[i] = 180*phi[i]/pi

for i in range(0,n):
    x[i] = radius[i]*cos(phi[i])

for i in range(0,n):
    y[i] = radius[i]*sin(phi[i])

print('r =',radius)
print('x =',x)
print('y =',y)
plt.plot(x,y)
plt.show()

Here is a screenshot of my maths book:


问:
Only show SQL results from users with exact three entries
```<code>SELECT *
FROM PlanData
WHERE GeneralEventCode = 'VM'
  AND AirlineCode = 'LH'
  AND DateStart > '2019-05-01'
  AND UserHomeBaseAirportCode = 'FRA'
</code>```

In this table I have also the field UserId. I would like to get only results, if a UserId has exact 3 entries in that table.

Thanks for the help

答:
You need 1 more condition in the WHERE clause, to select only UserIds with 3 entries:

```<code>SELECT * FROM PlanData
where
  GeneralEventCode='VM'
  and AirlineCode='LH'
  and DateStart>'2019-05-01'
  and UserHomeBaseAirportCode='FRA'
  and UserId IN (
    SELECT UserId
    FROM PlanData
    GROUP BY UserId
    HAVING Count(*) = 3
  )
</code>```

Body:
SELECT *
FROM PlanData
WHERE GeneralEventCode = 'VM'
  AND AirlineCode = 'LH'
  AND DateStart > '2019-05-01'
  AND UserHomeBaseAirportCode = 'FRA'

In this table I have also the field UserId. I would like to get only results, if a UserId has exact 3 entries in that table.

Thanks for the help

Body:
You need 1 more condition in the WHERE clause, to select only UserIds with 3 entries:

SELECT * FROM PlanData
where
  GeneralEventCode='VM'
  and AirlineCode='LH'
  and DateStart>'2019-05-01'
  and UserHomeBaseAirportCode='FRA'
  and UserId IN (
    SELECT UserId
    FROM PlanData
    GROUP BY UserId
    HAVING Count(*) = 3
  )


问:
How to link 3rd party libraries into Qt project that is targetted for WebAssembly (Wasm)
I have a large C++/Qt project that uses CMake to build, which is not supported by Qt when targetting into Wasm https://wiki.qt.io/Qt_for_WebAssembly (only qmake is supported now).

This project is depending on multiple 3rd party libraries, most notably yaml-cpp, which also uses cmake.

I can create a Qt project file for this, instead of using CMake, but it will cover only my application and not 3rd party libraries using CMake. If I was targetting some more common platform, like Linux or Windows, I suppose I could just compile the 3rd party libraries as dynamic libraries (.so or .dll) and then link my application to them, but I have no idea how to do this in Wasm world.

Is there a way to link or embed a 3rd library into output Wasm binary? I suppose I would have to compile yaml-cpp into Wasm itself and then link these 2 Wasm objects together in some way?

Did anyone ever succeeded in this? Is it even possible yet?

答: My understanding is you would have to compile those third party libraries for wasm too.  Browsers can safely execute wasm in a nice safe sandbox, but allowing execution of arbitrary code in DLLs would completely break that security.</p>


问:
Can't open input file Poco.obj or Find PocoFoundationd.lib
I am trying to install an external library for C++19 in my Microsoft visual studio called 'Poco', which is used for communication. Do I have to build it or something? what the build of the library is for anyway???

This is my first time I build an external libarry, so I have no idea how to do it. I opened the Pocoproject website, and followed all the steps one by one, I opened the Visual Studio cmd and built Poco through it : "buildwin.cmd 142".
These are the steps that I followed : https://pocoproject.org/docs/00200-GettingStarted.html#8

After I finished building it, and linked this file to my visual studio include list correctly : "poco-develop\Foundation\include\Poco". I tried to include a file :
#include <Poco/Types.h>.
It said this : cannot open input file '...\include\Poco.obj', it mentioned a file that even does not exist in my computer or the library.

However, I tried another linking way in my Visual Studio : Configuration Properties - V/C++ Directories - Include Directory, I added the path there, and I got a difference error : Cannot find 'PocoFoundationd.lib'

Probably, the problem is obtained from Visual Studio.

答:
The problem is from Visual Studio, It does not even need 'PocoLibraryd.lib'.
If we really need it or actually might use it, then 'PocoLibraryd.lib' should be contained with the github zipped file for poco library.
However, all I had to do is : go to Configuration properties -> Linker -> Input -> Ignore Specific Default Libraries, and add to it "PocoFoundationd.lib".


问:
Periodically Querying Postgresql and Visualize it On Dashboard
Here is the case, i want to visualize a query result of data taken periodically into dashboard (like grafana or kibana), the problem is I don't know which technology stack to use, should I use ELK stack, Prometheus + Grafana, or using Tableau, the requirements are:

First, it has support for multiple (hundreds) of database server as data source, currently I use Postgresql.

Second, it has support for running one query to all database instance and collect the result into one centralized server to be then displayed on dashboard.

Third, it has support for period/schedule set up (cron-like scheduler) for managing how often data should be queried from all database servers.

Fourth, it has support for alerting/notification system, where i can use existing platform library without much code needed.

Fifth, it has to be opensource project, with good reputation and quite large community support.

Thanks

答:
You can achieve your objective with ELK Stack. In Kibana, you will see basic Dashboard. If you want more detail Dashboard view, then you can integrate Elastic Search with Grafana as well using Lucene query.Below links will help you:
https://www.elastic.co/blog/logstash-jdbc-input-plugin

https://discuss.elastic.co/t/how-can-i-schedule-logstash-every-second-for-jdbc-input-plugin/27393/11

https://grafana.com/blog/2016/03/09/how-to-effectively-use-the-elasticsearch-data-source-in-grafana-and-solutions-to-common-pitfalls/#lucene


问:
std::set deduction guide doesn't work as expected
Shouldn't the two set types be identical?

#include <array>
#include <set>
#include <iostream>

template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;

int main() {

    std::array a {1,2,3,4};
    std::set<int> si {a.begin(), a.end()};
    std::set       s {a.begin(), a.end()};

    for(auto& i: si) { std::cout << i << "\n"; }
    for(auto& i: s ) { std::cout << i << "\n"; }

}
```

<p>instead it yields:</p>

```1
2
3
4
0x7ffdf5bc9050
0x7ffdf5bc9060
```

even tried with additional Allocator :-(

答:
There are two points of confusion here.

First, deduction guides must be in the scope of the class template that they're guiding, so this guide will just never be considered:

```<code>template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;
</code>```

It would have to look like this:

namespace std {
    template <class Iter>
    set(Iter, Iter) -> set<typename iterator_traits<Iter>::value_type>;
}
```

<p>But you're not allowed to add things into <code>namespace std</code>, so don't do that. And besides, this deduction guide already exists for <code>set</code>:</p>

```template<class InputIt,
         class Comp = std::less<typename std::iterator_traits<InputIt>::value_type>,
         class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
set(InputIt, InputIt, Comp = Comp(), Alloc = Alloc())
  -> set<typename std::iterator_traits<InputIt>::value_type, Comp, Alloc>;
```

<p>So there's no reason to add your version anyway.</p>

<hr />

<p>The reason <em>that</em> deduction guide isn't used, nor would yours be if you put it in the right namespace, is the usual major caveat for list-initialization:</p>

<p>If there is a matching <code>initializer_list<T></code> constructor, it is <em>strongly preferred</em> to anything else.</p>

<p>The specific language rule is that we do overload resolution specifically for those constructors first, and then we do the rest. And one of the other deduction guides in our list is:</p>

```template<class Key, class Comp = std::less<Key>, class Alloc = std::allocator<Key>>
set(std::initializer_list<Key>, Comp = Comp(), Alloc = Alloc())
  -> set<Key, Comp, Alloc>;
```

<p>Note that:</p>

```std::set s{a.begin(), a.end()};
```

<p>is the exact same <em>kind</em> of construction as:</p>

```std::set u{1, 2};
```

<p>Just because our two elements of the same type are iterators, doesn't mean they get treated any differently from any other two elements of the same type. So we get a set of iterators.</p>

<p>If you want to use the other deduction guide with the other constructor, you <em>must</em> use parentheses:</p>

```std::set s(a.begin(), a.end());
```

And remove your deduction guide!

Body:
Shouldn't the two set types be identical?

#include <array>
#include <set>
#include <iostream>

template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;

int main() {

    std::array a {1,2,3,4};
    std::set<int> si {a.begin(), a.end()};
    std::set       s {a.begin(), a.end()};

    for(auto& i: si) { std::cout << i << "\n"; }
    for(auto& i: s ) { std::cout << i << "\n"; }

}

instead it yields:

1
2
3
4
0x7ffdf5bc9050
0x7ffdf5bc9060

even tried with additional Allocator :-(

Body:
There are two points of confusion here.

First, deduction guides must be in the scope of the class template that they're guiding, so this guide will just never be considered:

template <class Iter>
std::set(Iter, Iter) -> std::set<typename std::iterator_traits<Iter>::value_type>;

It would have to look like this:

namespace std {
    template <class Iter>
    set(Iter, Iter) -> set<typename iterator_traits<Iter>::value_type>;
}

But you're not allowed to add things into namespace std, so don't do that. And besides, this deduction guide already exists for set:

template<class InputIt,
         class Comp = std::less<typename std::iterator_traits<InputIt>::value_type>,
         class Alloc = std::allocator<typename std::iterator_traits<InputIt>::value_type>>
set(InputIt, InputIt, Comp = Comp(), Alloc = Alloc())
  -> set<typename std::iterator_traits<InputIt>::value_type, Comp, Alloc>;

So there's no reason to add your version anyway.

The reason that deduction guide isn't used, nor would yours be if you put it in the right namespace, is the usual major caveat for list-initialization:

If there is a matching initializer_list<T> constructor, it is strongly preferred to anything else.

The specific language rule is that we do overload resolution specifically for those constructors first, and then we do the rest. And one of the other deduction guides in our list is:

template<class Key, class Comp = std::less<Key>, class Alloc = std::allocator<Key>>
set(std::initializer_list<Key>, Comp = Comp(), Alloc = Alloc())
  -> set<Key, Comp, Alloc>;

Note that:

std::set s{a.begin(), a.end()};

is the exact same kind of construction as:

std::set u{1, 2};

Just because our two elements of the same type are iterators, doesn't mean they get treated any differently from any other two elements of the same type. So we get a set of iterators.

If you want to use the other deduction guide with the other constructor, you must use parentheses:

std::set s(a.begin(), a.end());

And remove your deduction guide!


问:
Use express-ntlm authentication to auth to TFS api
Using express and express-ntlm, how can I create an http://localhost:3000/api/bug/ endpoint that creates a bug for me in TFS by hitting the TFS api?

I can do this using request-ntlm-promise right now and this is how I do it.

```<code>const ntlm = require('request-ntlm-promise');

const ntlmOptions = {
  username: 'myUserName',
  password: 'myPassword',
  url: 'http://tfsinstance/collection/project/_apis/wit/workitems/$bug?api-version=4.1',
  headers: {
    'Content-Type': 'application/json-patch+json'
  }
};

const tfsBugObject =[{
  'op': 'add',
  'path': '/fields/System.Title',
  'value': 'Test title'
}, {
  'op': 'add',
  'path': '/fields/Microsoft.VSTS.TCM.SystemInfo',
  'value': 'Test system info'
}, {
  'op': 'add',
  'path': '/fields/Microsoft.VSTS.TCM.ReproSteps',
  'value': 'test reproduction steps'
}];

ntlm.post(ntlmOptions, tfsBugObject).then((response) => { return res.send(response); });
</code>```

The problem is that I must provide a username and password in in ntlmOptions object. Doing this doesn't create the bug in TFS as the current user hitting the express API but instead creates the bug as the user 'myUserName'.

Using the express-ntlm package, is it possible to do an http.post to http://tfsinstance/collection/project/... using the NTLM credentials returned from that package?

TFS requires authentication in order for one to use the API.

Using express-ntlm I was hoping that I could do the following.

```<code>const express = require('express');
const ntlm = require('express-ntlm');
const http = require('http');
const app = express();

app.use(ntlm({ domain: 'mydomain', domaincontroller: 'ldap://domaincontroller' });
</code>```

then

```<code>httpOptions = {
    protocol: 'http',
    hostname: 'tfsinstance',
    pathname: '/collection/project/_apis/wit/workitems/$bug?api-version=4.1',
    port: 8080,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json-patch+json'
    }
};

app.post('/report/bug', (req, res, next) => {
    const request = http.request(httpOptions, (response => {
        response.on('data', data => {
            // return response from TFS through express to user
        });
    }));
});
</code>```

答:
express-ntlm acts as a proxy between a client and a domain controller. So the domain controller will handle the authentication with the client and express-ntlm just acts as a man in the middle until the authentication was successful.

If you can use some kind of API user and use express-ntlm to just get the correct username and pass it to the TFS API that would be the easiest way to do, otherwise I would suggest you to create your own proxy between your client and the TFS API.

Body:
Using express and express-ntlm, how can I create an http://localhost:3000/api/bug/ endpoint that creates a bug for me in TFS by hitting the TFS api?

I can do this using request-ntlm-promise right now and this is how I do it.

const ntlm = require('request-ntlm-promise');

const ntlmOptions = {
  username: 'myUserName',
  password: 'myPassword',
  url: 'http://tfsinstance/collection/project/_apis/wit/workitems/$bug?api-version=4.1',
  headers: {
    'Content-Type': 'application/json-patch+json'
  }
};

const tfsBugObject =[{
  'op': 'add',
  'path': '/fields/System.Title',
  'value': 'Test title'
}, {
  'op': 'add',
  'path': '/fields/Microsoft.VSTS.TCM.SystemInfo',
  'value': 'Test system info'
}, {
  'op': 'add',
  'path': '/fields/Microsoft.VSTS.TCM.ReproSteps',
  'value': 'test reproduction steps'
}];

ntlm.post(ntlmOptions, tfsBugObject).then((response) => { return res.send(response); });

The problem is that I must provide a username and password in in ntlmOptions object. Doing this doesn't create the bug in TFS as the current user hitting the express API but instead creates the bug as the user 'myUserName'.

Using the express-ntlm package, is it possible to do an http.post to http://tfsinstance/collection/project/... using the NTLM credentials returned from that package?

TFS requires authentication in order for one to use the API.

Using express-ntlm I was hoping that I could do the following.

const express = require('express');
const ntlm = require('express-ntlm');
const http = require('http');
const app = express();

app.use(ntlm({ domain: 'mydomain', domaincontroller: 'ldap://domaincontroller' });

then

httpOptions = {
    protocol: 'http',
    hostname: 'tfsinstance',
    pathname: '/collection/project/_apis/wit/workitems/$bug?api-version=4.1',
    port: 8080,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json-patch+json'
    }
};

app.post('/report/bug', (req, res, next) => {
    const request = http.request(httpOptions, (response => {
        response.on('data', data => {
            // return response from TFS through express to user
        });
    }));
});


问:
Creating a model for use in a pipeline from a hyperparameter tuning job
I'm trying to implement the best estimator from a hyperparameter tuning job into a pipeline object to deploy an endpoint.

I've read the docs in a best effort to include the results from the tuning job in the pipeline, but I'm having trouble creating the Model() class object.

```<code># This is the hyperparameter tuning job
tuner.fit({'train': s3_train, 'validation': s3_val},
include_cls_metadata=False)

#With a standard Model (Not from the tuner) the process was as follows:
scikit_learn_inferencee_model_name = sklearn_preprocessor.create_model()
xgb_model_name = Model(model_data=xgb_model.model_data, image=xgb_image)

model_name = 'xgb-inference-pipeline-' + timestamp_prefix
endpoint_name = 'xgb-inference-pipeline-ep-' + timestamp_prefix
sm_model = PipelineModel(
    name=model_name,
    role=role,
    models=[
        scikit_learn_inferencee_model_name,
        xgb_model_name])

sm_model.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge',
endpoint_name=endpoint_name)
</code>```

I would like to be able to cleanly instantiate a model object using my results from the tuning job and pass it into the PipelineModel object. Any guidance is appreciated.

答:
I think you are on the right track. Do you get any error? Refer this notebook  for instantiating the model from the tuner and use in inference pipeline.

Editing previous response based on the comment. To create model from the best training job of the hyperparameter tuning job, you can use below snippet

from sagemaker.tuner import HyperparameterTuner
from sagemaker.estimator import Estimator
from sagemaker.model import Model

# Attach to an existing hyperparameter tuning job.
xgb_tuning_job_name = 'my_xgb_hpo_tuning_job_name'
xgb_tuner = HyperparameterTuner.attach(xgb_tuning_job_name)

# Get the best XGBoost training job name from the HPO job
xgb_best_training_job = xgb_tuner.best_training_job()
print(xgb_best_training_job)

# Attach estimator to the best training job name
xgb_best_estimator = Estimator.attach(xgb_best_training_job)

# Create model to be passed to the inference pipeline
xgb_model = Model(model_data=xgb_best_estimator.model_data,
                  role=sagemaker.get_execution_role(),
                  image=xgb_best_estimator.image_name)
```

Body:
I'm trying to implement the best estimator from a hyperparameter tuning job into a pipeline object to deploy an endpoint.

I've read the docs in a best effort to include the results from the tuning job in the pipeline, but I'm having trouble creating the Model() class object.

# This is the hyperparameter tuning job
tuner.fit({'train': s3_train, 'validation': s3_val},
include_cls_metadata=False)

#With a standard Model (Not from the tuner) the process was as follows:
scikit_learn_inferencee_model_name = sklearn_preprocessor.create_model()
xgb_model_name = Model(model_data=xgb_model.model_data, image=xgb_image)

model_name = 'xgb-inference-pipeline-' + timestamp_prefix
endpoint_name = 'xgb-inference-pipeline-ep-' + timestamp_prefix
sm_model = PipelineModel(
    name=model_name,
    role=role,
    models=[
        scikit_learn_inferencee_model_name,
        xgb_model_name])

sm_model.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge',
endpoint_name=endpoint_name)

I would like to be able to cleanly instantiate a model object using my results from the tuning job and pass it into the PipelineModel object. Any guidance is appreciated.


问:
Angular - Display table list based on a list
I'm new to Angular and trying to display multiple tables based on a list of values. For each rule refNo there has to be a separate rule conditions table displayed one after the other. At the moment all the tables are displaying the same values.

RuleComponent.html

```<code>  <div  *ngFor="let x of automation_rules_list">

    <table class="table">
      <thead>
        <tr>
          <th>Ticket Field</th>
          <th>Operator</th>
          <th>Expected Value</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr  *ngFor="let o of automation_rules_conditions_list">
          <td>{{o.ticketField}}</td>
          <td>{{o.ticketField}}</td>
          <td>{{o.operator}}</td>
          <td>{{o.expectedValue}}</td>
          <td><span class="pointer text-danger"><i class="fas fa-trash-alt"></i></span></td>
        </tr>
      </tbody>

    </table>
</code>```

RuleComponent.ts

```<code>ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    this.automation_rules_conditions_list = res;

  });

}
</code>```

答:
You must add the new data to automation_rules_conditions_list instead of overwriting

If my answer is what you want, I have some suggestions for Rxjs

RuleComponent.ts

```<code>ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

   // reset automation_rules_conditions_list
   this.automation_rules_conditions_list = [];

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    // add the new data to automation_rules_conditions_list
    this.automation_rules_conditions_list.push(res);

  });

}
</code>```

Body:
I'm new to Angular and trying to display multiple tables based on a list of values. For each rule refNo there has to be a separate rule conditions table displayed one after the other. At the moment all the tables are displaying the same values.

RuleComponent.html

          Ticket Field
          Operator
          Expected Value
          Action

          {{o.ticketField}}
          {{o.ticketField}}
          {{o.operator}}
          {{o.expectedValue}}

RuleComponent.ts

ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    this.automation_rules_conditions_list = res;

  });

}

Body:
You must add the new data to automation_rules_conditions_list instead of overwriting

If my answer is what you want, I have some suggestions for Rxjs

RuleComponent.ts

ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

   // reset automation_rules_conditions_list
   this.automation_rules_conditions_list = [];

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    // add the new data to automation_rules_conditions_list
    this.automation_rules_conditions_list.push(res);

  });

}


问:
find number by given factorial number
I need to find number by given factorial number. I know how to find factorial of a number .But stuck to find number of given factorial..</p>

```<code>class Fact{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  int yo = number(number);
  System.out.println(fact + " " + yo );

 }

  public static int number(int no){
      for(int i = 1 ; i >= no ; i--){
          no = no / i;
      }
      return no;
  }
}
</code>```

答:
As I understand your goal correctly, here the code you are looking for:

```<code>class Fact {

    public static void main(String args[]) {
        int n = 5;

        int fact = factorial(n);
        int number = number(fact);

        System.out.println(n + " "+fact + " " + number);
    }

    public static int factorial(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }
        return fact;
    }

    public static int number(int factorial) {
        int i = 0;
        do {
            i++;
            factorial = factorial / i;
        } while (factorial > 1);
        return i;
    }
}
</code>```

output:

```<code>5 120 5
</code>```

P.S. function number doesn't work correctly for argument n! = 1 bc this fuction has two possible results - 0, 1 (see the table of results here https://en.wikipedia.org/wiki/Factorial ) and for n >= 14 due to integer overflow. number returns correct number only for factorial passed.

Title: find number by given factorial number

Body:
I need to find number by given factorial number. I know how to find factorial of a number .But stuck to find number of given factorial..

class Fact{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  int yo = number(number);
  System.out.println(fact + " " + yo );

 }

  public static int number(int no){
      for(int i = 1 ; i >= no ; i--){
          no = no / i;
      }
      return no;
  }
}

Body:
As I understand your goal correctly, here the code you are looking for:

class Fact {

    public static void main(String args[]) {
        int n = 5;

        int fact = factorial(n);
        int number = number(fact);

        System.out.println(n + " "+fact + " " + number);
    }

    public static int factorial(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }
        return fact;
    }

    public static int number(int factorial) {
        int i = 0;
        do {
            i++;
            factorial = factorial / i;
        } while (factorial > 1);
        return i;
    }
}

output:

5 120 5

P.S. function number doesn't work correctly for argument n! = 1 bc this fuction has two possible results - 0, 1 (see the table of results here https://en.wikipedia.org/wiki/Factorial ) and for n >= 14 due to integer overflow. number returns correct number only for factorial passed.


问:
How we run a .NET 32-bit application in a 64-bit Windows server?
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

```<code>System.BadImageFormatException: is not a valid Win32 application.
</code>```

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

答:
One possibility is that the application depends on an unmanaged DLL that needs to be run in 32-bit mode.  Since the default "AnyCPU" .NET build checks the platform automatically the .NET part of the program is starting in 64-bit mode.  This will cause the calls to the 32-bit-only unmanaged DLL to fail.

To fix it, you need to create a manifest file to tell the app to run in 32-bit mode.  I've never needed to do that myself, so I can't provide instructions and a quick Google search hasn't (yet) turned up anything.

[Update]

See if this link helps:

http://msdn.microsoft.com/en-us/library/aa374191.aspx

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

Body:
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

System.BadImageFormatException: is not a valid Win32 application.

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Joel Coehoorn


问:
eclipselink does not generate tables from annotated JPA classes
My IDE is eclipse -Helios and I am using mojarra jsf, mysql, eclipselink for jpa.

In my project, if I create the tables manually in mysql, I can see those tables in the "JPA Details" view. And if I don't create any table, the eclipse IDE shows an error, "Table "trainingsession" cannot be resolved".

I am not sure what's wrong. When would JPA create these tables ? and how ?
my persistence.xml is as follows,

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="wompower2" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>trainer</jta-data-source>
    <class>com.jsfcompref.trainer.entity.User</class>
    <class>com.jsfcompref.trainer.entity.TrainingSession</class>
    <class>com.jsfcompref.trainer.entity.Event</class>
    <class>com.jsfcompref.trainer.entity.AbstractEntity</class>
    <validation-mode>NONE</validation-mode>
    <properties>
      <property name="eclipselink.target-database" value="MySQL"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
      <property name="eclipselink.ddl-generation.output-mode" value="both"/>
      <property name="eclipselink.application-location" value="C:\wompower2\DDL"/>
      <property name="eclipselink.create-ddl-jdbc-file-name" value="create.sql"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/demo"></property>
      <property name="javax.persistence.jdbc.user" value="user"></property>
      <property name="javax.persistence.jdbc.password" value="pwd"></property>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>
  </persistence-unit>
</persistence>
</code>```

Thank you,
Arindam.

答:
Just a persistence.xml example using eclipselink and mysql for others looking for a working solution:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="java2curs"  transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>db.YourClasses</class>
  <properties>
    <property name="javax.persistence.jdbc.url"
          value="jdbc:mysql://localhost:3306/dbname"/>
    <property name="javax.persistence.jdbc.user" value="dbuser"/>
    <property name="javax.persistence.jdbc.password" value="dbpassword"/>
    <property name="eclipselink.ddl-generation" value="create-tables" />
    <property name="eclipselink.ddl-generation.output-mode" value="database" />
    <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
   </properties>
 </persistence-unit>

</persistence>
</code>```

Body:
My IDE is eclipse -Helios and I am using mojarra jsf, mysql, eclipselink for jpa.

In my project, if I create the tables manually in mysql, I can see those tables in the "JPA Details" view. And if I don't create any table, the eclipse IDE shows an error, "Table "trainingsession" cannot be resolved".

I am not sure what's wrong. When would JPA create these tables ? and how ?
my persistence.xml is as follows,

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="wompower2" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>trainer</jta-data-source>
    <class>com.jsfcompref.trainer.entity.User</class>
    <class>com.jsfcompref.trainer.entity.TrainingSession</class>
    <class>com.jsfcompref.trainer.entity.Event</class>
    <class>com.jsfcompref.trainer.entity.AbstractEntity</class>
    <validation-mode>NONE</validation-mode>
    <properties>
      <property name="eclipselink.target-database" value="MySQL"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
      <property name="eclipselink.ddl-generation.output-mode" value="both"/>
      <property name="eclipselink.application-location" value="C:\wompower2\DDL"/>
      <property name="eclipselink.create-ddl-jdbc-file-name" value="create.sql"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/demo"></property>
      <property name="javax.persistence.jdbc.user" value="user"></property>
      <property name="javax.persistence.jdbc.password" value="pwd"></property>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"></property>
    </properties>
  </persistence-unit>
</persistence>

Thank you,
Arindam.

Body:
Just a persistence.xml example using eclipselink and mysql for others looking for a working solution:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="java2curs"  transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>db.YourClasses</class>
  <properties>
    <property name="javax.persistence.jdbc.url"
          value="jdbc:mysql://localhost:3306/dbname"/>
    <property name="javax.persistence.jdbc.user" value="dbuser"/>
    <property name="javax.persistence.jdbc.password" value="dbpassword"/>
    <property name="eclipselink.ddl-generation" value="create-tables" />
    <property name="eclipselink.ddl-generation.output-mode" value="database" />
    <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
   </properties>
 </persistence-unit>

</persistence>


问:
java.io.FileNotFoundException in Opencsv
I want read a CSV file. I tried Reading CSV File In Android App

```<code>public float modelPredict(String StationNM, int day, int hour, int minute) {
        int[] model = new int[0];
        try {
            File csvfile = new File(Environment.getExternalStorageDirectory() + "/"+StationNM+".csv");
            CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));
//            CSVReader reader = new CSVReader(new FileReader(StationNM+".csv"));
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println(nextLine[0] + nextLine[1] + "etc...");
            }
            model = new int[nextLine.length];
            for (int i=0; i<nextLine.length; i++) {
                model[i] = Integer.parseInt(nextLine[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //Toast.makeText(this, "The specified file was not found", T oast.LENGTH_SHORT).show();
        }
</code>```

But I get an exception:

```<code>/System.err: java.io.FileNotFoundException: csvfile.getAbsolutePath() (No such file or directory)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:231)
        at java.io.FileInputStream.<init>(FileInputStream.java:165)
</code>```

How can I solve it?

I don't know what is input in "csvfile.getAbsolutePath()"

In my repository is https://github.com/Lay4U/CapstOne/tree/master/SC/MySubwayProject

答:
Replace:

```<code>CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));
</code>```

with:

```<code>CSVReader reader = new CSVReader(new FileReader(csvfile));
</code>```

Body:
I want read a CSV file. I tried Reading CSV File In Android App

public float modelPredict(String StationNM, int day, int hour, int minute) {
        int[] model = new int[0];
        try {
            File csvfile = new File(Environment.getExternalStorageDirectory() + "/"+StationNM+".csv");
            CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));
//            CSVReader reader = new CSVReader(new FileReader(StationNM+".csv"));
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println(nextLine[0] + nextLine[1] + "etc...");
            }
            model = new int[nextLine.length];
            for (int i=0; i<nextLine.length; i++) {
                model[i] = Integer.parseInt(nextLine[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //Toast.makeText(this, "The specified file was not found", T oast.LENGTH_SHORT).show();
        }

But I get an exception:

/System.err: java.io.FileNotFoundException: csvfile.getAbsolutePath() (No such file or directory)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:231)
        at java.io.FileInputStream.<init>(FileInputStream.java:165)

How can I solve it?

I don't know what is input in "csvfile.getAbsolutePath()"

In my repository is https://github.com/Lay4U/CapstOne/tree/master/SC/MySubwayProject

Body:
Replace:

CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));

with:

CSVReader reader = new CSVReader(new FileReader(csvfile));


问:
svn-externals with own svn-externals: how to recursively checkout?
So I'm using svn:externals to checkout an external repo. The external repo has its own svn-externals set up.

Now, when updating the working copy of my project, the files from the external repo are being updated, but its externals are not. Is that behavior as designed, can it be extended to also update the external dependencies?

答:
Recursive checkout are supported since Subversion1.5, as this thread illustrates.

The "Version Control with Subversion" book does mention svn checkout, svn update, svn switch, and svn export commands as able to recurse in the externals repos, but:

If an external is set for a particular revision, no amount of 'update' will change any file in it, even though the external repo has had new revisions.

the update must be always initiated from the parent repo, not directly from the sub-repo:

Be careful, though, that you don't inadvertently modify your external working copy in subtle ways that cause problems.

For example, while an externals definition might specify that the external working copy should be held at a particular revision number, if you run svn update directly on the external working copy, Subversion will oblige, and now your external working copy is out of sync with its declaration in the primary working copy.

So maybe one of those two cases applied here.

The OP Carsten reports:

It is actually working now.

I had set the externals prop on the root node of the external project (lets say project 'lib').

In my concrete project (project 'A'), the external was defined on a sub-folder of 'lib' (ie. myLocalFolder > lib/someFolder).

That seems to be the reason for subversion not recursing into lib's externals; only looked inside 'someFolder', didn't find external defs there, so it didn't checkout someFolder/externalLib.

Now, in 'lib' I changed externals definitions so that they are defined inside the folder that I refer to in 'A'; works like a charm now!


问:
Byte containing 2 signed nibbles to 2 signed integers
For some reason, I couldn't find any answer to this question on StackOverflow. If it's already been answered, kindly point me to a duplicate post. Thanks!

I have a device that delta encodes a signal and packs 2 4-bit deltas into a byte. I'm trying to decode the signal in Java by separating the upper and lower 4 bits of the byte into two separate, signed ints.

For example:

byte packedByte = (byte) 0x0FF; // should represent the value -1, -1 in twos complement

int upper = packedByte >> 4; // upper byte is easy, prints -1

/*
 * A few goes at getting the lower 4 bits:
 */
int lower = packedByte & 0x0F; // sign is not extended, prints 15
lower = (packedByte << 4) >> 4; // doesn't work for positive values
lower = (byte)((byte)(packedByte << 4) >>> 4); // works, but this feels slow
```

Any ideas?

答: Assuming, as Jim Garrison points out, your nibbles really only represent -8 up to positive 7, you can keep doing what you were doing tof the upper, and you can do the following for the lower: (packedByte & 0x0F)-2*(packedByte & 0x08). The logic here is that it leaves 0 to 7 alone (subtracts 0 from it), but if there is a 1 in the sign bit of the lower number, it subtracts 2*8 which is 16 to get the appropriate negative number.

Body:
For some reason, I couldn't find any answer to this question on StackOverflow. If it's already been answered, kindly point me to a duplicate post. Thanks!

I have a device that delta encodes a signal and packs 2 4-bit deltas into a byte. I'm trying to decode the signal in Java by separating the upper and lower 4 bits of the byte into two separate, signed ints.

For example:

byte packedByte = (byte) 0x0FF; // should represent the value -1, -1 in twos complement

int upper = packedByte >> 4; // upper byte is easy, prints -1

/*
 * A few goes at getting the lower 4 bits:
 */
int lower = packedByte & 0x0F; // sign is not extended, prints 15
lower = (packedByte << 4) >> 4; // doesn't work for positive values
lower = (byte)((byte)(packedByte << 4) >>> 4); // works, but this feels slow

Any ideas?


问:
Creating MongoDB Unique Key with C#
I am fighting to create a unique field EmailAddress. I've already seen in forums that I have to create an index, but it didn't work out for me so far. Does anyone have a code example? Do I have to create the index on every save/call, or is it enough to create it only once?

I tried this code:

```<code>DB.GetCollection<User>(Dbname)
    .EnsureIndex(new IndexKeysBuilder()
        .Ascending("EmailAddress"), IndexOptions.SetUnique(true));

DB.GetCollection<User>(Dbname).Save(user, SafeMode.True);
</code>```

My User model looks like this:

```<code>public class User
{
    [Required(ErrorMessage = "Email Required")]
    public string EmailAddress { get; set; }

    public ObjectId Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

答:
here's a working program using MongoDB.Entities (disclaimer: I'm the author)

using System;
using MongoDB.Driver;
using MongoDB.Entities;

namespace StackOverflow
{
    public class User : Entity
    {
        public string Name { get; set; }
        public string EmailAddress { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new DB("test");

            DB.Index<User>()
              .Options(o => o.Unique = true, o => o.Background = false)
              .Key(u => u.EmailAddress, Type.Ascending)
              .Create();

            var user1 = new User { Name = "First User", EmailAddress = "email@domain.com" };
            user1.Save();

            try
            {
                var user2 = new User { Name = "Second User", EmailAddress = "email@domain.com" };
                user2.Save();
            }
            catch (MongoWriteException x)
            {
                Console.WriteLine(x.Message);
                Console.ReadKey();
            }
        }
    }
}
```

trying to create a second user with the same email address results in the following exception:

A write operation resulted in an error. E11000 duplicate key error collection: test.User index: EmailAddress(Asc) dup key: { : "email@domain.com" }

Title: Creating MongoDB Unique Key with C#

Body:
I am fighting to create a unique field EmailAddress. I've already seen in forums that I have to create an index, but it didn't work out for me so far. Does anyone have a code example? Do I have to create the index on every save/call, or is it enough to create it only once?

I tried this code:

DB.GetCollection<User>(Dbname)
    .EnsureIndex(new IndexKeysBuilder()
        .Ascending("EmailAddress"), IndexOptions.SetUnique(true));

DB.GetCollection<User>(Dbname).Save(user, SafeMode.True);

My User model looks like this:

public class User
{
    [Required(ErrorMessage = "Email Required")]
    public string EmailAddress { get; set; }

    public ObjectId Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Body:
here's a working program using MongoDB.Entities (disclaimer: I'm the author)

using System;
using MongoDB.Driver;
using MongoDB.Entities;

namespace StackOverflow
{
    public class User : Entity
    {
        public string Name { get; set; }
        public string EmailAddress { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new DB("test");

            DB.Index<User>()
              .Options(o => o.Unique = true, o => o.Background = false)
              .Key(u => u.EmailAddress, Type.Ascending)
              .Create();

            var user1 = new User { Name = "First User", EmailAddress = "email@domain.com" };
            user1.Save();

            try
            {
                var user2 = new User { Name = "Second User", EmailAddress = "email@domain.com" };
                user2.Save();
            }
            catch (MongoWriteException x)
            {
                Console.WriteLine(x.Message);
                Console.ReadKey();
            }
        }
    }
}

trying to create a second user with the same email address results in the following exception:

A write operation resulted in an error. E11000 duplicate key error collection: test.User index: EmailAddress(Asc) dup key: { : "email@domain.com" }


问:
My insertion python sort is always placing the second number at the beginning
my code is working mostly fine except for a small bug where it is placing the second element at the beginning no matter the value e.g. 1,6,2,9,3,8,4,7,5,0 would become 6,0,1,2,3,4,5,7,8,9

I've tried altering the numbers in the FOR loop a bit but other than that genuinely cannot see what's wrong

```<code>def InsertionSort(array):
    for i in range(len(array)):
        for j in range(len(array)):
            if array[i] <= array[j+1]:
                new = array.pop(i)
                array.insert(j+1,new)
                break
            elif array[i] > array[j+1]:
                continue
        print (array)
</code>```

答:
The problem there is, that you switch the position of the second element with the first, but later on not compare it anymore.

Here an implementation which is close to yours, with slight changes to take care of all the entries

```<code>ar =[1,6,2,9,3,8,4,7,5,0]
def InsertionSort(array):
    for i in range(len(array)):
            val = array[i]
            while( i > 0 and array[i-1] > val):
                array[i] = array[i-1]
                i = i - 1
            array[i] = val
    print (array)

InsertionSort(ar)
</code>```

Body:
my code is working mostly fine except for a small bug where it is placing the second element at the beginning no matter the value e.g. 1,6,2,9,3,8,4,7,5,0 would become 6,0,1,2,3,4,5,7,8,9

I've tried altering the numbers in the FOR loop a bit but other than that genuinely cannot see what's wrong

def InsertionSort(array):
    for i in range(len(array)):
        for j in range(len(array)):
            if array[i] <= array[j+1]:
                new = array.pop(i)
                array.insert(j+1,new)
                break
            elif array[i] > array[j+1]:
                continue
        print (array)

Body:
The problem there is, that you switch the position of the second element with the first, but later on not compare it anymore.

Here an implementation which is close to yours, with slight changes to take care of all the entries

ar =[1,6,2,9,3,8,4,7,5,0]
def InsertionSort(array):
    for i in range(len(array)):
            val = array[i]
            while( i > 0 and array[i-1] > val):
                array[i] = array[i-1]
                i = i - 1
            array[i] = val
    print (array)

InsertionSort(ar)


问:
Spring-Data-JPA - How to delete child record in OneToMany relationship
I have a Person entity which has Set<Address> with OneToMany mapping.

```<code>@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL
)
private Set<Address> addresses = new HashSet<>();
</code>```

Address class has

```<code>@ManyToOne
@JoinColumn(name = "person_id")
private Person person;
</code>```

Now I am able to add records in the DB successfully.

How can I achieve the clearing the address hashset should result to removing the address records for the person.

For ex: In my service layer, below code does not remove the addresses in the DB.

```<code>Person p =  personRepository.findBy(1).get();
p.getAddresses().clear();
personRepository.save(p);

</code>```

What is the right way to achieve this?

答:
I had to do this to make this work.</p>

```<code>@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL,
        orphanRemoval = true
)
private Set<Address> addresses = new HashSet<>();
</code>```

Body:
I have a Person entity which has Set<Address> with OneToMany mapping.

@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL
)
private Set<Address> addresses = new HashSet<>();

Address class has

@ManyToOne
@JoinColumn(name = "person_id")
private Person person;

Now I am able to add records in the DB successfully.

How can I achieve the clearing the address hashset should result to removing the address records for the person.

For ex: In my service layer, below code does not remove the addresses in the DB.

Person p =  personRepository.findBy(1).get();
p.getAddresses().clear();
personRepository.save(p);

What is the right way to achieve this?

Body:
I had to do this to make this work.

@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL,
        orphanRemoval = true
)
private Set<Address> addresses = new HashSet<>();


问:
how to await data from meteor call?
I'm so beginner in angular1.5, My problem is The data returned from Meteor.call() doesn't display in the HTML

Here's my code:

hubs.js

```<code>class HubsController {
  data = [];

  constructor($scope, $uibModal) {
    $scope.viewModel(this);

    this.$scope = $scope;
    this.$uibModal = $uibModal;

    this.initViews();

    this.subscribe('admin.verifiedBusinesses');
    this.subscribe('admin.verifiedStars');
    this.getData();
    console.log('data', this.data);
  }

  ...

  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      return data;
    });
  }
}

angular
  .module('material-lite')
  .controller('hubsDataController', ['$scope', '$uibModal', HubsController]);
</code>```

data don't work here:

hubs.html

  ...

              {{ hubsData.name }}

```

I expect the output in html is the same as in the HubsController class returned from getData function

答:
I solved it.
I was missing the $apply() method to bind the data.

```<code>  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err); // TODO
        swal('Error', err.reason, 'error');
        return;
      }
      // Initialize active routes.
      this.$scope.$apply(() => {
        this.$scope.data = data;
      });
    });
  }
</code>```

Title: how to await data from meteor call?

Body:
I'm so beginner in angular1.5, My problem is The data returned from Meteor.call() doesn't display in the HTML

Here's my code:

hubs.js

class HubsController {
  data = [];

  constructor($scope, $uibModal) {
    $scope.viewModel(this);

    this.$scope = $scope;
    this.$uibModal = $uibModal;

    this.initViews();

    this.subscribe('admin.verifiedBusinesses');
    this.subscribe('admin.verifiedStars');
    this.getData();
    console.log('data', this.data);
  }

  ...

  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      return data;
    });
  }
}

angular
  .module('material-lite')
  .controller('hubsDataController', ['$scope', '$uibModal', HubsController]);

data don't work here:

hubs.html

  ...

              {{ hubsData.name }}

I expect the output in html is the same as in the HubsController class returned from getData function

Body:
I solved it.
I was missing the $apply() method to bind the data.

  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err); // TODO
        swal('Error', err.reason, 'error');
        return;
      }
      // Initialize active routes.
      this.$scope.$apply(() => {
        this.$scope.data = data;
      });
    });
  }


问:
Why can't the session be unset and destroyed?
I have an almost working registration system on my website, the only part missing is the logout function. It starts the session but doesn't seem to destroy it, therefore, the previous session is always active. Am I destroying the session correctly or am I doing something entirely wrong?

At first, I just tried setting the user data and then unsetting them one by one before destroying the session, that didn't work. So now I set the user data with plain strings before destroying them, again, doesn't seem to work.

the logout link looks like this:

```<code><a href="http://localhost/dir/dir1/dir2/index.php/Controller/logout">logout</a>
</code>```

In my controller I have this:

```<code>public function logout() {

    $this->load->helper('url');
    $this->load->library('session');

    $session_data = array(
      'data' =>  'data',
      'data' => 'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' => 'data',
      'data' => 'data',
      'data' => 'data',
      'data' => 'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data'
    );
    $this->session->set_userdata($session_data);

        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');

    $this->session->sess_destroy();
    redirect('http://localhost/dir/dir1/dir2/index.php/Controller/loginview', 'refresh');
}
</code>```

I expect the session to be destroyed before it redirects(which it does), yet when I type in the new login credentials it still shows the ones from the previous session, it should instead show the new ones.

答: You might need to implement ob_start() and ob_clean() as suggested by Session is not being destroy in codeigniter. Therefore this can be a duplicate of the same thing.

Body:
I have an almost working registration system on my website, the only part missing is the logout function. It starts the session but doesn't seem to destroy it, therefore, the previous session is always active. Am I destroying the session correctly or am I doing something entirely wrong?

At first, I just tried setting the user data and then unsetting them one by one before destroying the session, that didn't work. So now I set the user data with plain strings before destroying them, again, doesn't seem to work.

the logout link looks like this:

logout

In my controller I have this:

public function logout() {

    $this->load->helper('url');
    $this->load->library('session');

    $session_data = array(
      'data' =>  'data',
      'data' => 'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' => 'data',
      'data' => 'data',
      'data' => 'data',
      'data' => 'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data',
      'data' =>  'data'
    );
    $this->session->set_userdata($session_data);

        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');
        $this->session->unset_userdata('data');

    $this->session->sess_destroy();
    redirect('http://localhost/dir/dir1/dir2/index.php/Controller/loginview', 'refresh');
}

I expect the session to be destroyed before it redirects(which it does), yet when I type in the new login credentials it still shows the ones from the previous session, it should instead show the new ones.


问:
How do i compare dates?
I have date in string type then I need to compare these 2 dates

I've tried this but it shows me strange output

```<code>string str="2019-1-12";
    string str1="2019-1-13";
    tm timeDate;
    tm timeDate1;
    strptime(str.c_str(),"%Y-%m-%d ", &timeDate);
    time_t time_input = mktime(&timeDate);
    strptime(str1.c_str(),"%Y-%m-%d ", &timeDate1);
    time_t time_input1 = mktime(&timeDate1);

    double timeDiff = difftime(time_input,time_input1);
    cout<<timeDiff;
</code>```

答:
less than,equal to,greather than another date

When your dates are strings in the format of "YYYY-mm-dd", this is a special case where the less-than operator for string gives the same result as the less-than operator would for a hypothetical date class.  This is because the date is stored in "big endian" format, each number in the date is also "big endian".

The string less-than operator compares each character one-by-one and if one is less than the other, then that is the result of the entire comparison.

The only thing you need to do is to make sure that your month and day fields are each two characters (put a zero in front if they are one character), and then compare the strings.

```<code>cout << (str < str1) << '\n';
</code>```

Ditto for equality comparison.

Title: How do i compare dates?

Body:
I have date in string type then I need to compare these 2 dates

I've tried this but it shows me strange output

string str="2019-1-12";
    string str1="2019-1-13";
    tm timeDate;
    tm timeDate1;
    strptime(str.c_str(),"%Y-%m-%d ", &timeDate);
    time_t time_input = mktime(&timeDate);
    strptime(str1.c_str(),"%Y-%m-%d ", &timeDate1);
    time_t time_input1 = mktime(&timeDate1);

    double timeDiff = difftime(time_input,time_input1);
    cout<<timeDiff;

Body:
less than,equal to,greather than another date

When your dates are strings in the format of "YYYY-mm-dd", this is a special case where the less-than operator for string gives the same result as the less-than operator would for a hypothetical date class.  This is because the date is stored in "big endian" format, each number in the date is also "big endian".

The string less-than operator compares each character one-by-one and if one is less than the other, then that is the result of the entire comparison.

The only thing you need to do is to make sure that your month and day fields are each two characters (put a zero in front if they are one character), and then compare the strings.

cout << (str < str1) << '\n';

Ditto for equality comparison.


问:
Prevent reading a certain collection
I have many collections for reading, but they are not allowed to write. I also have one collection where reading is prohibited, but writing is allowed. How to do this correctly?
I tried many ways to correctly prescribe the rules. The official documentation did not solve my problem.

It should work on this principle:

```<code>match /{document=**} {
      allow read: if true;
      allow write: if false;
    }
match /FOLDER/FOLDER {
      allow read: if false;
      allow write: if true;
    }
</code>```

But it does not work because Overlapping match statements.
"In the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true"

Tried also with exists and get.

There are no common fields between these collections.

How to do this correctly?

答:
Since this rule grants unconditional read access to your entire database:

```<code>match /{document=**} {
  allow read: if true;
  allow write: if false;
}
</code>```

You can't use it at all if you don't want some of your collections to have read access.  You should remove that rule, and write new rules for each of the collections where you do want to allow access.

You could also try omitting the one unreadable collection from the global rule, but I don't recommend this, as it's less clear what you're trying to do:

```<code>match /{document=**} {
  allow read: if document[0] != "unreadable-collection";
  allow write: if false;
}
</code>```

Title: Prevent reading a certain collection

Body:
I have many collections for reading, but they are not allowed to write. I also have one collection where reading is prohibited, but writing is allowed. How to do this correctly?
I tried many ways to correctly prescribe the rules. The official documentation did not solve my problem.

It should work on this principle:

match /{document=**} {
      allow read: if true;
      allow write: if false;
    }
match /FOLDER/FOLDER {
      allow read: if false;
      allow write: if true;
    }

But it does not work because Overlapping match statements.
"In the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true"

Tried also with exists and get.

There are no common fields between these collections.

How to do this correctly?

Body:
Since this rule grants unconditional read access to your entire database:

match /{document=**} {
  allow read: if true;
  allow write: if false;
}

You can't use it at all if you don't want some of your collections to have read access.  You should remove that rule, and write new rules for each of the collections where you do want to allow access.

You could also try omitting the one unreadable collection from the global rule, but I don't recommend this, as it's less clear what you're trying to do:

match /{document=**} {
  allow read: if document[0] != "unreadable-collection";
  allow write: if false;
}


问:
Discard some dictionary items in list during random.choice
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

```<code>x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]
</code>```

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.

答:
You can choose from a list whose elements satisfy your criteria:</p>

```<code>random.choice([elem for elem in x if elem["ready"]])
</code>```

Body:
I want to get random item from a list, also I don't want some items to be consider while random.choice(). Below is my data structure

x=[
  { 'id': 1, 'version':0.1, 'ready': True  }
  { 'id': 6, 'version':0.2, 'ready': True }
  { 'id': 4, 'version':0.1, 'ready': False }
  { 'id': 35, 'version':0.1, 'ready': False  }
  { 'id': 45, 'version':0.1, 'ready': False  }
  { 'id': 63, 'version':0.1, 'ready': True   }
  { 'id': 34, 'version':0.1, 'ready': True   }
  { 'id': 33, 'version':0.1, 'ready': True   }
]

I can get the random item by using random.choice(x). But is there any way, consider 'ready': True attribute of item while random.choice().

Or any SIMPLE trick to achieve this?

NOTE: I want to use python in-built modules to avoid dependencies like numpy, etc.

Body:
You can choose from a list whose elements satisfy your criteria:

random.choice([elem for elem in x if elem["ready"]])


答:
One approach is to create an AngularJS promise from the callback-based API:

```<code>getData() {
    const deferred = this.$q.defer();
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
        deferred.reject(err);
        return;
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      deferred.resolve(data);
    });
    return deferred.promise;
}
</code>```

When an AngularJS promise resolves, the AngularJS framework automatically invokes $apply. This brings the data into the AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

Title: how to await data from meteor call?

Body:
One approach is to create an AngularJS promise from the callback-based API:

getData() {
    const deferred = this.$q.defer();
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
        deferred.reject(err);
        return;
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      deferred.resolve(data);
    });
    return deferred.promise;
}

When an AngularJS promise resolves, the AngularJS framework automatically invokes $apply. This brings the data into the AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.