问:
Cannot read property of undefined even though the pojo is correctly implemented
I am trying to map the response from an API and put it in html. Here are the main classes

app.component.html

```<code><h1>sneaky calories work!!</h1>
your query is {{recipeResult.q}}
<div *ngFor = "let recipeIn of recipeResult.hits">
    {{recipeIn.label}} {{recipeIn.url}}
<div>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { SearchRecipeService } from './recipe-service.service';
import { RecipeGlobal } from './pojos/recipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SnearkyCalories';
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService){}

  ngOnInit(){
    this.getRecipeInfo();
    console.log(this.recipeResult.hits);
  }

  getRecipeInfo(){
    this.searchRecipeService.getRecipeInfo().
    subscribe(recipeResult => this.recipeResult = recipeResult);
 }
}
</code>```

Recipe.ts:

```<code>export interface RecipeGlobal {
    q:     string;
    from:  number;
    to:    number;
    more:  boolean;
    count: number;
    hits:  Hit[];
}

export interface Hit {
    recipe:     Recipe;
    bookmarked: boolean;
    bought:     boolean;
}

export interface Recipe {
    uri:             string;
    label:           string;
    image:           string;
    source:          string;
    url:             string;
    shareAs:         string;
    yield:           number;
    dietLabels:      string[];
    healthLabels:    string[];
    cautions:        any[];
    ingredientLines: string[];
    ingredients:     Ingredient[];
    calories:        number;
    totalWeight:     number;
    totalTime:       number;
    totalNutrients:  { [key: string]: Total };
    totalDaily:      { [key: string]: Total };
    digest:          Digest[];
}

export interface Digest {
    label:        string;
    tag:          string;
    schemaOrgTag: null | string;
    total:        number;
    hasRDI:       boolean;
    daily:        number;
    unit:         Unit;
    sub?:         Digest[];
}

export enum Unit {
    Empty = "%",
    G = "g",
    Kcal = "kcal",
    Mg = "mg",
    Μg = "µg",
}

export interface Ingredient {
    text:   string;
    weight: number;
}

export interface Total {
    label:    string;
    quantity: number;
    unit:     Unit;
}
</code>```

recipe-service.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators'
import { Component, OnInit, Input } from '@angular/core';
import {RecipeGlobal, Recipe} from './pojos/recipe'

@Injectable({
  providedIn: 'root'
})
export class SearchRecipeService {

  constructor(
    private http: HttpClient) {}

    private searchUrl = 'https://api.edamam.com/search?q=bandeja paisa&app_id=xxxx&app_key=xxxxx&from=0&to=3&calories=591-722&health=alcohol-free';

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl);
  }

}
</code>```

I am getting this error in the chrome console:
Cannot read property 'hits' of undefined

I have tried printing the object directly in console but still get the same error. It seems like hits is not being parsed properly.

答:
recipeResult is still undefined when the component is created. You should use the safe navigation operator or use *ngIf:

```<code><div *ngFor="let recipeIn of recipeResult?.hits">
</code>```

or

```<code><ng-container *ngIf="recipeResult">
  <h1>sneaky calories work!!</h1>
  your query is {{recipeResult.q}}
  <div *ngFor = "let recipeIn of recipeResult.hits">
    {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>

</code>```

Body:
I am trying to map the response from an API and put it in html. Here are the main classes

app.component.html

sneaky calories work!!

your query is {{recipeResult.q}}

    {{recipeIn.label}} {{recipeIn.url}}

app.component.ts

import { Component } from '@angular/core';
import { SearchRecipeService } from './recipe-service.service';
import { RecipeGlobal } from './pojos/recipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SnearkyCalories';
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService){}

  ngOnInit(){
    this.getRecipeInfo();
    console.log(this.recipeResult.hits);
  }

  getRecipeInfo(){
    this.searchRecipeService.getRecipeInfo().
    subscribe(recipeResult => this.recipeResult = recipeResult);
 }
}

Recipe.ts:

export interface RecipeGlobal {
    q:     string;
    from:  number;
    to:    number;
    more:  boolean;
    count: number;
    hits:  Hit[];
}

export interface Hit {
    recipe:     Recipe;
    bookmarked: boolean;
    bought:     boolean;
}

export interface Recipe {
    uri:             string;
    label:           string;
    image:           string;
    source:          string;
    url:             string;
    shareAs:         string;
    yield:           number;
    dietLabels:      string[];
    healthLabels:    string[];
    cautions:        any[];
    ingredientLines: string[];
    ingredients:     Ingredient[];
    calories:        number;
    totalWeight:     number;
    totalTime:       number;
    totalNutrients:  { [key: string]: Total };
    totalDaily:      { [key: string]: Total };
    digest:          Digest[];
}

export interface Digest {
    label:        string;
    tag:          string;
    schemaOrgTag: null | string;
    total:        number;
    hasRDI:       boolean;
    daily:        number;
    unit:         Unit;
    sub?:         Digest[];
}

export enum Unit {
    Empty = "%",
    G = "g",
    Kcal = "kcal",
    Mg = "mg",
    Μg = "µg",
}

export interface Ingredient {
    text:   string;
    weight: number;
}

export interface Total {
    label:    string;
    quantity: number;
    unit:     Unit;
}

recipe-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators'
import { Component, OnInit, Input } from '@angular/core';
import {RecipeGlobal, Recipe} from './pojos/recipe'

@Injectable({
  providedIn: 'root'
})
export class SearchRecipeService {

  constructor(
    private http: HttpClient) {}

    private searchUrl = 'https://api.edamam.com/search?q=bandeja paisa&app_id=xxxx&app_key=xxxxx&from=0&to=3&calories=591-722&health=alcohol-free';

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl);
  }

}

I am getting this error in the chrome console:
Cannot read property 'hits' of undefined

I have tried printing the object directly in console but still get the same error. It seems like hits is not being parsed properly.

Body:
recipeResult is still undefined when the component is created. You should use the safe navigation operator or use *ngIf:

<div *ngFor="let recipeIn of recipeResult?.hits">

or

<ng-container *ngIf="recipeResult">
  <h1>sneaky calories work!!</h1>
  your query is {{recipeResult.q}}
  <div *ngFor = "let recipeIn of recipeResult.hits">
    {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>


来源: stackexchange

问:
madExcept + UPX
I'm having problems using madExcept + UPX on Delphi 2007.
Whenever I open the compressed application, a Windows exception dialog appears code 0xc0000005.
Anyone has the solution for this?

Thanks!

答:
That exception code usually means it's an unhandled external exception. What happens if you don't Use UPX? Does the exception go away?

It may not have anything to do with MadExcept, BTW. That exception code usually indicates that the exception happened before the VCL's exception handlers can be set up, and therefore it would probably be before MadExcept gets hooked in as well.

EDIT: From your comment, it sounds like UPX's compression technique may be interfering with MadExcept/Delphi's ability to hook up the Exception handler chain. Did you check the link Bruce provided?

OwnerDisplayName: gmuller

ContentLicense: CC BY-SA 2.5

Title: madExcept + UPX

OwnerDisplayName: Ken White

LastEditorDisplayName: Ken White


问:
search for innerHTML value in a table
how can I search in a table for a row with a specifik innerHTML value?

```<code><table>
<tr><td>test</td><td>100</td></tr>
<tr><td>test</td><td>200</td></tr>
<tr><td>test</td><td>300</td></tr>
</table>
</code>```

I need the index for the row (tr) where the second td is 200

here the index has to give 1

```<code>$('table tr'). something??
</code>```

EDIT:

and I also need a version that select the index before a give value is bigger (asc) than 200 (if it exists)

答: var ind = $('table tr:contains(200)').index();</p>

ContentLicense: CC BY-SA 3.0

Title: search for innerHTML value in a table

Body:
how can I search in a table for a row with a specifik innerHTML value?

test	100

test	200

test	300

I need the index for the row (tr) where the second td is 200

here the index has to give 1

$('table tr'). something??

EDIT:

and I also need a version that select the index before a give value is bigger (asc) than 200 (if it exists)


问:
Comparing the attributes of instances in a list and then adding to new list
I want to set up an algorithm where I have a list of instances of people for e.g:

```<code>worst_office = [jim, michael, pam, toby, oscar, kevin, kelly, ryan, jan]
</code>```

Now, all of these instances have an attribute with one person that they like, for e.g. jim likes pam, and an attribute with a list of two people that they dislike. So, what would be the most efficient way of comparing the attributes of all of the instances in the list, and then making and finding ALL the number of new lists with only those people that have either one person they like in the new group, or one dislike and one like, but NOT two dislikes.

For e.g.

michael hates jan and toby, but likes jim

toby hates michael and kevin, but likes pam

So, one list could contain [michael, toby, pam, jim] because even though michael and toby hate eachother but they still have one person that they like. Another list could contains toby but not jim, so michael shouldn't be included in the list since there is no one in there that he likes. AND if a list contains both jan and toby, michael won't still be included even if jim is in there since there are two people that he dislikes in the list.

So, I want to find out ALL of potential number of ways we can group ALL of the people in the list. I have tried to do it in the following way, but it takes a long time to process because of the permutation and I get multiple duplicates. I would appreciate a response, and any further questions on this algorithm. Thank you!

```<code>def check(first_list, second_list):
  for each_employee in first_list:
    name = each_employee.get_name()
    is_disliked = False
    is_liked = False
    count = 0

    if second_list:
        for j in second_list:
            if name in j.get_dislikes():
                is_disliked = True
                count += 1
            elif name == j.get_likes():
                is_liked = True

    if (is_disliked and not is_liked) or count > 1:
        if each_employee in second_list:
            second_list.remove(each_employee)
    else:
        if each_employee in second_list:
            pass
        else:
            second_list += [each_employee, ]

def checking(office_list):
    z = [1]
    best_office = []
    check(office_list, best_office)
    check(best_office.copy(), best_office)
    if len(best_office) >= 9:
    #This is to make sure only lists with more than 9 employees are selected
        for i in best_office:
            print(i.get_name())
        print('-----------------------')

perm_employees = itertools.permutations(worst_office)

for x in perm_employees:
    checking(x)
</code>```

答:
Works pretty quick

without the @functools.lru_cache(maxsize=None), it takes 0.15 seconds
with the cache its 0.06

I think there is a smarter answer, this is just brute force

```<code>import functools
import itertools as it
import time

start_time = time.time()

worst_office = ["jim", "michael", "pam", "toby", "oscar", "kevin", "kelly", "ryan", "jan"]

like_dislike_dict = {}
like_dislike_dict[("jim", "toby")] = -1
like_dislike_dict[("jim", "oscar")] = -1
like_dislike_dict[("jim", "michael")] = 1
like_dislike_dict[("michael", "pam")] = 1
like_dislike_dict[("michael", "toby")] = -1
like_dislike_dict[("michael", "oscar")] = -1
like_dislike_dict[("pam", "toby")] = -1
like_dislike_dict[("pam", "oscar")] = -1
like_dislike_dict[("pam", "jim")] = 1
like_dislike_dict[("toby", "jim")] = -1
like_dislike_dict[("toby", "michael")] = -1
like_dislike_dict[("toby", "oscar")] = 1
like_dislike_dict[("oscar", "jim")] = -1
like_dislike_dict[("oscar", "michael")] = -1
like_dislike_dict[("oscar", "kevin")] = 1
like_dislike_dict[("kevin", "ryan")] = -1
like_dislike_dict[("kevin", "jim")] = -1
like_dislike_dict[("kevin", "toby")] = 1
like_dislike_dict[("kelly", "jim")] = -1
like_dislike_dict[("kelly", "michael")] = -1
like_dislike_dict[("kelly", "ryan")] = 1
like_dislike_dict[("ryan", "jim")] = -1
like_dislike_dict[("ryan", "michael")] = -1
like_dislike_dict[("ryan", "jan")] = 1
like_dislike_dict[("jan", "jim")] = -1
like_dislike_dict[("jan", "michael")] = -1
like_dislike_dict[("jan", "kelly")] = 1

def partition(collection):
    # from https://stackoverflow.com/questions/19368375/set-partitions-in-python
    if len(collection) == 1:
        yield [ collection ]
        return
    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[ first ] + subset]  + smaller[n+1:]
        # put `first` in its own subset
        yield [ [ first ] ] + smaller

@functools.lru_cache(maxsize=None)
def valid_list(l):
    for name in l:
        per_set = it.product([name], l)
        per_set = frozenset(per_set)
        if not valid_set(per_set):
            return False
    return True

def valid_set(t):
    sum = 0
    in_dict = False
    for per in t:

        if per in like_dislike_dict:

            in_dict = True
            sum+= like_dislike_dict[per]
    if not in_dict or sum<0:
        return False
    return True

partition_list = list(partition(worst_office))
valids = []
for partition_option in partition_list:
    valid = True
    for part in partition_option:
        if not valid_list(frozenset(part)):
            valid = False
    if valid:
        valids.append(partition_option)

print(valids)
print(list(partition_list[-4]))
print("--- %s seconds ---" % (time.time() - start_time))

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to set up an algorithm where I have a list of instances of people for e.g:

worst_office = [jim, michael, pam, toby, oscar, kevin, kelly, ryan, jan]

Now, all of these instances have an attribute with one person that they like, for e.g. jim likes pam, and an attribute with a list of two people that they dislike. So, what would be the most efficient way of comparing the attributes of all of the instances in the list, and then making and finding ALL the number of new lists with only those people that have either one person they like in the new group, or one dislike and one like, but NOT two dislikes.

For e.g.

michael hates jan and toby, but likes jim

toby hates michael and kevin, but likes pam

So, one list could contain [michael, toby, pam, jim] because even though michael and toby hate eachother but they still have one person that they like. Another list could contains toby but not jim, so michael shouldn't be included in the list since there is no one in there that he likes. AND if a list contains both jan and toby, michael won't still be included even if jim is in there since there are two people that he dislikes in the list.

So, I want to find out ALL of potential number of ways we can group ALL of the people in the list. I have tried to do it in the following way, but it takes a long time to process because of the permutation and I get multiple duplicates. I would appreciate a response, and any further questions on this algorithm. Thank you!

def check(first_list, second_list):
  for each_employee in first_list:
    name = each_employee.get_name()
    is_disliked = False
    is_liked = False
    count = 0

    if second_list:
        for j in second_list:
            if name in j.get_dislikes():
                is_disliked = True
                count += 1
            elif name == j.get_likes():
                is_liked = True

    if (is_disliked and not is_liked) or count > 1:
        if each_employee in second_list:
            second_list.remove(each_employee)
    else:
        if each_employee in second_list:
            pass
        else:
            second_list += [each_employee, ]

def checking(office_list):
    z = [1]
    best_office = []
    check(office_list, best_office)
    check(best_office.copy(), best_office)
    if len(best_office) >= 9:
    #This is to make sure only lists with more than 9 employees are selected
        for i in best_office:
            print(i.get_name())
        print('-----------------------')

perm_employees = itertools.permutations(worst_office)

for x in perm_employees:
    checking(x)

Body:
Works pretty quick

without the @functools.lru_cache(maxsize=None), it takes 0.15 seconds
with the cache its 0.06

I think there is a smarter answer, this is just brute force

import functools
import itertools as it
import time

start_time = time.time()

worst_office = ["jim", "michael", "pam", "toby", "oscar", "kevin", "kelly", "ryan", "jan"]

like_dislike_dict = {}
like_dislike_dict[("jim", "toby")] = -1
like_dislike_dict[("jim", "oscar")] = -1
like_dislike_dict[("jim", "michael")] = 1
like_dislike_dict[("michael", "pam")] = 1
like_dislike_dict[("michael", "toby")] = -1
like_dislike_dict[("michael", "oscar")] = -1
like_dislike_dict[("pam", "toby")] = -1
like_dislike_dict[("pam", "oscar")] = -1
like_dislike_dict[("pam", "jim")] = 1
like_dislike_dict[("toby", "jim")] = -1
like_dislike_dict[("toby", "michael")] = -1
like_dislike_dict[("toby", "oscar")] = 1
like_dislike_dict[("oscar", "jim")] = -1
like_dislike_dict[("oscar", "michael")] = -1
like_dislike_dict[("oscar", "kevin")] = 1
like_dislike_dict[("kevin", "ryan")] = -1
like_dislike_dict[("kevin", "jim")] = -1
like_dislike_dict[("kevin", "toby")] = 1
like_dislike_dict[("kelly", "jim")] = -1
like_dislike_dict[("kelly", "michael")] = -1
like_dislike_dict[("kelly", "ryan")] = 1
like_dislike_dict[("ryan", "jim")] = -1
like_dislike_dict[("ryan", "michael")] = -1
like_dislike_dict[("ryan", "jan")] = 1
like_dislike_dict[("jan", "jim")] = -1
like_dislike_dict[("jan", "michael")] = -1
like_dislike_dict[("jan", "kelly")] = 1

def partition(collection):
    # from https://stackoverflow.com/questions/19368375/set-partitions-in-python
    if len(collection) == 1:
        yield [ collection ]
        return
    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[ first ] + subset]  + smaller[n+1:]
        # put `first` in its own subset
        yield [ [ first ] ] + smaller

@functools.lru_cache(maxsize=None)
def valid_list(l):
    for name in l:
        per_set = it.product([name], l)
        per_set = frozenset(per_set)
        if not valid_set(per_set):
            return False
    return True

def valid_set(t):
    sum = 0
    in_dict = False
    for per in t:

        if per in like_dislike_dict:

            in_dict = True
            sum+= like_dislike_dict[per]
    if not in_dict or sum<0:
        return False
    return True

partition_list = list(partition(worst_office))
valids = []
for partition_option in partition_list:
    valid = True
    for part in partition_option:
        if not valid_list(frozenset(part)):
            valid = False
    if valid:
        valids.append(partition_option)

print(valids)
print(list(partition_list[-4]))
print("--- %s seconds ---" % (time.time() - start_time))


问:
mat-form-field must contain a MatFormFieldControl
We are trying to build our own form-field-Components at our Company. We are trying to wrap material design's Components like this:

field:

<mat-form-field>
    <ng-content></ng-content>
    <mat-hint align="start">{{hint}} </mat-hint>
    <mat-hint align="end">{{message.value.length}} / 256</mat-hint>
    <mat-error>This field is required</mat-error>
</mat-form-field>
```
<p>textbox:</p>
<pre class="lang-html prettyprint-override"><code><field hint="hint">
    <input matInput
    [placeholder]="placeholder"
    [value]="value"
    (change)="onChange($event)"
    (keydown)="onKeydown($event)"
    (keyup)="onKeyup($event)"
    (keypress)="onKeypress($event)">
</field>
</code>```

Usage:

<textbox value="test" hint="my hint"></textbox>
```
<p>This results in approximately this:</p>
<pre class="lang-html prettyprint-override"><code><textbox  placeholder="Personnummer/samordningsnummer" value="" ng-reflect-placeholder="Personnummer/samordningsnummer">
  <field>
    <mat-form-field class="mat-input-container mat-form-field">
      <div class="mat-input-wrapper mat-form-field-wrapper">
        <div class="mat-input-flex mat-form-field-flex">
          <div class="mat-input-infix mat-form-field-infix">
            <input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false">
            <span class="mat-input-placeholder-wrapper mat-form-field-placeholder-wrapper"></span>
          </div>
        </div>
        <div class="mat-input-underline mat-form-field-underline">
          <span class="mat-input-ripple mat-form-field-ripple"></span>
        </div>
        <div class="mat-input-subscript-wrapper mat-form-field-subscript-wrapper"></div>
      </div>
    </mat-form-field>
  </field>
</textbox>
</code>```

But I'm getting "mat-form-field must contain a MatFormFieldControl" in the console. I guess this has to do with mat-form-field not directly containing a matInput-field. But it is containing it, it's just withing the ng-content projection.

Here is a blitz:
https://stackblitz.com/edit/angular-xpvwzf

答: You have missed matInput  directive in your input tag.

Body:
We are trying to build our own form-field-Components at our Company. We are trying to wrap material design's Components like this:

field:

<mat-form-field>
    <ng-content></ng-content>
    <mat-hint align="start">{{hint}} </mat-hint>
    <mat-hint align="end">{{message.value.length}} / 256</mat-hint>
    <mat-error>This field is required</mat-error>
</mat-form-field>

textbox:

<field hint="hint">
    <input matInput
    [placeholder]="placeholder"
    [value]="value"
    (change)="onChange($event)"
    (keydown)="onKeydown($event)"
    (keyup)="onKeyup($event)"
    (keypress)="onKeypress($event)">
</field>

Usage:

<textbox value="test" hint="my hint"></textbox>

This results in approximately this:

<textbox  placeholder="Personnummer/samordningsnummer" value="" ng-reflect-placeholder="Personnummer/samordningsnummer">
  <field>
    <mat-form-field class="mat-input-container mat-form-field">

            <input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false">

    </mat-form-field>
  </field>
</textbox>

But I'm getting "mat-form-field must contain a MatFormFieldControl" in the console. I guess this has to do with mat-form-field not directly containing a matInput-field. But it is containing it, it's just withing the ng-content projection.

Here is a blitz:
https://stackblitz.com/edit/angular-xpvwzf


问:
detecting when the camera view is blocked (black frame)
I'm trying to detect camera tampering (lens being blocked, resulting in a black frame). The approach I have taken so far is to apply background subtraction and then finding contours post thresholding the foreground mask. Next, I find the area of each contour and if the contour area is higher than a threshold value (say, larger than 3/4th of the camera frame area), then the camera is said to be tampered.
Although upon trying this approach, there is a false tamper alert, even when the camera captures full view.
Not sure, how to go about this detection.
Any help shall be highly appreciated</p>

答:
Take a snapshot from your camera and save it.
And run this python code. If you haven't PIL lib you have to install it.</p>

```<code>from PIL import Image
im = Image.open('yourCamSnapshot.jpg')
pixels = im.getdata()

blackThresh=30    #30 is RGB value
nblack=0

for pixel in pixels:
    if(pixel[0]<=blackThresh and pixel[1]<=blackThresh and pixel[2]<=blackThresh):
        nblack=nblack+1

n=len(pixels)

if (nblack / float(n)) > 0.8:    #0.8 is 80% black
    print("raise exception")
</code>```

Body:
Take a snapshot from your camera and save it.
And run this python code. If you haven't PIL lib you have to install it.

from PIL import Image
im = Image.open('yourCamSnapshot.jpg')
pixels = im.getdata()

blackThresh=30    #30 is RGB value
nblack=0

for pixel in pixels:
    if(pixel[0]<=blackThresh and pixel[1]<=blackThresh and pixel[2]<=blackThresh):
        nblack=nblack+1

n=len(pixels)

if (nblack / float(n)) > 0.8:    #0.8 is 80% black
    print("raise exception")


问:
Program to find parity
I'm trying to count the number of bits that are set to 1 but the total always comes to 1 (or 0 if there's none)
What am I doing wrong?

```<code>typedef uint32_t uint;

uint hamm_parity(uint data)
{
    uint total = 0;
    uint i;

    for (i = 0; i < 32; i++)
    {
        if ((data & (1u << i)) == (1u << i))
            total++;
    }
    if (total % 2 == 0)
        return 0;
    else
        return 1;
}
</code>```

I also tried with:

```<code>if ((data >> i) & 1u)
</code>```

Also tried changing "1u" to 1 and to a variable

答:
Okay so I found my error, I wrote the code on here in a simpler way so you wouldn't need context, but by doing so, I hid my error.

Instead of using 32 for the loop i used a constant, but I used the wrong one.
Silly me...

Thanks anyway for the help!

Title: Program to find parity

Body:
I'm trying to count the number of bits that are set to 1 but the total always comes to 1 (or 0 if there's none)
What am I doing wrong?

typedef uint32_t uint;

uint hamm_parity(uint data)
{
    uint total = 0;
    uint i;

    for (i = 0; i < 32; i++)
    {
        if ((data & (1u << i)) == (1u << i))
            total++;
    }
    if (total % 2 == 0)
        return 0;
    else
        return 1;
}

I also tried with:

if ((data >> i) & 1u)

Also tried changing "1u" to 1 and to a variable


问:
Position edge labels on igraph plot in R
I'm trying to use igraph to plot a causal diagram between a few variables. I below is my code and basically everything I want in the graph, except that I cannot get the other two edge labels to move up above the edges, like the one that connects "stability" to "status".

```<code>ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("-", "-", "-")

nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)

study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = 0.5,
     edge.label.cex = 3,
     edge.label.color = "black")
</code>```

答:
You have to specify for each label the y-coordinate, i.e. edge.label.y = c(0.6, 0.2, -0.5) . I changed your code a little bit so you can see which label is which, i.e. association <- c("A", "B", "C")

The complete code:

```<code>library(igraph)

ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("A", "B", "C")

nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)

study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = c(0.6, 0.2, -0.5), # specify the y-coordinate for each label
     edge.label.cex = 3,
     edge.label.color = "black")
</code>```

This wil result in:

Body:
I'm trying to use igraph to plot a causal diagram between a few variables. I below is my code and basically everything I want in the graph, except that I cannot get the other two edge labels to move up above the edges, like the one that connects "stability" to "status".

ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("-", "-", "-")

nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)

study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = 0.5,
     edge.label.cex = 3,
     edge.label.color = "black")

Body:
You have to specify for each label the y-coordinate, i.e. edge.label.y = c(0.6, 0.2, -0.5) . I changed your code a little bit so you can see which label is which, i.e. association <- c("A", "B", "C")

The complete code:

library(igraph)

ego <- c("Stability (high)", "Stability (high)", "Stability (high)")
alter <- c("Status", "Depressive symptoms", "Anxiety Symptoms")
association <- c("A", "B", "C")

nodes <- c("Stability (high)", "Status", "Depressive symptoms", "Anxiety Symptoms")
x <- c(-5, 5, 5, 5)
y <- c(4, 8, 4, 0)

edges <- as.data.frame(cbind(ego, alter, association))
nodes <- cbind.data.frame(nodes, x, y)

nodes$x <- as.numeric(nodes$x)
nodes$y <- as.numeric(nodes$y)

study1 <- graph_from_data_frame(edges, nodes, directed = TRUE)

E(study1)$color <- "red"

plot(study1, layout=as.matrix(nodes[,c("x","y")]),
     vertex.size = 75,
     vertex.color = "gray",
     vertex.label.color = "black",
     vertex.label.family = "Arial",
     vertex.label.cex = 0.7,
     edge.arrow.size = 0.7,
     edge.width = 3.5,
     edge.color = E(study1)$color,
     edge.label = E(study1)$association,
     edge.label.y = c(0.6, 0.2, -0.5), # specify the y-coordinate for each label
     edge.label.cex = 3,
     edge.label.color = "black")

This wil result in:


答:
The error is simply because you are trying to access recipeResult before it has been returned asynchronously.

```<code>ngOnInit(){
  this.getRecipeInfo();
  // ERROR: this.recipeResult hasn't been returned from the service yet
  // console.log(this.recipeResult.hits);
}

getRecipeInfo(){
  this.searchRecipeService.getRecipeInfo().
  subscribe(recipeResult => {
    this.recipeResult = recipeResult);
    // Move here, it will now log correctly after the recipeResult has been returned
    console.log(this.recipeResult.hits);
  })
}
</code>```

And you also need to handle the null recipeResult in your component with a ? (>= v9) or *ngIf:

```<code><div *ngFor = "let recipeIn of recipeResult?.hits">
    {{recipeIn.label}} {{recipeIn.url}}
<div>

<!-- alternative for < Angular 9 -->
<ng-container *ngIf="recipeResult>
  <div *ngFor = "let recipeIn of recipeResult?.hits">
      {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>
</code>```

Title: Cannot read property of undefined even though the pojo is correctly implemented

Body:
The error is simply because you are trying to access recipeResult before it has been returned asynchronously.

ngOnInit(){
  this.getRecipeInfo();
  // ERROR: this.recipeResult hasn't been returned from the service yet
  // console.log(this.recipeResult.hits);
}

getRecipeInfo(){
  this.searchRecipeService.getRecipeInfo().
  subscribe(recipeResult => {
    this.recipeResult = recipeResult);
    // Move here, it will now log correctly after the recipeResult has been returned
    console.log(this.recipeResult.hits);
  })
}

And you also need to handle the null recipeResult in your component with a ? (>= v9) or *ngIf:

<div *ngFor = "let recipeIn of recipeResult?.hits">
    {{recipeIn.label}} {{recipeIn.url}}
<div>

<!-- alternative for < Angular 9 -->
<ng-container *ngIf="recipeResult>
  <div *ngFor = "let recipeIn of recipeResult?.hits">
      {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>


问:
Phalcon 4.x creates multiple folders to store cached data. What is the benefit of having recursive and multiple folders?

$hash = '123456789';
$fileName = "test.{$hash}.html";
```

the final directory structure will be like following.

te/st/.1/23/45/67/test.123456789.html

it simply breaks down the file name in to directories of two characters leaving the last 2 chars from the path test.123456789

答:
To prevent too many files in one folder error.
See https://docs.phalcon.io/4.0/en/cache#stream as well.

Body:
$hash = '123456789';
$fileName = "test.{$hash}.html";

the final directory structure will be like following.

te/st/.1/23/45/67/test.123456789.html

it simply breaks down the file name in to directories of two characters leaving the last 2 chars from the path test.123456789


问:
Set range equal to multiple named ranges with line break
I am setting a range variable equal to a list of ranges. The list is so long that I would like to use a line break for easier management. However, I am having a tough time getting the syntax. I've tried many combinations.

The code in one line works and looks like this (with a lot more named ranges):

```<code>Dim xNamedRangeList As Range
Set xNamedRangeList = Range("NamedRange1, NamedRange2")
</code>```

My best attempt so far is this.

```<code>Set xNamedRangeList = " Range(""" & _
"NamedRange1," & _
"NamedRange2" &_
""")"
</code>```

Debug.print looks like this: Ranged("NamedRange1, NamedRange2")

While this works in debug.print, it sure doesn't work when I set xNamedRangeList equal to it. I think I've turned the formula into a string, but not sure how to make it work in the formula.

答:
If NamedRange1  and  NamedRange2 are variables then try:</p>

```<code>Range(NamedRange1 + NamedRange2)
</code>```

Body:
I am setting a range variable equal to a list of ranges. The list is so long that I would like to use a line break for easier management. However, I am having a tough time getting the syntax. I've tried many combinations.

The code in one line works and looks like this (with a lot more named ranges):

Dim xNamedRangeList As Range
Set xNamedRangeList = Range("NamedRange1, NamedRange2")

My best attempt so far is this.

Set xNamedRangeList = " Range(""" & _
"NamedRange1," & _
"NamedRange2" &_
""")"

Debug.print looks like this: Ranged("NamedRange1, NamedRange2")

While this works in debug.print, it sure doesn't work when I set xNamedRangeList equal to it. I think I've turned the formula into a string, but not sure how to make it work in the formula.

Body:
If NamedRange1  and  NamedRange2 are variables then try:

Range(NamedRange1 + NamedRange2)


问:
Where can I download a sample Django template?
I just started working at a place as a front end developer where I need to build Django templates. I never worked with these before, does anyone know where I can download a sample template so I can look through the code structure?

I won't be doing any application development using the Django framework, only taking the variables the developer gives me and incorporating the in the html/css templates I build.

答:
Here's a nice little tutorial.
http://www.webmonkey.com/2010/02/use_templates_in_django/

Also, Check out the Django Docs.
http://docs.djangoproject.com/en/1.3/ref/templates/builtins/


问:
What is the best way to send a list of arguments to a function within a class in Python?
I have a class called Dataset. Now within this dataset there is a function which has been defined to read a csv. Now some of those files comes with different encodings and delimiters etc., So I need to pass a filepath, encodings and delimiter to that function. What is the best way to do this? In future there may be need for few more of these arguments.

```<code>class Dataset:
     def __init__(self,path):
        self.__fielpath=path
        .......
     def read(self):
        data=pd.read_csv(self.__filepath)
</code>```

For pd.read_csv() need to send arguments what is the best way to do this?

答:
Use **kwargs to pass keyword arguments inside the function

```<code>class Dataset:
     def __init__(self,path):
        self.__fielpath=path
        .......
     def read(self, **kwargs):
        data=pd.read_csv(self.__filepath, **kwargs)

d = Dataset(path="some_path")
data = d.read(columns=["a","b","c"], skiprows=3)
</code>```

Body:
I have a class called Dataset. Now within this dataset there is a function which has been defined to read a csv. Now some of those files comes with different encodings and delimiters etc., So I need to pass a filepath, encodings and delimiter to that function. What is the best way to do this? In future there may be need for few more of these arguments.

class Dataset:
     def __init__(self,path):
        self.__fielpath=path
        .......
     def read(self):
        data=pd.read_csv(self.__filepath)

For pd.read_csv() need to send arguments what is the best way to do this?

Body:
Use **kwargs to pass keyword arguments inside the function

class Dataset:
     def __init__(self,path):
        self.__fielpath=path
        .......
     def read(self, **kwargs):
        data=pd.read_csv(self.__filepath, **kwargs)

d = Dataset(path="some_path")
data = d.read(columns=["a","b","c"], skiprows=3)


问:
ArrayList sorted order lost strangely but why?
I have created a simple POJO Class Person and two comparators 'compareByValue' and 'compareByIndex' to sort the ArrayList of Person class. I start by sorting the ArrayList 'persons' and do a little filtering operation inside the loop of some other array. For the first pass it's okay but in the second pass of the loop ,immediately the order of Arraylist 'persons' is lost.
what's wrong with my code? the only operation done using ArrayList 'persons' is the subArray call does it destroy the ordering of the list?</p>

```<code>class Result {
     static class Person
     {
        public Person(int index,int value){
            this.index=index;
            this.value=value;
        }

        int index;
        int value;

        public int getValue() {
            return value;
        }

        public int getIndex() {
            return index;
        }
    }

    public static Comparator<Person>compareByValue=new Comparator<Result.Person>()
    {
        @Override
        public int compare(Person o1, Person o2) {
            // TODO Auto-generated method stub
           return o1.getValue()-o2.getValue();
        }
    };
    public static Comparator<Person>compareByIndex=new Comparator<Result.Person>(){

        @Override
        public int compare(Person o1, Person o2) {

           return o1.getIndex()-o2.getIndex();
        }
    };

    public static int target(int targetValue,List<Person> persons)
    {
        int res=-1;
        int s=0;
        int  e=persons.size()-1;

        while(s<=e)
        {
            int m = (s+e)/2;
            if(persons.get(m).getValue()<targetValue){
                s=m+1;
            }else{
                res=m;
                e=m-1;
            }
        }
    return res;
}

public static List<Integer> kthPerson(int k, List<Integer> p, List<Integer> q) {

     List<Person> persons=new ArrayList<>();
    List<Integer> queryRes=new ArrayList<>();

     for(int j=0;j<q.size();j++){
         queryRes.add(0);
     }

     for(int j=0;j<p.size();j++)
     {
         Person person=new Person(j,p.get(j));
         persons.add(person);
     }

    persons.sort(compareByValue);

    for(int j=0;j<q.size();j++)
    {
         int targetIndex=target(q.get(j).intValue(), persons);
         if(targetIndex==-1){continue;}

         if(persons.size()-targetIndex>=k)
         {
             List<Person> targetPersons=persons.subList(targetIndex, persons.size());
             targetPersons.sort(compareByIndex);
             queryRes.set(j, targetPersons.get(k-1).getIndex()+1);
         }
     }
        return queryRes;
    }
}
</code>```

答:
The subList() method does not change any order, but it also does not return a new list. Javadoc:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

  ...

   (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

That means that if the order in the sub-list is changed, same is reflect in main list. If this is not wanted, create a copy of the returned sub-list:

List<Person> targetPersons = new ArrayList(persons.subList(targetIndex, persons.size()));
```

I have not understood the algorithm of code posted in question, this answer is based mainly on questions text

Body:
I have created a simple POJO Class Person and two comparators 'compareByValue' and 'compareByIndex' to sort the ArrayList of Person class. I start by sorting the ArrayList 'persons' and do a little filtering operation inside the loop of some other array. For the first pass it's okay but in the second pass of the loop ,immediately the order of Arraylist 'persons' is lost.
what's wrong with my code? the only operation done using ArrayList 'persons' is the subArray call does it destroy the ordering of the list?

class Result {
     static class Person
     {
        public Person(int index,int value){
            this.index=index;
            this.value=value;
        }

        int index;
        int value;

        public int getValue() {
            return value;
        }

        public int getIndex() {
            return index;
        }
    }

    public static Comparator<Person>compareByValue=new Comparator<Result.Person>()
    {
        @Override
        public int compare(Person o1, Person o2) {
            // TODO Auto-generated method stub
           return o1.getValue()-o2.getValue();
        }
    };
    public static Comparator<Person>compareByIndex=new Comparator<Result.Person>(){

        @Override
        public int compare(Person o1, Person o2) {

           return o1.getIndex()-o2.getIndex();
        }
    };

    public static int target(int targetValue,List<Person> persons)
    {
        int res=-1;
        int s=0;
        int  e=persons.size()-1;

        while(s<=e)
        {
            int m = (s+e)/2;
            if(persons.get(m).getValue()<targetValue){
                s=m+1;
            }else{
                res=m;
                e=m-1;
            }
        }
    return res;
}

public static List<Integer> kthPerson(int k, List<Integer> p, List<Integer> q) {

     List<Person> persons=new ArrayList<>();
    List<Integer> queryRes=new ArrayList<>();

     for(int j=0;j<q.size();j++){
         queryRes.add(0);
     }

     for(int j=0;j<p.size();j++)
     {
         Person person=new Person(j,p.get(j));
         persons.add(person);
     }

    persons.sort(compareByValue);

    for(int j=0;j<q.size();j++)
    {
         int targetIndex=target(q.get(j).intValue(), persons);
         if(targetIndex==-1){continue;}

         if(persons.size()-targetIndex>=k)
         {
             List<Person> targetPersons=persons.subList(targetIndex, persons.size());
             targetPersons.sort(compareByIndex);
             queryRes.set(j, targetPersons.get(k-1).getIndex()+1);
         }
     }
        return queryRes;
    }
}

Body:
The subList() method does not change any order, but it also does not return a new list. Javadoc:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

  ...

   (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

That means that if the order in the sub-list is changed, same is reflect in main list. If this is not wanted, create a copy of the returned sub-list:

List<Person> targetPersons = new ArrayList(persons.subList(targetIndex, persons.size()));

I have not understood the algorithm of code posted in question, this answer is based mainly on questions text


问:
Limit drop area with Cytoscape
I'm trying to make a web designer with Cytoscape, and I'd like to set a restricted area in which the user can drop a node. In essence: the user can drop a node out of the "canvas" (just a rectangle in CSS) and they get lost. Like in the image below:

As you can see, my node is shaped as a rectangle, which can be dropped out of the zone I'm trying to limit. What should I do?
Thanks!

答:
The following code snippet uses both the built in cy.fit() function as well as the cytoscape-autopan-on-drag extension.

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),

    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },

      {
        selector: "edge",
        style: {
          "target-arrow-shape": "triangle"
        }
      },

      {
        selector: ":selected",
        style: {}
      }
    ],

    elements: {
      nodes: [{
          data: {
            id: "n0"
          }
        },
        {
          data: {
            id: "n1"
          }
        },
        {
          data: {
            id: "n2"
          }
        },
        {
          data: {
            id: "n3"
          }
        },
        {
          data: {
            id: "n4"
          }
        },
        {
          data: {
            id: "n5"
          }
        },
        {
          data: {
            id: "n6"
          }
        },
        {
          data: {
            id: "n7"
          }
        },
        {
          data: {
            id: "n8"
          }
        },
        {
          data: {
            id: "n9"
          }
        },
        {
          data: {
            id: "n10"
          }
        },
        {
          data: {
            id: "n11"
          }
        },
        {
          data: {
            id: "n12"
          }
        },
        {
          data: {
            id: "n13"
          }
        },
        {
          data: {
            id: "n14"
          }
        },
        {
          data: {
            id: "n15"
          }
        },
        {
          data: {
            id: "n16"
          }
        }
      ],
      edges: [{
          data: {
            source: "n0",
            target: "n1"
          }
        },
        {
          data: {
            source: "n1",
            target: "n2"
          }
        },
        {
          data: {
            source: "n1",
            target: "n3"
          }
        },
        {
          data: {
            source: "n4",
            target: "n5"
          }
        },
        {
          data: {
            source: "n4",
            target: "n6"
          }
        },
        {
          data: {
            source: "n6",
            target: "n7"
          }
        },
        {
          data: {
            source: "n6",
            target: "n8"
          }
        },
        {
          data: {
            source: "n8",
            target: "n9"
          }
        },
        {
          data: {
            source: "n8",
            target: "n10"
          }
        },
        {
          data: {
            source: "n11",
            target: "n12"
          }
        },
        {
          data: {
            source: "n12",
            target: "n13"
          }
        },
        {
          data: {
            source: "n13",
            target: "n14"
          }
        },
        {
          data: {
            source: "n13",
            target: "n15"
          }
        }
      ]
    },

    layout: {
      name: "dagre",
      padding: 50
    }
  }));

  // demo your core ext
  cy.autopanOnDrag({
    /* Options here */
  });

  cy.on('tapdrag', 'node', function() {
    cy.fit(cy.elements(), 50);
    cy.center();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px;
}

#cy {
  position: absolute;
  width: 60%;
  height: 60%;
  border: 1px solid gray;
}</code>```

```

Title: Limit drop area with Cytoscape

Body:
The following code snippet uses both the built in cy.fit() function as well as the cytoscape-autopan-on-drag extension.

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),

    style: [{
        selector: "node",
        style: {
          content: "data(id)"
        }
      },

      {
        selector: "edge",
        style: {
          "target-arrow-shape": "triangle"
        }
      },

      {
        selector: ":selected",
        style: {}
      }
    ],

    elements: {
      nodes: [{
          data: {
            id: "n0"
          }
        },
        {
          data: {
            id: "n1"
          }
        },
        {
          data: {
            id: "n2"
          }
        },
        {
          data: {
            id: "n3"
          }
        },
        {
          data: {
            id: "n4"
          }
        },
        {
          data: {
            id: "n5"
          }
        },
        {
          data: {
            id: "n6"
          }
        },
        {
          data: {
            id: "n7"
          }
        },
        {
          data: {
            id: "n8"
          }
        },
        {
          data: {
            id: "n9"
          }
        },
        {
          data: {
            id: "n10"
          }
        },
        {
          data: {
            id: "n11"
          }
        },
        {
          data: {
            id: "n12"
          }
        },
        {
          data: {
            id: "n13"
          }
        },
        {
          data: {
            id: "n14"
          }
        },
        {
          data: {
            id: "n15"
          }
        },
        {
          data: {
            id: "n16"
          }
        }
      ],
      edges: [{
          data: {
            source: "n0",
            target: "n1"
          }
        },
        {
          data: {
            source: "n1",
            target: "n2"
          }
        },
        {
          data: {
            source: "n1",
            target: "n3"
          }
        },
        {
          data: {
            source: "n4",
            target: "n5"
          }
        },
        {
          data: {
            source: "n4",
            target: "n6"
          }
        },
        {
          data: {
            source: "n6",
            target: "n7"
          }
        },
        {
          data: {
            source: "n6",
            target: "n8"
          }
        },
        {
          data: {
            source: "n8",
            target: "n9"
          }
        },
        {
          data: {
            source: "n8",
            target: "n10"
          }
        },
        {
          data: {
            source: "n11",
            target: "n12"
          }
        },
        {
          data: {
            source: "n12",
            target: "n13"
          }
        },
        {
          data: {
            source: "n13",
            target: "n14"
          }
        },
        {
          data: {
            source: "n13",
            target: "n15"
          }
        }
      ]
    },

    layout: {
      name: "dagre",
      padding: 50
    }
  }));

  // demo your core ext
  cy.autopanOnDrag({
    /* Options here */
  });

  cy.on('tapdrag', 'node', function() {
    cy.fit(cy.elements(), 50);
    cy.center();
  })
});

body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px;
}

#cy {
  position: absolute;
  width: 60%;
  height: 60%;
  border: 1px solid gray;
}

<html>

<head>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
  <script src="https://unpkg.com/dagre@0.7.4/dist/dagre.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-dagre@2.1.0/cytoscape-dagre.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-autopan-on-drag@2.2.0/cytoscape-autopan-on-drag.min.js"></script>
</head>

<body>
  <div id="cy"></div>
</body>

</html>


问:
Best way to install java 8 using docker?
I have a dockerfile that starts with the following line

FROM java:8

I thought this is supposed to pull the image from the docker container registry and install. no?

when I run the java command inside my container I get the following error

```<code>ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
</code>```

What is the easiest and the best way to install java 8(openjdk version) using docker?

UPDATE:

```<code>RUN apt-get install -y --no-install-recommends software-properties-common
RUN add-apt-repository -y ppa:openjdk-r/ppa
RUN apt-get update
RUN apt-get install -y openjdk-8-jdk
RUN apt-get install -y openjdk-8-jre
RUN update-alternatives --config java
RUN update-alternatives --config javac
</code>```

答:
Add below setting  to your DockerFile to install openjdk 8 in your docker container.</p>

```<code># Install "software-properties-common" (for the "add-apt-repository")
RUN apt-get update && apt-get install -y \
    software-properties-common

# Add the "JAVA" ppa
RUN add-apt-repository -y \
    ppa:webupd8team/java

# Install OpenJDK-8
RUN apt-get update && \
    apt-get install -y openjdk-8-jdk && \
    apt-get install -y ant && \
    apt-get clean;

# Fix certificate issues
RUN apt-get update && \
    apt-get install ca-certificates-java && \
    apt-get clean && \
    update-ca-certificates -f;

# Setup JAVA_HOME -- useful for docker commandline
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOME
</code>```

Body:
I have a dockerfile that starts with the following line

FROM java:8

I thought this is supposed to pull the image from the docker container registry and install. no?

when I run the java command inside my container I get the following error

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

What is the easiest and the best way to install java 8(openjdk version) using docker?

UPDATE:

RUN apt-get install -y --no-install-recommends software-properties-common
RUN add-apt-repository -y ppa:openjdk-r/ppa
RUN apt-get update
RUN apt-get install -y openjdk-8-jdk
RUN apt-get install -y openjdk-8-jre
RUN update-alternatives --config java
RUN update-alternatives --config javac

Body:
Add below setting  to your DockerFile to install openjdk 8 in your docker container.

# Install "software-properties-common" (for the "add-apt-repository")
RUN apt-get update && apt-get install -y \
    software-properties-common

# Add the "JAVA" ppa
RUN add-apt-repository -y \
    ppa:webupd8team/java

# Install OpenJDK-8
RUN apt-get update && \
    apt-get install -y openjdk-8-jdk && \
    apt-get install -y ant && \
    apt-get clean;

# Fix certificate issues
RUN apt-get update && \
    apt-get install ca-certificates-java && \
    apt-get clean && \
    update-ca-certificates -f;

# Setup JAVA_HOME -- useful for docker commandline
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOME


问:
How do I preserve line breaks when using jsoup to convert html to plain text?
I have the following code:

```<code> public class NewClass {
     public String noTags(String str){
         return Jsoup.parse(str).text();
     }

     public static void main(String args[]) {
         String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
         "<HTML> <HEAD> <TITLE></TITLE> <style>body{ font-size: 12px;font-family: verdana, arial, helvetica, sans-serif;}</style> </HEAD> <BODY><p><b>hello world</b></p><p><br><b>yo</b> <a href=\"http://google.com\">googlez</a></p></BODY> </HTML> ";

         NewClass text = new NewClass();
         System.out.println((text.noTags(strings)));
}
</code>```

And I have the result:

```<code>hello world yo googlez
</code>```

But I want to break the line:

```<code>hello world
yo googlez
</code>```

I have looked at jsoup's TextNode#getWholeText() but I can't figure out how to use it.

If there's a
 in the markup I parse, how can I get a line break in my resulting output?

答:
With

```<code>Jsoup.parse("A\nB").text();
</code>```

you have output

```<code>"A B"
</code>```

and not

```<code>A

B
</code>```

For this I'm using:

```<code>descrizione = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", "br2n")).text();
text = descrizione.replaceAll("br2n", "\n");
</code>```

Body:
I have the following code:

 public class NewClass {
     public String noTags(String str){
         return Jsoup.parse(str).text();
     }

     public static void main(String args[]) {
         String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
         "  <TITLE></TITLE>
hello world

yo googlez
  ";

         NewClass text = new NewClass();
         System.out.println((text.noTags(strings)));
}

And I have the result:

hello world yo googlez

But I want to break the line:

hello world
yo googlez

I have looked at jsoup's TextNode#getWholeText() but I can't figure out how to use it.

If there's a
 in the markup I parse, how can I get a line break in my resulting output?

Body:
With

Jsoup.parse("A\nB").text();

you have output

"A B"

and not

A

B

For this I'm using:

descrizione = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", "br2n")).text();
text = descrizione.replaceAll("br2n", "\n");


问:
Autosize height of ggplotly in shiny
I have a very high plotlyOutput (because it has many categories on the y axis). If It's rendered just with ggplotly(g), I get this plot, with a fixed height:

So I specify it's height, like this: ggplotly(g, height = 1500), I get an appropiate size (the following is a fraction of the plot because of it's size):

My problem is that when I filter the data through my app's input controls, It maintains the height (cause its now fixed), even when there are very few categories on the y axis. Like this (the following is a fraction of the plot because of it's size):

So, ¿how can I get dynamic height for my plotlyOutput, such as when there's, say, 3 categories on the y axis, It adjust the height to be shorter, but building to a maximum of 1500px as the number of categories increases?

答:
I don't see any solution except this one, which calculates the height in function of the number of categories in the plot:</p>

```<code>library(shiny)
library(plotly)

dat <- data.frame(
  Letter = c(LETTERS,letters),
  height = rpois(52, 10)
)

ui <- fluidPage(
  checkboxInput("filter", "Filter"),
  plotlyOutput("ggly", height = "100%")
)

server <- function(input, output, session){

  output[["ggly"]] <- renderPlotly({
    ggdat <- if(input[["filter"]]) dat[dat$Letter %in% c("A","B"),] else dat
    height <- nlevels(droplevels(ggdat$Letter)) * 30
    gg <- ggplot(ggdat) + geom_col(aes(x = Letter, y = height)) + coord_flip()
    ggplotly(gg, height = min(1500, max(300, height)))
  })

}

shinyApp(ui, server)
</code>```

Title: Autosize height of ggplotly in shiny

Body:
I don't see any solution except this one, which calculates the height in function of the number of categories in the plot:

library(shiny)
library(plotly)

dat <- data.frame(
  Letter = c(LETTERS,letters),
  height = rpois(52, 10)
)

ui <- fluidPage(
  checkboxInput("filter", "Filter"),
  plotlyOutput("ggly", height = "100%")
)

server <- function(input, output, session){

  output[["ggly"]] <- renderPlotly({
    ggdat <- if(input[["filter"]]) dat[dat$Letter %in% c("A","B"),] else dat
    height <- nlevels(droplevels(ggdat$Letter)) * 30
    gg <- ggplot(ggdat) + geom_col(aes(x = Letter, y = height)) + coord_flip()
    ggplotly(gg, height = min(1500, max(300, height)))
  })

}

shinyApp(ui, server)


问:
How Resolution changes X & Y cords
I am tracking the color of a pixel at X & Y at a resolution of 1920 by 1080, I am simply wondering if there is any mathematically way to remain accurate in tracking the same pixel throughout various resolutions.

The pixel is not moving and is static, however I am aware that changing resolutions affects scaling and the X & Y system of the monitor.

So any suggestions would be great!

答:
As always the whole screen area is filled, the same location on that physical screen (determined as the ratio of xLocation divided by the xWidth and the yLocation divided by the yHeight, this in centimeters or inches) will also always be at the same ratio of xPixelindex divided by xTotalpixels and yPixelindex divided by yTotalpixels.

Lets assume you have xRefererence and yReference of the target pixel, in a resolution WidthReference and HeightReference in which these coordinates mark the desired pixel.

Lets assume you have WidthCurrent and HeightCurrent of your screen size in pixels, for the resolurion in which you want to target a pixel at the same physical location.

Lets assume that you need to determine xCurrent and yCurrent as the coordinates for the pixel in the current resolution.

Then calculate the current coordinates as:

```<code>xCurrent = (1.0 * WidthCurrent) /  WidthReference * xReference;
yCurrent = (1.0 * HeightCurrent)/ HeightReference * yReference;
</code>```

Title: How Resolution changes X & Y cords

Body:
As always the whole screen area is filled, the same location on that physical screen (determined as the ratio of xLocation divided by the xWidth and the yLocation divided by the yHeight, this in centimeters or inches) will also always be at the same ratio of xPixelindex divided by xTotalpixels and yPixelindex divided by yTotalpixels.

Lets assume you have xRefererence and yReference of the target pixel, in a resolution WidthReference and HeightReference in which these coordinates mark the desired pixel.

Lets assume you have WidthCurrent and HeightCurrent of your screen size in pixels, for the resolurion in which you want to target a pixel at the same physical location.

Lets assume that you need to determine xCurrent and yCurrent as the coordinates for the pixel in the current resolution.

Then calculate the current coordinates as:

xCurrent = (1.0 * WidthCurrent) /  WidthReference * xReference;
yCurrent = (1.0 * HeightCurrent)/ HeightReference * yReference;


问:
Call a UIViewController method when application goes background and come to foreground
how to call a method when application goes background and changes some activity like the time or date of mobile and come to foreground (application active mode).

Then i want to call a method in UIViewController classes

FirstViewController Class Method.

```<code>-(void)refreshItems{
// Your item refresh code.
}
</code>```

答:
Add Below Code in ViewController</p>
```<code> override func viewDidLoad() {
 super.viewDidLoad()

//Mark:- application move to bckground

 let backgorundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)

//Mark:- application move to foreground

let foregroundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToForeground),name: UIApplication.willEnterForegroundNotification, object: nil)

 }

//Mark:- background method implementation

@objc func appMovedToBackground() {
print("App moved to background!")
 }

 //Mark:- foreground method implementation

@objc func appMovedToForeground() {
   print("App moved to foreground!")
}
</code>```

Body:
how to call a method when application goes background and changes some activity like the time or date of mobile and come to foreground (application active mode).

Then i want to call a method in UIViewController classes

FirstViewController Class Method.

-(void)refreshItems{
// Your item refresh code.
}

Body:
Add Below Code in ViewController

 override func viewDidLoad() {
 super.viewDidLoad()

//Mark:- application move to bckground

 let backgorundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)

//Mark:- application move to foreground

let foregroundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToForeground),name: UIApplication.willEnterForegroundNotification, object: nil)

 }

//Mark:- background method implementation

@objc func appMovedToBackground() {
print("App moved to background!")
 }

 //Mark:- foreground method implementation

@objc func appMovedToForeground() {
   print("App moved to foreground!")
}


问:
How to implement Three.js inside Gatsby?
I've installed react-three-fiber and three packages. I'm following this tutorial, but I have doubts of where to put this line:

const rootElement = document.getElementById("root");

Also, I'm starting to receive this error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

My index.js:

```<code>import React, { Children, useRef, useState } from "react"

import {  Link } from "gatsby"

import { Canvas} from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => {

  return(

    <Layout>

      <div>

        <h1>Hi</h1>

      </div>

      <canvas>

        <Children></Children>

      </canvas>

    </Layout>

    )

}

const rootElement = document.getElementById("root");

export default IndexPage
</code>```

Any ideas?

答:
Make sure you have installed both three and react-three-fiber.

```<code>npm install three react-three-fiber
</code>```

Then in your gatsby page component just import Canvas from react-three-fiber before using it in your JSX.

```<code>import React from "react"
import { Canvas} from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Canvas />
  </Layout>
)

export default IndexPage
</code>```

Regarding const rootElement = document.getElementById("root"); :

Although Gatsby is built with React, it doesn't require you to select a root element in order to render your app. If this sounds confusing, you should spend a little bit of time to take a read of the Gatsby docs.

If you were to build the example from the react-three-fiber docs in Gatsby, it would look something like this.

```<code>import React, { useRef, useState } from "react"
import { Canvas, useFrame } from "react-three-fiber"

const Box = props => {
  // This reference will give us direct access to the mesh so we can animate it
  const mesh = useRef()

  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)

  // Rotate mesh every frame, this is outside of React without overhead
  useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01))

  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? [1.5, 1.5, 1.5] : [1, 1, 1]}
      onClick={e => setActive(!active)}
      onPointerOver={e => setHover(true)}
      onPointerOut={e => setHover(false)}
    >
      <boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
      <meshStandardMaterial
        attach="material"
        color={hovered ? "hotpink" : "orange"}
      />
    </mesh>
  )
}

const IndexPage = () => (
  <Canvas>
    <ambientLight />
    <pointLight position={[10, 10, 10]} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />
  </Canvas>
)

export default IndexPage

</code>```

Body:
I've installed react-three-fiber and three packages. I'm following this tutorial, but I have doubts of where to put this line:

const rootElement = document.getElementById("root");

Also, I'm starting to receive this error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

My index.js:

import React, { Children, useRef, useState } from "react"

import {  Link } from "gatsby"

import { Canvas} from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => {

  return(

    <Layout>

Hi

      <canvas>

        <Children></Children>

      </canvas>

    </Layout>

    )

}

const rootElement = document.getElementById("root");

export default IndexPage

Any ideas?

Body:
Make sure you have installed both three and react-three-fiber.

npm install three react-three-fiber

Then in your gatsby page component just import Canvas from react-three-fiber before using it in your JSX.

import React from "react"
import { Canvas} from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Canvas />
  </Layout>
)

export default IndexPage

Regarding const rootElement = document.getElementById("root"); :

Although Gatsby is built with React, it doesn't require you to select a root element in order to render your app. If this sounds confusing, you should spend a little bit of time to take a read of the Gatsby docs.

If you were to build the example from the react-three-fiber docs in Gatsby, it would look something like this.

import React, { useRef, useState } from "react"
import { Canvas, useFrame } from "react-three-fiber"

const Box = props => {
  // This reference will give us direct access to the mesh so we can animate it
  const mesh = useRef()

  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)

  // Rotate mesh every frame, this is outside of React without overhead
  useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01))

  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? [1.5, 1.5, 1.5] : [1, 1, 1]}
      onClick={e => setActive(!active)}
      onPointerOver={e => setHover(true)}
      onPointerOut={e => setHover(false)}
    >
      <boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
      <meshStandardMaterial
        attach="material"
        color={hovered ? "hotpink" : "orange"}
      />
    </mesh>
  )
}

const IndexPage = () => (
  <Canvas>
    <ambientLight />
    <pointLight position={[10, 10, 10]} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />
  </Canvas>
)

export default IndexPage


问:
Getting the error that Expected an assignment or function call and instead saw an expression no-unused-expressions?
I am new in react js and i am following the Udemy course but I am getting the error that "Expected an assignment or function call and instead saw an expression  no-unused-expressions".Basically I am using a firebase database to develop this application in this app user put their name as a student.</p>

```<code>import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

var firebase=require('firebase');
var uuid=require('uuid');

var firebaseConfig = {
    apiKey: "AIzaSyAwXf9-4PgY0ttsGy1FHmyLHZOFO1oVcic",
    authDomain: "uservey-206d4.firebaseapp.com",
    databaseURL: "https://uservey-206d4.firebaseio.com",
    projectId: "uservey-206d4",
    storageBucket: "uservey-206d4.appspot.com",
    messagingSenderId: "723372497898",
    appId: "1:723372497898:web:0ebb13dcb9ce6d2f6eb093",
    measurementId: "G-J6190VVVQH"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

class Survey extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uid:uuid.v1(),
            studentName:'',
            answers:{
                answer1:'',
                answer2:'',
                answer3:'',
            },
            isSubmitted:false
         };
    }
    render() {
       var studentName;
       var questions;
         if(this.state.studentName ==='' && this.state.isSubmitted === false){
          <div>
              <h1>Please Enter Your Name:</h1>
             <input type="text" className="form-control" placeholder="Please Enter Your Name"/>
              </div>
         }
        return(
        <div>
            {studentName}
            ------------------------------
            {questions}
            </div> );}
}

export default Survey;
</code>```

答:
render function expects you to return jsx to render, so:

 render() {
   if(this.state.studentName ==='' && this.state.isSubmitted === false){
     return (

Please Enter Your Name:

         <input type="text" className="form-control" placeholder="Please Enter Your Name"/>

    )
   }

   return (

            {studentName}
            ------------------------------
            {questions}

   );
}
```

also, fix your indents, it helps to keep your sanity in the long run

Body:
I am new in react js and i am following the Udemy course but I am getting the error that "Expected an assignment or function call and instead saw an expression  no-unused-expressions".Basically I am using a firebase database to develop this application in this app user put their name as a student.

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

var firebase=require('firebase');
var uuid=require('uuid');

var firebaseConfig = {
    apiKey: "AIzaSyAwXf9-4PgY0ttsGy1FHmyLHZOFO1oVcic",
    authDomain: "uservey-206d4.firebaseapp.com",
    databaseURL: "https://uservey-206d4.firebaseio.com",
    projectId: "uservey-206d4",
    storageBucket: "uservey-206d4.appspot.com",
    messagingSenderId: "723372497898",
    appId: "1:723372497898:web:0ebb13dcb9ce6d2f6eb093",
    measurementId: "G-J6190VVVQH"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

class Survey extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uid:uuid.v1(),
            studentName:'',
            answers:{
                answer1:'',
                answer2:'',
                answer3:'',
            },
            isSubmitted:false
         };
    }
    render() {
       var studentName;
       var questions;
         if(this.state.studentName ==='' && this.state.isSubmitted === false){

Please Enter Your Name:

             <input type="text" className="form-control" placeholder="Please Enter Your Name"/>

         }
        return(

            {studentName}
            ------------------------------
            {questions}

 );}
}

export default Survey;

Body:
render function expects you to return jsx to render, so:

 render() {
   if(this.state.studentName ==='' && this.state.isSubmitted === false){
     return (
       <div>
         <h1>Please Enter Your Name:</h1>
         <input type="text" className="form-control" placeholder="Please Enter Your Name"/>
       </div>
    )
   }

   return (
     <div>
            {studentName}
            ------------------------------
            {questions}
     </div>
   );
}

also, fix your indents, it helps to keep your sanity in the long run


问:
Postgres CPU high usage after hours
I have a Application server  with Postgresql database on Windows 2016, 8 virtual threads CPU and 32GB memory

I try to stress with 10 client to concurrent insert to database,
each insert operation take about 500ms on a 2.5m records table

It's working fine in about 1hours and take ~2GB memory and 80% CPU,
after that time, cpu go up to 100% ( memory not change) and postgres seem not responding and client could not connect to server

I check in Postgres log and see error :

```<code>[2020-02-18 22:48:59 JST]  26344[16] WARNING:  worker took too long to start; canceled
</code>```

also have no lock with this query check :

```<code>SELECT bl.pid                 AS blocked_pid,
         a.usename              AS blocked_user,
         ka.query               AS current_or_recent_statement_in_blocking_process,
         ka.state               AS state_of_blocking_process,
         now() - ka.query_start AS blocking_duration,
         kl.pid                 AS blocking_pid,
         ka.usename             AS blocking_user,
         a.query                AS blocked_statement,
         now() - a.query_start  AS blocked_duration
  FROM  pg_catalog.pg_locks         bl
   JOIN pg_catalog.pg_stat_activity a  ON a.pid = bl.pid
   JOIN pg_catalog.pg_locks         kl ON kl.transactionid = bl.transactionid AND kl.pid != bl.pid
   JOIN pg_catalog.pg_stat_activity ka ON ka.pid = kl.pid
  WHERE NOT bl.GRANTED;
</code>```

No slow sql found in pg_stat_activity or pg lock

All memory,wal or checkpoint config is default

I also using postgresql ODBC for connection pool
Could anyone suggest me a way to detect the problem?

答:
If an INSERT takes half a second, you have a serious problem.

It looks like you are overloading the CPU resources on the database server. The solution would be to find the statements that take too much time when the database is not under load and tune them to be faster. Then you can handle more of them with your available CPU.

Title: Postgres CPU high usage after hours

Body:
I have a Application server  with Postgresql database on Windows 2016, 8 virtual threads CPU and 32GB memory

I try to stress with 10 client to concurrent insert to database,
each insert operation take about 500ms on a 2.5m records table

It's working fine in about 1hours and take ~2GB memory and 80% CPU,
after that time, cpu go up to 100% ( memory not change) and postgres seem not responding and client could not connect to server

I check in Postgres log and see error :

[2020-02-18 22:48:59 JST]  26344[16] WARNING:  worker took too long to start; canceled

also have no lock with this query check :

SELECT bl.pid                 AS blocked_pid,
         a.usename              AS blocked_user,
         ka.query               AS current_or_recent_statement_in_blocking_process,
         ka.state               AS state_of_blocking_process,
         now() - ka.query_start AS blocking_duration,
         kl.pid                 AS blocking_pid,
         ka.usename             AS blocking_user,
         a.query                AS blocked_statement,
         now() - a.query_start  AS blocked_duration
  FROM  pg_catalog.pg_locks         bl
   JOIN pg_catalog.pg_stat_activity a  ON a.pid = bl.pid
   JOIN pg_catalog.pg_locks         kl ON kl.transactionid = bl.transactionid AND kl.pid != bl.pid
   JOIN pg_catalog.pg_stat_activity ka ON ka.pid = kl.pid
  WHERE NOT bl.GRANTED;

No slow sql found in pg_stat_activity or pg lock

All memory,wal or checkpoint config is default

I also using postgresql ODBC for connection pool
Could anyone suggest me a way to detect the problem?


问:
How to change blank fields to null in express js
I want to get all request body params as null if param is blank. Is there any way in the express js.

```<code>{
  username: " ",
  password: ""
}
</code>```

// Get it as

```<code>{
  username: null,
  password: null
}
</code>```

答:
in a most simplest way (if you want to mutate the original object itself)    </p>

```<code>let obj = {username:'' , password:''}
for(i in obj){
    if(obj[i] === '')
        obj[i] = null
}
</code>```

Body:
I want to get all request body params as null if param is blank. Is there any way in the express js.

{
  username: " ",
  password: ""
}

// Get it as

{
  username: null,
  password: null
}

Body:
in a most simplest way (if you want to mutate the original object itself)

let obj = {username:'' , password:''}
for(i in obj){
    if(obj[i] === '')
        obj[i] = null
}


问:
Resizing images to fit inside a container
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

```

How I would like it to look:

答:
If you are using Bootstrap4 then don't need to write single line of css code as per your attachment image structure. So follow below html with help of BS4 predefined classes.

Use vh-100 class for viewport height 100%.

Use h-100 class in row to inherit parent height.

Use no-gutters in row class for removing gap.

Use h-50 class for each column height set to 50%.

Use img-fluid mh-100 on image for responsive.

Doc: https://getbootstrap.com/docs/4.3/utilities/sizing/#relative-to-the-parent

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

```

Body:
I'm trying to make a 4 panel screen which would fit the screen of any user who accesses it. The images push everything else out of the div that envolves them. I don't want it to overflow.

My code:

How I would like it to look:

Body:
If you are using Bootstrap4 then don't need to write single line of css code as per your attachment image structure. So follow below html with help of BS4 predefined classes.

Use vh-100 class for viewport height 100%.

Use h-100 class in row to inherit parent height.

Use no-gutters in row class for removing gap.

Use h-50 class for each column height set to 50%.

Use img-fluid mh-100 on image for responsive.

Doc: https://getbootstrap.com/docs/4.3/utilities/sizing/#relative-to-the-parent

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

<div class="container-fluid px-0 vh-100">
  <div class="row no-gutters h-100">
    <div class="col-6 h-50">
      <img src="https://docplayer.org/docs-images/22/1321497/images/61-0.png" class="img-fluid mh-100">
    </div>
    <div class="col-6 h-50">
      <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" class="img-fluid mh-100">
    </div>
    <div class="col-6 h-50">
      <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" class="img-fluid mh-100">
    </div>
    <div class="col-6 h-50">
      <img src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" class="img-fluid mh-100">
    </div>
  </div>
</div>


问:
open cash drawer with TM-T81 epson iOS SDK
I want to open a cash drawer which I have bought its printer driven cash drawer. And I have an Epson TM-T81 receipt printer.

I get a delegate called when I open and close the printer manually but I want to open it automatically when receipt is printed.

The code I have written is :

```<code>-(void)openDrawer{
    EposBuilder *builder = [[EposBuilder alloc] initWithPrinterModel:@"TM-P20" Lang:0];
    if(builder == nil){
        return ;
    }

//add command
int result;
result  = [builder addPulse:EPOS_OC_DRAWER_1 Time:EPOS_OC_PULSE_100];
NSLog(@"%d command result",result);
NSString *str = @"27 112 48 55 121";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
result = [builder addCommand:data];

NSLog(@"%d pulse",result);

if(result != EPOS_OC_SUCCESS){
    NSLog(@"cut failed");
    return ;
}

//send builder data
unsigned long status = 0;
unsigned long battery = 0;
result = [printer sendData:builder Timeout:10000 Status:&status Battery:&battery];

//remove builder
[builder clearCommandBuffer];
</code>```

}

Looking for a solution from experts like you.

答:
I added below the line of code and got working for the TM-T20 series.

```<code>[printer_ addPulse:EPOS2_DRAWER_HIGH time:EPOS2_PULSE_100];
</code>```

Body:
I want to open a cash drawer which I have bought its printer driven cash drawer. And I have an Epson TM-T81 receipt printer.

I get a delegate called when I open and close the printer manually but I want to open it automatically when receipt is printed.

The code I have written is :

-(void)openDrawer{
    EposBuilder *builder = [[EposBuilder alloc] initWithPrinterModel:@"TM-P20" Lang:0];
    if(builder == nil){
        return ;
    }

//add command
int result;
result  = [builder addPulse:EPOS_OC_DRAWER_1 Time:EPOS_OC_PULSE_100];
NSLog(@"%d command result",result);
NSString *str = @"27 112 48 55 121";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
result = [builder addCommand:data];

NSLog(@"%d pulse",result);

if(result != EPOS_OC_SUCCESS){
    NSLog(@"cut failed");
    return ;
}

//send builder data
unsigned long status = 0;
unsigned long battery = 0;
result = [printer sendData:builder Timeout:10000 Status:&status Battery:&battery];

//remove builder
[builder clearCommandBuffer];

}

Looking for a solution from experts like you.

Body:
I added below the line of code and got working for the TM-T20 series.

[printer_ addPulse:EPOS2_DRAWER_HIGH time:EPOS2_PULSE_100];


问:
How to download the qt mobility examples package in Opensuse 11.2
This example: http://doc.trolltech.com/qtmobility-1.1-tp/fetchgooglemaps.html is not present in the following "qt-mobility-opensource-src-1.2.0" directory: </p>

```<code>[17:05:10 Tue May 17] ~/tarBalls/qt-mobility-opensource-src-1.2.0/examples  $ls
annotatedurl             bttennis                   documentproperties     ndefeditor                    sfwecho
audiodevices             calendardemo               examples.pro           notesmanagerplugin            sfw-notes
audioinput               camera                     filemanagerplugin      publish-subscribe             slideshow
audiooutput              connectivity               flickrdemo             qmlorganizer                  sysinfo
audiorecorder            declarative-camera         hapticsplayer          qsystemalignedtimer           todo
battery-charge           declarative-connectivity   hapticsquare           querymessages                 videographicsitem
bearercloud              declarative-location       keepintouch            quickstart                    videowidget
bearermonitor            declarative-messages       landmarkbrowser        radio                         writemessage
bluetoothtransferplugin  declarative-music-browser  logfilepositionsource  samplephonebook
btchat                   declarative-sfw-dialer     mapsdemo               sensors
btfiletransfer           declarative-sfw-notes      mediabrowser           servicebrowser
btscanner                declarative-systeminfo     mobility_examples.pri  serviceinstaller_sfw_symbian
[17:08:20 Tue May 17] ~/tarBalls/qt-mobility-opensource-src-1.2.0/examples  $
</code>```

答:
The FetchGoogleMaps example seems to have been removed from the Qt Mobility examples after version 1.0.0. You could try getting it from one of these older tags, although there is no guarantee that it will work with the recent sources and might have some bugs.

Edit:

As the OP has found out, there are currently two improved examples over the older FetchGoogleMaps which can be found here and here.

Body:
This example: http://doc.trolltech.com/qtmobility-1.1-tp/fetchgooglemaps.html is not present in the following "qt-mobility-opensource-src-1.2.0" directory:

[17:05:10 Tue May 17] ~/tarBalls/qt-mobility-opensource-src-1.2.0/examples  $ls
annotatedurl             bttennis                   documentproperties     ndefeditor                    sfwecho
audiodevices             calendardemo               examples.pro           notesmanagerplugin            sfw-notes
audioinput               camera                     filemanagerplugin      publish-subscribe             slideshow
audiooutput              connectivity               flickrdemo             qmlorganizer                  sysinfo
audiorecorder            declarative-camera         hapticsplayer          qsystemalignedtimer           todo
battery-charge           declarative-connectivity   hapticsquare           querymessages                 videographicsitem
bearercloud              declarative-location       keepintouch            quickstart                    videowidget
bearermonitor            declarative-messages       landmarkbrowser        radio                         writemessage
bluetoothtransferplugin  declarative-music-browser  logfilepositionsource  samplephonebook
btchat                   declarative-sfw-dialer     mapsdemo               sensors
btfiletransfer           declarative-sfw-notes      mediabrowser           servicebrowser
btscanner                declarative-systeminfo     mobility_examples.pri  serviceinstaller_sfw_symbian
[17:08:20 Tue May 17] ~/tarBalls/qt-mobility-opensource-src-1.2.0/examples  $


问:
Using store in interceptors axios? nuxt js
I use interceptors to catch errors in the application. If catch 401 error, I would like to mutate the state of one of my variables. How to use my store inside the axios interceptors? I use axios like plugin in my nuxt-app

答:
// inside my axios configuration
export default function({ $axios, store }) {}```


问:
How to calculate the percentage of different values in same column and group by month of current year?
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

```<code>    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)
</code>```

I want output like this

```<code>month percentage

    1       75%
    2       50%
</code>```

答:
http://sqlfiddle.com/#!9/179518/76

This is more simple sql

Select year(service_date), month(service_date), sum(sla_osla = "sla")/ count(*) * 100 FROM orders group by year(service_date), month(service_date)

I've also grouped by year here.

Edit if you want the percent sign etc then use this

http://sqlfiddle.com/#!9/179518/82

Body:
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)

I want output like this

month percentage

    1       75%
    2       50%