问:
How to increase the compile sdk version
Actually,the minCompileSdk is 31, but the minSdkVersionis significantly lower.  I have to increase thecompileSdkof my project  .
I got to know about it by looking at the this error,
Also the link to the above explanation,this.

So I wanted to know how to increase the compileSdk of my project.

```<code>What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> Multiple task action failures occurred:
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.window:window-java:1.0.0-beta04.
        AAR metadata file: /home/manish/.gradle/caches/transforms-2/files-2.1/625039eaad011f884ddd84f857a44b7f/jetified-window-java-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.window:window:1.0.0-beta04.
        AAR metadata file: /home/manish/.gradle/caches/transforms-2/files-2.1/a78fdf90e4c1f8464b19895cfb365f3f/jetified-window-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties.
</code>```

答:
you can find the compileSdkVersion under: android > app > build.gradle</p>
```<code>android {

  compileSdkVersion 31

  ...

}
</code>```

Title: How to increase the compile sdk version

Body:
Actually,the minCompileSdk is 31, but the minSdkVersionis significantly lower.  I have to increase thecompileSdkof my project  .
I got to know about it by looking at the this error,
Also the link to the above explanation,this.

So I wanted to know how to increase the compileSdk of my project.

What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> Multiple task action failures occurred:
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.window:window-java:1.0.0-beta04.
        AAR metadata file: /home/manish/.gradle/caches/transforms-2/files-2.1/625039eaad011f884ddd84f857a44b7f/jetified-window-java-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties.
   > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
      > The minCompileSdk (31) specified in a
        dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
        is greater than this module's compileSdkVersion (android-30).
        Dependency: androidx.window:window:1.0.0-beta04.
        AAR metadata file: /home/manish/.gradle/caches/transforms-2/files-2.1/a78fdf90e4c1f8464b19895cfb365f3f/jetified-window-1.0.0-beta04/META-INF/com/android/build/gradle/aar-metadata.properties.

Body:
you can find the compileSdkVersion under: android > app > build.gradle

android {

  compileSdkVersion 31

  ...

}


来源: stackexchange

问:
Iterate over a union
I have such enum/range:

period: 'UTD' | 'EOM' | 'ETM'

I want to iterate through all options in select:

```<code><select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
    >
        <ng-container *ngFor="let e of period">
            <option [value]="e" [selected]="e === period">
                {{ e }}
            </option>
        </ng-container>
    </select>
</code>```

I need to get HTML  with option per available enum in period range:

UTD
EOM
ETM

How is that possible please?

答:
Thanks to Matthieu Riegler's answer, it works. I had a little pain to put working in component so here is a whole sample:

```<code>const Periods = ['UTD', 'EOM', 'ETM'] as const;
type Period = typeof Periods[number];

@Component({
    selector: 'app-input-date',
    templateUrl: './input-date.component.html',
    styleUrls: ['./input-date.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputDateComponent implements OnInit,  Validator, ControlValueAccessor {

    period: Period;
    periods = Periods;
...
</code>```

and in HTML:

```<code><select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
        [disabled]="disabled"
    >
        <ng-container *ngFor="let e of periods">
            <option [value]="e" [selected]="e === period">
                {{
</code>```

ContentLicense: CC BY-SA 4.0

Title: Iterate over a union

Body:
I have such enum/range:

period: 'UTD' | 'EOM' | 'ETM'

I want to iterate through all options in select:

<select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
    >
        <ng-container *ngFor="let e of period">
            <option [value]="e" [selected]="e === period">
                {{ e }}
            </option>
        </ng-container>
    </select>

I need to get HTML  with option per available enum in period range:

UTD
EOM
ETM

How is that possible please?

Body:
Thanks to Matthieu Riegler's answer, it works. I had a little pain to put working in component so here is a whole sample:

const Periods = ['UTD', 'EOM', 'ETM'] as const;
type Period = typeof Periods[number];

@Component({
    selector: 'app-input-date',
    templateUrl: './input-date.component.html',
    styleUrls: ['./input-date.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputDateComponent implements OnInit,  Validator, ControlValueAccessor {

    period: Period;
    periods = Periods;
...

and in HTML:

<select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
        [disabled]="disabled"
    >
        <ng-container *ngFor="let e of periods">
            <option [value]="e" [selected]="e === period">
                {{


问:
How to solve TypeError (Cannot set properties of undefined) when assigning a service variable
What I'm trying to do is assigning the value of a select form (dropdown) to a variable in a service, because I need this variable across components.

dropdown.component.html:

```<code><mat-form-field>
<mat-select [(ngModel)]="selectedValue"  (ngModelChange)='onChange()' placeholder="select ticker">
    <mat-option *ngFor="let t of tickers" [value]="t">{{t}}</mat-option>
</mat-select>
</mat-form-field>
</code>```

dropdown.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;
  private DfParams!: LoadDfParamsService;

  constructor() { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}
</code>```

LoadDfParamsService:

```<code>import { Injectable } from '@angular/core';

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

  public ticker!: string;

  constructor() { }
}
</code>```

The variable selectedValue will be updated succesful  in dropdown.component.ts

But by trying to assign the variable of the service

```<code>this.DfParams.ticker = this.selectedValue;
</code>```

I get this error:

```<code>core.mjs:6485 ERROR TypeError: Cannot set properties of undefined (setting 'ticker')
    at DropdownComponent.onChange (dropdown.component.ts:21:25)
    at DropdownComponent_Template_mat_select_ngModelChange_1_listener (dropdown.component.html:2:59)
    at executeListenerWithErrorHandling (core.mjs
</code>```

How can I solve this?

答:
Since angular is using dependency injection, you need to inject the service through the constructor or the setters.

Example injecting the service in the constructor

```<code>import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;

  constructor(private DfParams: LoadDfParamsService) { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}
</code>```

Looking forward to hearing back from you on whether this resolved the issue

Body:
What I'm trying to do is assigning the value of a select form (dropdown) to a variable in a service, because I need this variable across components.

dropdown.component.html:

<mat-form-field>
<mat-select [(ngModel)]="selectedValue"  (ngModelChange)='onChange()' placeholder="select ticker">
    <mat-option *ngFor="let t of tickers" [value]="t">{{t}}</mat-option>
</mat-select>
</mat-form-field>

dropdown.component.ts:

import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;
  private DfParams!: LoadDfParamsService;

  constructor() { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}

LoadDfParamsService:

import { Injectable } from '@angular/core';

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

  public ticker!: string;

  constructor() { }
}

The variable selectedValue will be updated succesful  in dropdown.component.ts

But by trying to assign the variable of the service

this.DfParams.ticker = this.selectedValue;

I get this error:

core.mjs:6485 ERROR TypeError: Cannot set properties of undefined (setting 'ticker')
    at DropdownComponent.onChange (dropdown.component.ts:21:25)
    at DropdownComponent_Template_mat_select_ngModelChange_1_listener (dropdown.component.html:2:59)
    at executeListenerWithErrorHandling (core.mjs

How can I solve this?

Body:
Since angular is using dependency injection, you need to inject the service through the constructor or the setters.

Example injecting the service in the constructor

import { Component, OnInit } from '@angular/core';
import {LoadDfParamsService} from '../../services/load-df-params.service';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {

  tickers = ["BTC-PERP", "ETH-PERP", "ATOM-PERP"];

  public selectedValue!:string;

  constructor(private DfParams: LoadDfParamsService) { }

  ngOnInit(): void {
  }
  onChange() {
    this.DfParams.ticker = this.selectedValue;
    //console.log(this.DfParams)
  }
}

Looking forward to hearing back from you on whether this resolved the issue


问:
The difference between two dates
I have been writing some queries about SQL Server in order to learn.

I wonder that how can I get the difference of today between 90 days ago in a SQL query?

答:
You want DATEADD, not DATEDIFF, and you need to decide whether you need 90 days ago:

```<code>SELECT DATEADD(day,-90,CURRENT_TIMESTAMP)
</code>```

or 3 months ago:

```<code>SELECT DATEADD(month,-3,CURRENT_TIMESTAMP)
</code>```

ContentLicense: CC BY-SA 3.0

Title: The difference between two dates

Body:
You want DATEADD, not DATEDIFF, and you need to decide whether you need 90 days ago:

SELECT DATEADD(day,-90,CURRENT_TIMESTAMP)

or 3 months ago:

SELECT DATEADD(month,-3,CURRENT_TIMESTAMP)


问:
Flattening Hierarchy on parent and child id in python
I have 2 columns that correlate to supervisory hierarchy ids, the one is the parent and the other is the child. So imagine the parent would start with the CEO and then would have a child id such as the chief marketing officer or any of the CEOs direct reports. I'm trying to build out the entire sup org hierarchy based on these two columns.

```<code>Sup Org Name | superior org ID.  | sup org ID
CEO          |                   | 111
CPO          | 111               | 222
CTO          | 111               | 221
Engineering  | 221               | 223
PM           | 222               | 224
Backend Dev. | 223               | 228
</code>```

My goal would be create the hierarchy across multiple columns so we can build out the whole hierarchy

```<code>Level 1. | Level 2 | Level 3 | Level 4
111      | 222     | 224
111      | 221     | 223
111      | 221     | 223     | 228
</code>```

And so on.

I'd also like to see the above with the sup org name replaced for the id. Having it both ways is helpful for my data.

I've tried doing a lot of self-joins but there has to be a cleaner way...

答:
With the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "name": {
            0: "CEO",
            1: "CPO",
            2: "CTO",
            3: "Engineering",
            4: "PM",
            5: "Backend_Dev",
            6: "COO",
        },
        "ID": {0: 111, 1: 222, 2: 221, 3: 223, 4: 224, 5: 228, 6: 220},
        "superior_ID": {0: "", 1: 111, 2: 111, 3: 221, 4: 222, 5: 223, 6: 111},
    }
)
```
<p>You could try this:</p>
<pre class="lang-py prettyprint-override"><code># Setup
df = df.sort_values(by=["superior_ID", "ID"]).reset_index(drop=True)
highest_ID = df.loc[df["superior_ID"] == "", "ID"].values[0]
number_of_paths = df["superior_ID"].value_counts()[highest_ID]
paths = {i + 1: [] for i in range(number_of_paths)}

# Iterate to find all paths (111/222/224 is one path)
for i, row in df.iterrows():
    if row["superior_ID"] == highest_ID:
        paths[i + 1].append(highest_ID)
        paths[i + 1].append(row["ID"])
        continue
    for path in paths.values():
        if row["superior_ID"] in path:
            path.append(row["ID"])

# Create new df concatenating found paths as rows
new_df = pd.DataFrame()
for path in paths.values():
    s = pd.Series(path)
    new_df = pd.concat([new_df, s], axis=1)

# Transpose and cleanup
new_df = (
    new_df
    .T
    .pipe(lambda x: x.iloc[x.isna().sum(axis=1).mul(-1).argsort()])
    .fillna(999)
    .astype(int)
    .pipe(lambda x: x.set_axis([f"level_{i+1}" for i in x.columns], axis="columns"))
    .replace(999, "")
    .reset_index(drop=True)
)
</code>```

And so:

print(new_df)
# Output
   level_1  level_2 level_3 level_4
0      111      220
1      111      222     224
2      111      221     223     228
```

Body:
I have 2 columns that correlate to supervisory hierarchy ids, the one is the parent and the other is the child. So imagine the parent would start with the CEO and then would have a child id such as the chief marketing officer or any of the CEOs direct reports. I'm trying to build out the entire sup org hierarchy based on these two columns.

Sup Org Name | superior org ID.  | sup org ID
CEO          |                   | 111
CPO          | 111               | 222
CTO          | 111               | 221
Engineering  | 221               | 223
PM           | 222               | 224
Backend Dev. | 223               | 228

My goal would be create the hierarchy across multiple columns so we can build out the whole hierarchy

Level 1. | Level 2 | Level 3 | Level 4
111      | 222     | 224
111      | 221     | 223
111      | 221     | 223     | 228

And so on.

I'd also like to see the above with the sup org name replaced for the id. Having it both ways is helpful for my data.

I've tried doing a lot of self-joins but there has to be a cleaner way...

Body:
With the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "name": {
            0: "CEO",
            1: "CPO",
            2: "CTO",
            3: "Engineering",
            4: "PM",
            5: "Backend_Dev",
            6: "COO",
        },
        "ID": {0: 111, 1: 222, 2: 221, 3: 223, 4: 224, 5: 228, 6: 220},
        "superior_ID": {0: "", 1: 111, 2: 111, 3: 221, 4: 222, 5: 223, 6: 111},
    }
)

You could try this:

# Setup
df = df.sort_values(by=["superior_ID", "ID"]).reset_index(drop=True)
highest_ID = df.loc[df["superior_ID"] == "", "ID"].values[0]
number_of_paths = df["superior_ID"].value_counts()[highest_ID]
paths = {i + 1: [] for i in range(number_of_paths)}

# Iterate to find all paths (111/222/224 is one path)
for i, row in df.iterrows():
    if row["superior_ID"] == highest_ID:
        paths[i + 1].append(highest_ID)
        paths[i + 1].append(row["ID"])
        continue
    for path in paths.values():
        if row["superior_ID"] in path:
            path.append(row["ID"])

# Create new df concatenating found paths as rows
new_df = pd.DataFrame()
for path in paths.values():
    s = pd.Series(path)
    new_df = pd.concat([new_df, s], axis=1)

# Transpose and cleanup
new_df = (
    new_df
    .T
    .pipe(lambda x: x.iloc[x.isna().sum(axis=1).mul(-1).argsort()])
    .fillna(999)
    .astype(int)
    .pipe(lambda x: x.set_axis([f"level_{i+1}" for i in x.columns], axis="columns"))
    .replace(999, "")
    .reset_index(drop=True)
)

And so:

print(new_df)
# Output
   level_1  level_2 level_3 level_4
0      111      220
1      111      222     224
2      111      221     223     228


问:
How to retrieve JSON Response from a javax.ws.rs.core.Response response?
I am making a request to an API and getting a response status code of 200.

Response of the api includes a json response.

```<code>import javax.ws.rs.core.Response;

Response response = webclient.post(SomeReqString);
</code>```

How can I retrieve the json response as string from the web client response?

答:
You could try</p>
```<code>String responseAsString = response.getEntity().toString();
</code>```

Body:
I am making a request to an API and getting a response status code of 200.

Response of the api includes a json response.

import javax.ws.rs.core.Response;

Response response = webclient.post(SomeReqString);

How can I retrieve the json response as string from the web client response?

Body:
You could try

String responseAsString = response.getEntity().toString();


问:
TypeError: create_int(): incompatible function arguments
I've Been Recently Learning Computer Vision using python, and when making a hand detector project, I encountered this error :-

```<code>Traceback (most recent call last):
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 64, in <module>
main()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 41, in main
detector = handDetector()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 13, in __init__
self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
self.trackCon)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solutions\hands.py", line 114, in __init__
super().__init__(
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 258, in __init__
self._input_side_packets = {
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 259, in <dictcomp>
name: self._make_packet(self._side_input_type_info[name], data)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 513, in _make_packet
return getattr(packet_creator, 'create_' + packet_data_type.value)(data)
TypeError: create_int(): incompatible function arguments. The following argument types
are supported:
1. (arg0: int) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5
[ WARN:0] global D:\a\opencv-python\opencv-
python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-
 namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
</code>```

And I tried Very Much Debugging it, But Not Successfull :(, So Please Help me, Here's The Code That I've Written:-

```<code>import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands = 2, detectionCon=0.5, trackCon = 0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
                                        self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

def findHands(self, img, draw=True):
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = self.hands.process(imgRGB)
    # print(results.multi_hand_landmarks)

    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            if draw:
                self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
    return img

            # for id, lm in enumerate(handLms.landmark):
            #     # print(id, lm)
            #     h, w, c = img.shape
            #     cx, cy = int(lm.x*w), int(lm.y*h)
            #     print(id, cx, cy)
            #     # if id == 4:
            #     cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()

while True:
    success, img = cap.read()
    img = detector.findHands(img)

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)),(10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (255,0,255),3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

if __name__ == "__main__":
    main()
</code>```

I've Tried Making A Class of Hand Detector, Which Does the same thing to detect hand but we can also use it in our other files, That's why I've written this code, and encountered this issue!

答: It's a problem of indentation since findHands() needs to be part of the class handDetector(). So just tab findHands() and it should work</p>

Body:
I've Been Recently Learning Computer Vision using python, and when making a hand detector project, I encountered this error :-

Traceback (most recent call last):
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 64, in <module>
main()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 41, in main
detector = handDetector()
File "c:\Users\idhant\OneDrive - 007lakshya\Idhant\Programming\Projects\MY MACHINE
LEARNING PROJECTS\Hand Tracking Module.py", line 13, in __init__
self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
self.trackCon)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solutions\hands.py", line 114, in __init__
super().__init__(
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 258, in __init__
self._input_side_packets = {
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 259, in <dictcomp>
name: self._make_packet(self._side_input_type_info[name], data)
File "C:\Users\idhant\AppData\Roaming\Python\Python39\site-
packages\mediapipe\python\solution_base.py", line 513, in _make_packet
return getattr(packet_creator, 'create_' + packet_data_type.value)(data)
TypeError: create_int(): incompatible function arguments. The following argument types
are supported:
1. (arg0: int) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5
[ WARN:0] global D:\a\opencv-python\opencv-
python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-
 namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

And I tried Very Much Debugging it, But Not Successfull :(, So Please Help me, Here's The Code That I've Written:-

import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands = 2, detectionCon=0.5, trackCon = 0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon,
                                        self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

def findHands(self, img, draw=True):
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = self.hands.process(imgRGB)
    # print(results.multi_hand_landmarks)

    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            if draw:
                self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
    return img

            # for id, lm in enumerate(handLms.landmark):
            #     # print(id, lm)
            #     h, w, c = img.shape
            #     cx, cy = int(lm.x*w), int(lm.y*h)
            #     print(id, cx, cy)
            #     # if id == 4:
            #     cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()

while True:
    success, img = cap.read()
    img = detector.findHands(img)

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)),(10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (255,0,255),3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

if __name__ == "__main__":
    main()

I've Tried Making A Class of Hand Detector, Which Does the same thing to detect hand but we can also use it in our other files, That's why I've written this code, and encountered this issue!


问:
Saving JSON into MySQL using PHP overwrites rather than adds a new sub array
I'm trying to save a json array into a MySQL field using PHP. The idea is that when someone submits a new comment, the comment is added into a json array of all comments and saved into the database as a multidimensional array. I've searched StackOverflow - but when any new comment submitted it just overwrites the existing array - rather than adding to it. And I can't see what I'm doing wrong. Here is my code:

The form has a hidden field, where I echo the json from the database:

```<code><input type="hidden" name="json" value=" <?php echo json_encode($item->issue_comments);?> "/>
</code>```

Then, when the form submits using POST, I have the following code to decode and add the new sub array (date/name/comment) into the main array and reencode.

```<code>$comments = json_decode($_POST['json'], true);
$comments['comment'][] = array('date'=>$comment_date, 'name'=>$issue_commenter, 'comment'=>$_POST['issue_comment']);
$json = json_encode($comments);
</code>```

This is what is saved in the database:

```<code>{"comment": [{"date": "2022-02-12 18:02:02", "name": 1, "comment": "comment text"}]}
</code>```

Thanks for any help

答:
Your application design requires a transactional read - modify - write cycle to the database column containing the JSON. If you will enlarge the JSON array in a column of the table, you'll need something like this.

START TRANSACTION;
SELECT json_column FROM tbl WHERE id=? FOR UPDATE;
```
<p>Then you'll modify the JSON data in your php app. Then you'll do, to the database:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE tbl SET json_column = ? WHERE id=?;
COMMIT;
</code>```

If you use the design where you stash the JSON object to be modified in browser state (in your hidden field) and two users of your app update the same ticket concurrently, one of the comments, at least, will get lost.

Bill K's suggestion of a separate comments table gets you out of this possible problem. You can do INSERTs concurrently with no risk of data loss.

Body:
I'm trying to save a json array into a MySQL field using PHP. The idea is that when someone submits a new comment, the comment is added into a json array of all comments and saved into the database as a multidimensional array. I've searched StackOverflow - but when any new comment submitted it just overwrites the existing array - rather than adding to it. And I can't see what I'm doing wrong. Here is my code:

The form has a hidden field, where I echo the json from the database:

<input type="hidden" name="json" value=" <?php echo json_encode($item->issue_comments);?> "/>

Then, when the form submits using POST, I have the following code to decode and add the new sub array (date/name/comment) into the main array and reencode.

$comments = json_decode($_POST['json'], true);
$comments['comment'][] = array('date'=>$comment_date, 'name'=>$issue_commenter, 'comment'=>$_POST['issue_comment']);
$json = json_encode($comments);

This is what is saved in the database:

{"comment": [{"date": "2022-02-12 18:02:02", "name": 1, "comment": "comment text"}]}

Thanks for any help

Body:
Your application design requires a transactional read - modify - write cycle to the database column containing the JSON. If you will enlarge the JSON array in a column of the table, you'll need something like this.

START TRANSACTION;
SELECT json_column FROM tbl WHERE id=? FOR UPDATE;

Then you'll modify the JSON data in your php app. Then you'll do, to the database:

UPDATE tbl SET json_column = ? WHERE id=?;
COMMIT;

If you use the design where you stash the JSON object to be modified in browser state (in your hidden field) and two users of your app update the same ticket concurrently, one of the comments, at least, will get lost.

Bill K's suggestion of a separate comments table gets you out of this possible problem. You can do INSERTs concurrently with no risk of data loss.


答:
Just inject the service into the constructor</p>
```<code>constructor(private DfParams: LoadDfParamsService) { }
</code>```

Title: How to solve TypeError (Cannot set properties of undefined) when assigning a service variable

Body:
Just inject the service into the constructor

constructor(private DfParams: LoadDfParamsService) { }


问:
How might I store in a variable the string read by fgets() without leaking memory?
I want the following code to accomplish to store the content of the file it reads in a variable
content without leaking memory:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1);
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1);
    return result;
}

int main() {

char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"r");
char line[200];
char * content = "";

if (archivo == NULL)
        exit(1);
else {

fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
        printf("\nThe content of %s is:\n", path);
        while (feof(archivo) == 0) {
        fgets(line, 200, archivo); //reads one line at a time - comment out the while loop to find out
        content = concat(content, line);
       //free(content);//No leaks but no content either
            }
          }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
      fclose(archivo);
      exit(0);
        }
      }
fclose(archivo);
puts(content);
free(content);
return 0;
}
</code>```

much the same as this code that uses fread() does it:

```<code>#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <sys/types.h>

int main() {

int count;
char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"rb");

 if (archivo == NULL) {
     puts("Does not exist.");
     exit(1);
       }
 else {

  fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  char contenido[sz];
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
    count = fread(&contenido, 10 * sizeof(char), sz, archivo);//reads 10 characters at a time.
    }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
        }
  fclose(archivo);
  // Printing data to check validity
  printf("Data read from file: %s \n", contenido);
  printf("Elements read: %i, read %li byte at a time.\n", count, 10 * sizeof(char));

 }
return 0;
}
</code>```

The first code snippet leaks memory, as evidenced by valgrind:

```<code>...
total heap usage: 44 allocs, 4 frees, 23,614 bytes allocated
...
==404853== LEAK SUMMARY:
==404853==    definitely lost: 17,198 bytes in 40 blocks
...
</code>```

When I attempt to prevent such leak by executing free() within the while loop I get no value stored in content. How might I store the string read by fgets without leaking memory?

答:
You knew what you needed to do but didnt do it right

```<code>    content = concat(content, line);
   //free(content);//No leaks but no content either
</code>```

you need to keep the old content pointer so you can delete it after you create a new one

```<code>    char *oldc = content;
    content = concat(content, line);
    free(oldc);
</code>```

Body:
I want the following code to accomplish to store the content of the file it reads in a variable
content without leaking memory:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1);
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1);
    return result;
}

int main() {

char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"r");
char line[200];
char * content = "";

if (archivo == NULL)
        exit(1);
else {

fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
        printf("\nThe content of %s is:\n", path);
        while (feof(archivo) == 0) {
        fgets(line, 200, archivo); //reads one line at a time - comment out the while loop to find out
        content = concat(content, line);
       //free(content);//No leaks but no content either
            }
          }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
      fclose(archivo);
      exit(0);
        }
      }
fclose(archivo);
puts(content);
free(content);
return 0;
}

much the same as this code that uses fread() does it:

#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <sys/types.h>

int main() {

int count;
char path[] = "/home/jim/trackers_best.txt";
FILE *archivo = fopen(path,"rb");

 if (archivo == NULL) {
     puts("Does not exist.");
     exit(1);
       }
 else {

  fseek(archivo, 0L, SEEK_END);
  int sz = ftell(archivo);
  char contenido[sz];
  fseek(archivo, 0L, SEEK_SET);
  if (sz < pow(10, 7) ) {
    count = fread(&contenido, 10 * sizeof(char), sz, archivo);//reads 10 characters at a time.
    }
  else {
      puts("File take up more than 10 MBs, I refuse to read it.");
        }
  fclose(archivo);
  // Printing data to check validity
  printf("Data read from file: %s \n", contenido);
  printf("Elements read: %i, read %li byte at a time.\n", count, 10 * sizeof(char));

 }
return 0;
}

The first code snippet leaks memory, as evidenced by valgrind:

...
total heap usage: 44 allocs, 4 frees, 23,614 bytes allocated
...
==404853== LEAK SUMMARY:
==404853==    definitely lost: 17,198 bytes in 40 blocks
...

When I attempt to prevent such leak by executing free() within the while loop I get no value stored in content. How might I store the string read by fgets without leaking memory?

Body:
You knew what you needed to do but didnt do it right

    content = concat(content, line);
   //free(content);//No leaks but no content either

you need to keep the old content pointer so you can delete it after you create a new one

    char *oldc = content;
    content = concat(content, line);
    free(oldc);


问:
Python "ModuleNotFoundError"
im working the first time with Python and want to rebuild the https://github.com/riffnshred/nhl-led-scoreboard to an nfl scoreboard (i know, there is a fantastic work on github, but i want to get all the great features the nhl script delivers with it).

My problem is, that my debugger says that the file "scoreboard_config.py" cannot found the "validate_json.py" at the nfl_setup directory.

My Tree is 1:1 like the nhl project, im only changed the names from nhl to nfl.

```<code>...
src/
   api/
   boards/
   config/
   data/
        -scoreboard_config.py
   images/
   nfl_api/ (old nhl_api)
   nfl_setup/ (old nhl_setup)
        -validate_json.py
   renderer/
   sbio/
...
</code>```

My code at the scoreboard_config.py

```<code>from utils import get_file
from data.layout import Layout
from data.colors import Color
from config.main import Config
from nfl_setup.validate_json import validateConf

# oldCode
# from nhl_setup.validate_json import validateConf

import json
import os
import sys
import debug

...
</code>```

So you can see, there is the same Project-Tree like the nhl Setup (where it's work perfect)...

Thanks everyone for your help!

答: Just fixed it by myself - i addet __init__.py to the nfl_source Directory.

Title: Python "ModuleNotFoundError"

Body:
im working the first time with Python and want to rebuild the https://github.com/riffnshred/nhl-led-scoreboard to an nfl scoreboard (i know, there is a fantastic work on github, but i want to get all the great features the nhl script delivers with it).

My problem is, that my debugger says that the file "scoreboard_config.py" cannot found the "validate_json.py" at the nfl_setup directory.

My Tree is 1:1 like the nhl project, im only changed the names from nhl to nfl.

...
src/
   api/
   boards/
   config/
   data/
        -scoreboard_config.py
   images/
   nfl_api/ (old nhl_api)
   nfl_setup/ (old nhl_setup)
        -validate_json.py
   renderer/
   sbio/
...

My code at the scoreboard_config.py

from utils import get_file
from data.layout import Layout
from data.colors import Color
from config.main import Config
from nfl_setup.validate_json import validateConf

# oldCode
# from nhl_setup.validate_json import validateConf

import json
import os
import sys
import debug

...

So you can see, there is the same Project-Tree like the nhl Setup (where it's work perfect)...

Thanks everyone for your help!


问:
Add multiple subtitles to video with ffmpeg-python
I am trying to add multiple subtitles (not burned) to a video file with ffmpeg-python. I have this ffmpeg command:

```<code>ffmpeg -i input.mp4 -f srt \
-i "subs/en/en_srt_sub.srt" \
-i "subs/fr/fr_srt_sub" \
-map 0:0 -map 0:1 -map 1:0 -map 2:0 \
-c:v copy -c:a copy \
-c:s srt -c:s srt \
-metadata:s:s:0 language=en -metadata:s:s:0 title=English \
-metadata:s:s:1 language=fr -metadata:s:s:1 title=French \
output.mkv
</code>```

Is there a way to do this with the ffmpeg-python module or do I just have to use string formatting and subprocess.

答:
The same command can be translated to something like this:

#Import library
import ffmpeg

#Define vars
video="input.mp4"
sub1="subs/en/en_srt_sub.srt"
l1="en"
t1="English"
sub2="subs/fr/fr_srt_sub.srt"
l2="fr"
t2="French"
output_file="output.mkv"

#Define input values
input_ffmpeg = ffmpeg.input(video)
input_ffmpeg_sub1 = ffmpeg.input(sub1)
input_ffmpeg_sub2 = ffmpeg.input(sub2)

#Define output file
input_video = input_ffmpeg['v']
input_audio = input_ffmpeg['a']
input_subtitles1 = input_ffmpeg_sub1['s']
input_subtitles2 = input_ffmpeg_sub['s']
output_ffmpeg = ffmpeg.output(
    input_video, input_audio, input_subtitles1, input_subtitles2, output_file,
    vcodec='copy', acodec='copy',
    **{'metadata:s:s:0': "language="+l1, 'metadata:s:s:0': "title="+t1, 'metadata:s:s:1': "language="+l2, 'metadata:s:s:1': "title="+t2 }
)

# If the destination file already exists, overwrite it.
output_ffmpeg = ffmpeg.overwrite_output(output_ffmpeg)

# Print the equivalent ffmpeg command we could run to perform the same action as above.
print(ffmpeg.compile(output_ffmpeg))

# Do it! transcode!
ffmpeg.run(output_ffmpeg)
```

In order to add other stream metadata you can check Custom Filter in the official documentation.

Body:
I am trying to add multiple subtitles (not burned) to a video file with ffmpeg-python. I have this ffmpeg command:

ffmpeg -i input.mp4 -f srt \
-i "subs/en/en_srt_sub.srt" \
-i "subs/fr/fr_srt_sub" \
-map 0:0 -map 0:1 -map 1:0 -map 2:0 \
-c:v copy -c:a copy \
-c:s srt -c:s srt \
-metadata:s:s:0 language=en -metadata:s:s:0 title=English \
-metadata:s:s:1 language=fr -metadata:s:s:1 title=French \
output.mkv

Is there a way to do this with the ffmpeg-python module or do I just have to use string formatting and subprocess.

Body:
The same command can be translated to something like this:

#Import library
import ffmpeg

#Define vars
video="input.mp4"
sub1="subs/en/en_srt_sub.srt"
l1="en"
t1="English"
sub2="subs/fr/fr_srt_sub.srt"
l2="fr"
t2="French"
output_file="output.mkv"

#Define input values
input_ffmpeg = ffmpeg.input(video)
input_ffmpeg_sub1 = ffmpeg.input(sub1)
input_ffmpeg_sub2 = ffmpeg.input(sub2)

#Define output file
input_video = input_ffmpeg['v']
input_audio = input_ffmpeg['a']
input_subtitles1 = input_ffmpeg_sub1['s']
input_subtitles2 = input_ffmpeg_sub['s']
output_ffmpeg = ffmpeg.output(
    input_video, input_audio, input_subtitles1, input_subtitles2, output_file,
    vcodec='copy', acodec='copy',
    **{'metadata:s:s:0': "language="+l1, 'metadata:s:s:0': "title="+t1, 'metadata:s:s:1': "language="+l2, 'metadata:s:s:1': "title="+t2 }
)

# If the destination file already exists, overwrite it.
output_ffmpeg = ffmpeg.overwrite_output(output_ffmpeg)

# Print the equivalent ffmpeg command we could run to perform the same action as above.
print(ffmpeg.compile(output_ffmpeg))

# Do it! transcode!
ffmpeg.run(output_ffmpeg)

In order to add other stream metadata you can check Custom Filter in the official documentation.


问:
how to run multiple domains (or sub-domain) on one Laravel app
I want to host multiple site with shared pages and functionality but don't want redirection

web.php

```<code>Route::get('/', function () {
    return "site 1";
});

Route::domain('site2.test')->group(function () {
    Route::get('/', function () {
        return "site 2";
    });
});

</code>```

domain 1 preview

domain 2 preview

C:\Windows\System32\drivers\etc\hosts

```<code>127.0.0.1 site1.test
127.0.0.1 site2.test
</code>```

C:\xampp\apache\conf\extra\httpd-vhosts.conf

```<code><VirtualHost *:80>
    ServerAdmin admin@media.com
    DocumentRoot "C:/xampp/htdocs/multidomain/public"
    ServerName  site1.test
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin admin@media.com
    DocumentRoot "C:/xampp/htdocs/multidomain/public"
    ServerName  site2.test
</VirtualHost>
</code>```

答:
"In order to ensure your subdomain routes are reachable, you should register subdomain routes before registering root domain routes. This will prevent root domain routes from overwriting subdomain routes which have the same URI path." (source)

You'll need to just move your Route::domain() to the top.

Body:
I want to host multiple site with shared pages and functionality but don't want redirection

web.php

Route::get('/', function () {
    return "site 1";
});

Route::domain('site2.test')->group(function () {
    Route::get('/', function () {
        return "site 2";
    });
});

domain 1 preview

domain 2 preview

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 site1.test
127.0.0.1 site2.test

C:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin admin@media.com
    DocumentRoot "C:/xampp/htdocs/multidomain/public"
    ServerName  site1.test
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin admin@media.com
    DocumentRoot "C:/xampp/htdocs/multidomain/public"
    ServerName  site2.test
</VirtualHost>


问:
How to fade-in image transition on page load, using flutter?
I don't believe I am asking such a simple question.

I try to change opacity in initState() but it does not have an effect.

How do I trigger setState if I don't use a button?

Here is the DARTPAD.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: LogoFade(),
    );
  }
}

class LogoFade extends StatefulWidget {
  @override
  createState() => LogoFadeState();
}

class LogoFadeState extends State<LogoFade> {
  double opacityLevel = 0.0;

  void changeOpacity() {
    setState(() => opacityLevel = 1.0);
  }

  @override
  void initState() {
    changeOpacity();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
// changeOpacity();
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AnimatedOpacity(
          opacity: opacityLevel,
          duration: Duration(seconds: 6),
          child: FlutterLogo(
            size: 200,
          ),
        ),
      ],
    );
  }
}
```
<p><strong>I just want a simple <strong>FadeIn</strong> effect like Animate.css library.</strong> Like we make in web with the example below.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade-in-image {
  animation: fadeIn 6s;

}
@keyframes fadeIn {
  0% {opacity:0;}
  100% {opacity:1;}
}</code>```

```

答:
In flutter app life cycle intiState() called before the Widget build(BuildContext context) called.So technically your opacity varriable always initialize with 1.You can use FutureDelay to see the effect of this animation.

```<code>void changeOpacity() async{
await Future.delayed(const Duration(milliseconds: 2000));
setState(() => opacityLevel = 1.0);
}

 @override
 void initState() {
 changeOpacity();
 super.initState();
}
</code>```

Body:
I don't believe I am asking such a simple question.

I try to change opacity in initState() but it does not have an effect.

How do I trigger setState if I don't use a button?

Here is the DARTPAD.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: LogoFade(),
    );
  }
}

class LogoFade extends StatefulWidget {
  @override
  createState() => LogoFadeState();
}

class LogoFadeState extends State<LogoFade> {
  double opacityLevel = 0.0;

  void changeOpacity() {
    setState(() => opacityLevel = 1.0);
  }

  @override
  void initState() {
    changeOpacity();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
// changeOpacity();
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AnimatedOpacity(
          opacity: opacityLevel,
          duration: Duration(seconds: 6),
          child: FlutterLogo(
            size: 200,
          ),
        ),
      ],
    );
  }
}

I just want a simple FadeIn effect like Animate.css library. Like we make in web with the example below.

.fade-in-image {
  animation: fadeIn 6s;

}
@keyframes fadeIn {
  0% {opacity:0;}
  100% {opacity:1;}
}

Body:
In flutter app life cycle intiState() called before the Widget build(BuildContext context) called.So technically your opacity varriable always initialize with 1.You can use FutureDelay to see the effect of this animation.

void changeOpacity() async{
await Future.delayed(const Duration(milliseconds: 2000));
setState(() => opacityLevel = 1.0);
}

 @override
 void initState() {
 changeOpacity();
 super.initState();
}


问:
Include local .json file in Eclipse Android project
I have a local .json file. I don't want it to be on a server, I just want it to be included in my app. I tried to paste it directly into Eclipse in my project, but I got a FileNotFoundException, I also tried to paste it in the workspace folder in Windows Explorer/Finder and got the same exception. Where should I put it?

Thanks!

答: Under /assets in your project folder. If you don't have one, make it.</p>


问:
Execution failed for task ':app:checkDebugAarMetadata

What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.work:work-runtime:2.7.0-rc01.
AAR metadata file: C:\Users\100812.gradle\caches\transforms-2\files-2.1\8fcba37f766c3622d8dbd30df4e98577\work-runtime-2.7.0-rc01\META-INF\com\android\build\gradle\aar-metadata.properties.

答:
you can find the compileSdkVersion under: android > app > build.gradle

```<code>android {

  compileSdkVersion 31

  ...

}
</code>```

Body:
you can find the compileSdkVersion under: android > app > build.gradle

android {

  compileSdkVersion 31

  ...

}


问:
Why is my Angular ngrx not storing data to and retrieving it from the store as expected?
My reducers are registered in the reducer constant of index.ts as shown:

    export const reducers: ActionReducerMap <State> = {
        homeState:HomeReducers,
        productsState:ProductsReducers
    }
```
<p>The reducers are imported into app.module as shown:</p>
<pre class="lang-js prettyprint-override"><code>    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        StoreModule.forRoot(reducers, {}),
      ],
    })
    export class AppModule { }
</code>```

My action function is shown below:

    export const StoreProducts = createAction(
        '[Store Products] Store Products',
        props<{products}>()
     )
```
<p>The action function is called as shown:</p>
<pre class="lang-js prettyprint-override"><code>    this.httpClient.get(`${this.url}/${queryParams}`).pipe(
      tap(products => {
        console.log('ProductsService products', products)
        productsActions.StoreProducts({products})
      })
    ).subscribe();
</code>```

The reducer expected to store the data is shown here:

    export const ProductsReducers = createReducer(initialState,
       on(productsActions.StoreProducts, (state, action) => {
            console.log('action.products', action.products)
            return {
                ...state, products: action.products
            }
        }),
   )
```

The data never reaches the store. I have implemented several other reducers that are working fine.
Is it possible to write debugging statement in the action function?

答:
The Action in NgRx should be dispatched using the store.dispatch function, not by calling it directly.

So you can adjust your code like the following:

constructor(private store: Store) {}

//...
this.httpClient
  .get(`${this.url}/${queryParams}`)
  .pipe(
    tap((products) => {
      console.log('ProductsService products', products);
      // >>>> You can dispatch the any NgRx's actions using store.dispatch function <<<<<
      this.store.dispatch(productsActions.StoreProducts({ products }));
    })
  )
  .subscribe();
}
```

Body:
My reducers are registered in the reducer constant of index.ts as shown:

    export const reducers: ActionReducerMap <State> = {
        homeState:HomeReducers,
        productsState:ProductsReducers
    }

The reducers are imported into app.module as shown:

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        StoreModule.forRoot(reducers, {}),
      ],
    })
    export class AppModule { }

My action function is shown below:

    export const StoreProducts = createAction(
        '[Store Products] Store Products',
        props<{products}>()
     )

The action function is called as shown:

    this.httpClient.get(`${this.url}/${queryParams}`).pipe(
      tap(products => {
        console.log('ProductsService products', products)
        productsActions.StoreProducts({products})
      })
    ).subscribe();

The reducer expected to store the data is shown here:

    export const ProductsReducers = createReducer(initialState,
       on(productsActions.StoreProducts, (state, action) => {
            console.log('action.products', action.products)
            return {
                ...state, products: action.products
            }
        }),
   )

The data never reaches the store. I have implemented several other reducers that are working fine.
Is it possible to write debugging statement in the action function?


问:
How to make PhpStorm/WebStorm scope highlighting look more expressive?
When I first learned Java, I was using an IDE called "BlueJ." It had this feature called "Scope Highlighting" which made it very easy to read blocks of code. See picture below:

As you can see on the first picture, on BlueJ the whole Background of a scope is highlighted with one color.

In PhpStorm or even in most of IDE's today, I get only a highlighting for a scope, which I set the cursor on, and only in a very minimalist way, as you can see on the left side of the picture below:

Is there a way, or a Plugin for PhpStorm out there, to get it to look more like BlueJ's scope Highlighting???

Thanks

edit:

What I've have found out so far:
There is something alike for HTML, (Setting>Editor>General>Appearance:Enable HTML/XML tag tree highlighting:Set opacity higher than 0) Then you will get this:

Something like this for the other languages (PHP, JS,...) would make me really happy :)

答:
Maybe you will also like the VSCode extension "Blockman". It highlights nested code blocks based on curly/square/round brackets, html/xml tags and Python/Yaml indentation. (I am the author of Blockman).
.


问:
Error when I install autoviz on anaconda prompt
I have been trying to install autoviz but every time I try to I get this error message: Failed to build worldcloud and ERROR: Command errored out with exit status 1
Failed to build worldcloud

Can anyone help with this issue.

On a side note I am new to python and I am not sure how/or the best est way to install packages and modules on python so if anyone has any references that are easy to read and helpful I would greatly appreciate it.

答:
According to its pypi page, wordcloud is available as a wheel for several platforms.

As for anaconda, it says:

If you are using conda, you can install from the conda-forge channel:

conda install -c conda-forge wordcloud

Otherwise, you'll have to build it yourself. Which on ms-windows means you'll have to install a C compiler and tools. While not intrinsically difficult, this can be intimidating for people who are new to building C-extensions for Python modules.


问:
How to work around "A catch-all parameter can only appear as the last segment of the route template."
If I have a controller with an action method that uses attribute based routing and declare it like this, all is well:

```<code>    [HttpGet]
    [Route("/dev/info/{*somevalue}")]
    public IActionResult Get(string somevalue) {

        return View();
    }
</code>```

I can route to the above action method for example by specifying a url that ends in /dev/info/hello-world or /dev/info/new-world

However my business requirement is to have a urls that look like this: /dev/hello-world/info or /dev/new-world/info  And there is an endless set of such urls that all need to route to the same action method on the controller.

I thought to set up the attribute based route on the action method as follows:

```<code>    [HttpGet]
    [Route("/dev/{*somevalue}/info/")]
    public IActionResult Get(string somevalue) {

        return View();
    }
</code>```

But when I do that I get the following error as soon as the web project runs:

An unhandled exception occurred while processing the request.
  RouteCreationException: The following errors occurred with attribute routing information:

For action: 'App.SomeController.Get (1-wwwSomeProject)'
  Error: A catch-all parameter can only appear as the last segment of the route template.
  Parameter name: routeTemplate
  Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.GetRouteInfos(IReadOnlyList actions)

There has to be some way to work around this error.  Know a way?

答:
It is possible to achieve this by using the regular expression:

[HttpGet]
[Route(@"/dev/{somevalue:regex(^.*$)}/info/")]
public IActionResult Get(string somevalue)
{
    return View();
}
```

About routing constrain using the regular expressions see in the documentation: Route constraint reference

The regular expression tokens explanation:

Token
Explanation

^
Asserts position at start of a line

.
Matches any character (except for line terminators)

*
Matches the previous token between zero and unlimited times, as many times as possible

$
Asserts position at the end of a line

If it's required to have the “world”suffix in the second segment then add this suffix to the pattern like the following: [Route(@"/dev/{somevalue:regex(^.*world$)}/info/")].

Body:
If I have a controller with an action method that uses attribute based routing and declare it like this, all is well:

    [HttpGet]
    [Route("/dev/info/{*somevalue}")]
    public IActionResult Get(string somevalue) {

        return View();
    }

I can route to the above action method for example by specifying a url that ends in /dev/info/hello-world or /dev/info/new-world

However my business requirement is to have a urls that look like this: /dev/hello-world/info or /dev/new-world/info  And there is an endless set of such urls that all need to route to the same action method on the controller.

I thought to set up the attribute based route on the action method as follows:

    [HttpGet]
    [Route("/dev/{*somevalue}/info/")]
    public IActionResult Get(string somevalue) {

        return View();
    }

But when I do that I get the following error as soon as the web project runs:

An unhandled exception occurred while processing the request.
  RouteCreationException: The following errors occurred with attribute routing information:

For action: 'App.SomeController.Get (1-wwwSomeProject)'
  Error: A catch-all parameter can only appear as the last segment of the route template.
  Parameter name: routeTemplate
  Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.GetRouteInfos(IReadOnlyList actions)

There has to be some way to work around this error.  Know a way?

Body:
It is possible to achieve this by using the regular expression:

[HttpGet]
[Route(@"/dev/{somevalue:regex(^.*$)}/info/")]
public IActionResult Get(string somevalue)
{
    return View();
}

About routing constrain using the regular expressions see in the documentation: Route constraint reference

The regular expression tokens explanation:

Token
Explanation

^
Asserts position at start of a line

.
Matches any character (except for line terminators)

*
Matches the previous token between zero and unlimited times, as many times as possible

$
Asserts position at the end of a line

If it's required to have the “world”suffix in the second segment then add this suffix to the pattern like the following: [Route(@"/dev/{somevalue:regex(^.*world$)}/info/")].


问:
WAP to find the second largest number without using an array in java
I have received a question in my school programming assignment, which goes like this:
Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number.
Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!

```<code>    import java.util.*;
class SecondLargest
{
    public static void main(String args[])
    {
        System.out.println('\u000C'); //used to clear screen
        Scanner y=new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n=y.nextInt();
        System.out.println("Enter number 1");
        int num=y.nextInt();
        int max=num,min=num,temp=num;
        for(int i=2;i<=n;i++)
        {
            System.out.println("Enter number "+i);
            num=y.nextInt();
            if(num>max)
            max=num;
            else if(num<min)
            min=num;

        }
        System.out.println("The largest number is "+max);
        System.out.println("The smallest number is "+min);
    }
}
</code>```

答:
Just make another variable like your min and max variables.</p>
```<code>if (num<max && num >min) {

}
</code>```

Body:
I have received a question in my school programming assignment, which goes like this:
Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number.
Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!

    import java.util.*;
class SecondLargest
{
    public static void main(String args[])
    {
        System.out.println('\u000C'); //used to clear screen
        Scanner y=new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n=y.nextInt();
        System.out.println("Enter number 1");
        int num=y.nextInt();
        int max=num,min=num,temp=num;
        for(int i=2;i<=n;i++)
        {
            System.out.println("Enter number "+i);
            num=y.nextInt();
            if(num>max)
            max=num;
            else if(num<min)
            min=num;

        }
        System.out.println("The largest number is "+max);
        System.out.println("The smallest number is "+min);
    }
}

Body:
Just make another variable like your min and max variables.

if (num<max && num >min) {

}


问:
Categorize data with Vlookup in Google Sheets without the help of a helper table
I want to categorize data in Google Sheets by using array function, without the help of helper tables. I cannot figured out how to put incremented values in an array function. For example, if I have a table like:

Name

cup

cup

pencil

pencil

book

table

I can use a helper table to name each group and use a Vlookup formula to get the below table with the formula,

```<code>vlookup($A1,$D$2:$E$4,2,0)
</code>```

, where $D$2:$E$4 is the reference table.

Name
Group

cup
groupid1

cup
groupid1

pencil
groupid2

pencil
groupid2

book
groupid3

table
groupid4

Instead of the reference table I was wondering if I could use a array function or array in the VLOOKUP formula.

For example something like,

```<code>{unique(A1:A),if(/referance-to-index-1 of unique(A1:A) != 0/,"GROUPID[1 auto-incremented]","" )}
</code>```

So that I get an array like this, please ignore the heading,

Name
Group

cup
groupid1

pencil
groupid2

book
groupid3

table
groupid4

答:
See my comment to your original post.

That being said, here is my guess as to what you mean.

Suppose that your original list is in Sheet1!A2:A. Try this formula in A1 of some other empty sheet:

=ArrayFormula({UNIQUE(FILTER(Sheet1!A2:A,Sheet1!A2:A<>"")),"GROUPID"&SEQUENCE(COUNTA(UNIQUE(Sheet1!A2:A)))})

Body:
I want to categorize data in Google Sheets by using array function, without the help of helper tables. I cannot figured out how to put incremented values in an array function. For example, if I have a table like:

Name

cup

cup

pencil

pencil

book

table

I can use a helper table to name each group and use a Vlookup formula to get the below table with the formula,

vlookup($A1,$D$2:$E$4,2,0)

, where $D$2:$E$4 is the reference table.

Name
Group

cup
groupid1

cup
groupid1

pencil
groupid2

pencil
groupid2

book
groupid3

table
groupid4

Instead of the reference table I was wondering if I could use a array function or array in the VLOOKUP formula.

For example something like,

{unique(A1:A),if(/referance-to-index-1 of unique(A1:A) != 0/,"GROUPID[1 auto-incremented]","" )}

So that I get an array like this, please ignore the heading,

Name
Group

cup
groupid1

pencil
groupid2

book
groupid3

table
groupid4


问:
How to know the number of characters in utf8 string
i want to know is there a simple way to determine the number of characters in UTF8 string.
For example, in windows it can be done by:

converting UTF8 string to wchar_t string

use wcslen function and get result

But I need more simpler and crossplatform solution.

Thanks in advance.

答:
If the string is known to be valid UTF-8, simply take the length of the string in bytes, excluding bytes whose values are in the range 0x80-0xbf:

```<code>size_t i, cnt;
for (cnt=i=0; s[i]; i++) if (s[i]<0x80 || s[i]>0xbf) cnt++;
</code>```

Note that s must point to an array of unsigned char in order for the comparisons to work.

Body:
If the string is known to be valid UTF-8, simply take the length of the string in bytes, excluding bytes whose values are in the range 0x80-0xbf:

size_t i, cnt;
for (cnt=i=0; s[i]; i++) if (s[i]<0x80 || s[i]>0xbf) cnt++;

Note that s must point to an array of unsigned char in order for the comparisons to work.


问:
Why can I click on a link outside of its text element?
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

```<code><div class="nav-list">
       <a class="home_A"href="Home.php">
          <img class="homeIcon" src="photos/icon.png">
       </a>
</div>
</code>```

CSS of the image

```<code>.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}
</code>```

CSS of the  link

```<code>.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}
</code>```

HTML of the  link

```<code><form method="POST" class="signinForm">
<ul>
    <li> <h1 class="signinH1">sign in</h1></li>
    <li> <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required></li>
    <li> <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required></li>
    <li> <input type="submit" value="Log in"class="signinbutton"></li>
    <li><a href="signUp.php">Sign up</a></li>
</ul>

</form>
</code>```

Thanks all.

答:
Assign display: inline-block of course, also use object-fit:contain on  and set the line-height: of  to 1 to 1.25 depending on how your font is setup but there's very little play in the value.

:root {
  font: 1ch/1 'Segoe UI'
}

body {
  font-size: 2ch;
}

a {
  font-size: 2.5rem;
  line-height: 1.15;
}

a,
img {
  display: inline-block;
}

img {
  object-fit: contain;
  width: 3rem;
  height: 3rem;
  margin-bottom: -3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='frame'>

..::Zer00ne::..
  <img src='https://i.ibb.co/Kx33pSY/01.jpg'>
</div></code>```

Body:
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

CSS of the image

.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}

CSS of the  link

.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}

HTML of the  link

<form method="POST" class="signinForm">

sign in

 <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required>

 <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required>

 <input type="submit" value="Log in"class="signinbutton">

Sign up

</form>

Thanks all.

Body:
Assign display: inline-block of course, also use object-fit:contain on <img> and set the line-height: of <a> to 1 to 1.25 depending on how your font is setup but there's very little play in the value.

:root {
  font: 1ch/1 'Segoe UI'
}

body {
  font-size: 2ch;
}

a {
  font-size: 2.5rem;
  line-height: 1.15;
}

a,
img {
  display: inline-block;
}

img {
  object-fit: contain;
  width: 3rem;
  height: 3rem;
  margin-bottom: -3px;
}

<div class='frame'>
  <a class="zOne" href="https://stackoverflow.com/users/2813224/zer00ne">
..::Zer00ne::..
  <img src='https://i.ibb.co/Kx33pSY/01.jpg'></a>
</div>


问:
Preserving the order of user-provided parameters with Python Click
I am trying to port an argparse command-line interface (CLI) to click. This CLI must maintain the order in which parameters are provided by the user. With the argparse version, I used this StackOverflow answer to maintain order. With click, I am not sure how to do this.

I tried creating a custom callback to store params and values in order, but if a parameter is used multiple times, the callback fires the first time it sees a matching parameter.

import click
import typing

class OrderParams:
    _options: typing.List[typing.Tuple[click.Parameter, typing.Any]] = []

    @classmethod
    def append(cls, ctx: click.Context, param: click.Parameter, value: typing.Any):
        cls._options.append((param, value))

@click.command()
@click.option("--animal", required=True, multiple=True, callback=OrderParams.append)
@click.option("--thing", required=True, multiple=True, callback=OrderParams.append)
def cli(*, animal, thing):
    click.echo("Got this order of parameters:")
    for param, value in OrderParams._options:
        print("  ", param.name, value)

if __name__ == "__main__":
    cli()
```
<h3>Current output:</h3>
```$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
   animal ('cat', 'dog')
   thing ('rock',)
```
<h3>Desired output:</h3>
```$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
   animal 'cat'
   thing 'rock'
   animal 'dog'
```

The click documentation describes the behavior that a callback is called once the first time a parameter is encountered, even if the parameter is used multiple times.

If an option or argument is split up on the command line into multiple places because it is repeated [...] the callback will fire based on the position of the first option.

答:
@StephenRauch's answer is correct but it misses one minor detail. Calling the cli function i.e. the script without any arguments will result in an error:

type(self)._options.append((param, opts[param.name].pop(0)))
AttributeError: 'NoneType' object has no attribute 'pop'
```
<p>The fix for this is checking <code>opts[param.name]</code> if it is not <code>None</code>. The modified <code>OrderedParamsCommand</code> looks like:</p>
<pre class="lang-py prettyprint-override"><code>class OrderedParamsCommand(click.Command):
    _options = []

    def parse_args(self, ctx, args):
        # run the parser for ourselves to preserve the passed order
        parser = self.make_parser(ctx)
        opts, _, param_order = parser.parse_args(args=list(args))
        for param in param_order:
            # Type check
            option = opts[param.name]
            if option != None:
                type(self)._options.append((param, option.pop(0)))

        # return "normal" parse results
        return super().parse_args(ctx, args)
</code>```

EDIT: I posted an answer as I could not propose an edit

EDIT 2: Uhh, this should not be the solution. I just tried --help with this and it crashed with this error:

type(self)._options.append((param, option.pop(0)))
AttributeError: 'bool' object has no attribute 'pop'
```

Too bad, I wished there is a proper solution

Body:
I am trying to port an argparse command-line interface (CLI) to click. This CLI must maintain the order in which parameters are provided by the user. With the argparse version, I used this StackOverflow answer to maintain order. With click, I am not sure how to do this.

I tried creating a custom callback to store params and values in order, but if a parameter is used multiple times, the callback fires the first time it sees a matching parameter.

import click
import typing

class OrderParams:
    _options: typing.List[typing.Tuple[click.Parameter, typing.Any]] = []

    @classmethod
    def append(cls, ctx: click.Context, param: click.Parameter, value: typing.Any):
        cls._options.append((param, value))

@click.command()
@click.option("--animal", required=True, multiple=True, callback=OrderParams.append)
@click.option("--thing", required=True, multiple=True, callback=OrderParams.append)
def cli(*, animal, thing):
    click.echo("Got this order of parameters:")
    for param, value in OrderParams._options:
        print("  ", param.name, value)

if __name__ == "__main__":
    cli()

Current output:

$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
   animal ('cat', 'dog')
   thing ('rock',)

Desired output:

$ python cli.py --animal cat --thing rock --animal dog
Got this order of parameters:
   animal 'cat'
   thing 'rock'
   animal 'dog'

The click documentation describes the behavior that a callback is called once the first time a parameter is encountered, even if the parameter is used multiple times.

If an option or argument is split up on the command line into multiple places because it is repeated [...] the callback will fire based on the position of the first option.

Body:
@StephenRauch's answer is correct but it misses one minor detail. Calling the cli function i.e. the script without any arguments will result in an error:

type(self)._options.append((param, opts[param.name].pop(0)))
AttributeError: 'NoneType' object has no attribute 'pop'

The fix for this is checking opts[param.name] if it is not None. The modified OrderedParamsCommand looks like:

class OrderedParamsCommand(click.Command):
    _options = []

    def parse_args(self, ctx, args):
        # run the parser for ourselves to preserve the passed order
        parser = self.make_parser(ctx)
        opts, _, param_order = parser.parse_args(args=list(args))
        for param in param_order:
            # Type check
            option = opts[param.name]
            if option != None:
                type(self)._options.append((param, option.pop(0)))

        # return "normal" parse results
        return super().parse_args(ctx, args)

EDIT: I posted an answer as I could not propose an edit

EDIT 2: Uhh, this should not be the solution. I just tried --help with this and it crashed with this error:

type(self)._options.append((param, option.pop(0)))
AttributeError: 'bool' object has no attribute 'pop'

Too bad, I wished there is a proper solution


问:
Location Background - Network Connection
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here</p>

```<code>    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager
       didUpdateToLocationCLLocation *)newLocation
       fromLocationCLLocation *)oldLocation
     {

      NSLog(@"Location Change");
     }
     This Method Call Only Once.
</code>```

答:
Make sure you are not testing this in simulator.
You don't get location updates on the iphone simulator.</p>

Body:
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here

    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager
       didUpdateToLocationCLLocation *)newLocation
       fromLocationCLLocation *)oldLocation
     {

      NSLog(@"Location Change");
     }
     This Method Call Only Once.


问:
Is .Alp file enough to run model on other device
I'm currently not having the option to check this question since I do not have 2 computers running Anylogic.

My question is if you share your anylogic .Alp file with somebody, is he able to open the model.

Or should you also need to share the things in your model file when you save it(3d map, databasemap and pictures)

Or do you even need more since when you save an anylogic file you also need to name the Java package.

I'm asking this because my computer is running on his end and I need to know what I've to put in the cloud when my computer will crash and will not be able to use it.

Im currently have put the map from the model map in the cloud and the database excel files. (But no file about the Java package cause I could not find it)

答:
You only need the .alp file itself and all items that are in the model folder where the .alp sits. This can include:

images

database subfolder

lib subfolder (holding any required jar files)

logs subfolder

outputs subfolder

So if you simply zip the entire model folder and send it over, the other person unzips it AND IF he/she uses the same AnyLogic version, all will work.

If it is an older version of AnyLogic on the other end, it may not work (but also it may, it depends on the version difference).

Also, if you created the model with the Professional version and you used some elements that are not accessible in the free PLE version and if the other person only uses the PLE, it will also not work.

If you really just need the other person to run the model, consider compiling it or using the AnyLogic cloud.


问:
How can I override the OnBeforeUnload dialog and replace it with my own?
I need to warn users about unsaved changes before they leave a page (a pretty common problem).

```<code>window.onbeforeunload = handler
</code>```

This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.

So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?

Javascript in my page:

```<code><script type="text/javascript">
    window.onbeforeunload = closeIt;
</script>
</code>```

The closeIt() function:

```<code>function closeIt()
{
  if (changes == "true" || files == "true")
  {
      return "Here you can append a custom message to the default dialog.";
  }
}
</code>```

Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):

```<code>$(window).beforeunload(function () {
    confirm('new message: ' + this.href + ' !', this.href);
    return false;
});
</code>```

which also doesn't work - I cannot seem to bind to the beforeunload event.

答:
Try this</p>
```<code>$(window).bind('beforeunload', function (event) {
            setTimeout(function () {
                var retVal = confirm("Do you want to continue ?");
                if (retVal == true) {
                    alert("User wants to continue!");
                    return true;
                }
                else {
                    window.stop();
                    return false;
                }
            });
            return;
        });
</code>```

OwnerDisplayName: manwood

Body:
I need to warn users about unsaved changes before they leave a page (a pretty common problem).

window.onbeforeunload = handler

This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.

So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?

Javascript in my page:

The closeIt() function:

function closeIt()
{
  if (changes == "true" || files == "true")
  {
      return "Here you can append a custom message to the default dialog.";
  }
}

Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):

$(window).beforeunload(function () {
    confirm('new message: ' + this.href + ' !', this.href);
    return false;
});

which also doesn't work - I cannot seem to bind to the beforeunload event.

LastEditorDisplayName: manwood

Body:
Try this

$(window).bind('beforeunload', function (event) {
            setTimeout(function () {
                var retVal = confirm("Do you want to continue ?");
                if (retVal == true) {
                    alert("User wants to continue!");
                    return true;
                }
                else {
                    window.stop();
                    return false;
                }
            });
            return;
        });


问:
Is there a way to modify user e-mail routing via the api?
I would like to be able to modify user-level e-mail routing via an API, but I can't seem to find a library that will permit this.

Am I missing something, or is this not possible?

答:
In case this is the aim of the OP, the admin API has support for managing routing

<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:apps="http://schemas.google.com/apps/2006">
<apps:property name='routeDestination' value='route-smtp.domain.com'/>
<apps:property name='routeRewriteTo' value='true'/>
<apps:property name='routeEnabled' value='true'/>
<apps:property name='bounceNotifications' value='true'/>
<apps:property name='accountHandling' value='can be either allAccounts | provisionedAccounts | unknownAccounts'/>
</atom:entry>
```


问:
How to make a string array?
How do I make a string array in python with length 100 for example. I don't use python much so I'm not really sure how. I want the array to be formatted in this way so I can assign a string to a value in a separate line.</p>
```<code>keyword = [100]
keyword[0] = "Blue Light Glasses"
keyword[1] = "Tech Fleece Joggers"
</code>```

答:
there isn't a way in python to declare a array of a fixed lenght but there are some "tricks" to do this as:

```<code>lenght = 100
# You are creating an array of 100 None items
listOfNone = [None] * lenght
</code>```

Another thing you can't do is declare an array of that fixed value type (like string). You can create an array only made of string but at any time you could replace a string element of the array with an int for example.
Here is an example:

```<code>lenght = 100
# Declaring an array made of 100 "a beautiful string" repeating
listOfStrings = ["a beautiful string"] * lenght
# Replacing the tenth element with a 12 (type int)
listOfStrings[9] = 12
# You can check the type of the element in python by printing:
print(type(listOfStrings[9])) # This will print int
print(type(listOfStrings[8])) # This will print string. As you can see there are 2 types of var in the same list (python doesn't matter)
listOfStrings[24] = False #Placing a bool in the 25th element
</code>```

There is a workaround to this: you can create a function that handles the array (or use a class too, but I don't know your Python level).
I'm typing a basic function for you that you can adjust for your needs

```<code>def fillArrayWithElement(array, element):
    if not str(type(array)) == "<class 'list'>":
        # The array is not an array
        raise ValueError('The first parameter must be list type')
        return
    if not str(type(prova2)) == "<class 'str'>":
        # The element to add is not a string
        raise ValueError('The element must be str type')
        return
    array.append(element)
    return array
</code>```

OwnerDisplayName: anon

Title: How to make a string array?

Body:
How do I make a string array in python with length 100 for example. I don't use python much so I'm not really sure how. I want the array to be formatted in this way so I can assign a string to a value in a separate line.

keyword = [100]
keyword[0] = "Blue Light Glasses"
keyword[1] = "Tech Fleece Joggers"

Body:
there isn't a way in python to declare a array of a fixed lenght but there are some "tricks" to do this as:

lenght = 100
# You are creating an array of 100 None items
listOfNone = [None] * lenght

Another thing you can't do is declare an array of that fixed value type (like string). You can create an array only made of string but at any time you could replace a string element of the array with an int for example.
Here is an example:

lenght = 100
# Declaring an array made of 100 "a beautiful string" repeating
listOfStrings = ["a beautiful string"] * lenght
# Replacing the tenth element with a 12 (type int)
listOfStrings[9] = 12
# You can check the type of the element in python by printing:
print(type(listOfStrings[9])) # This will print int
print(type(listOfStrings[8])) # This will print string. As you can see there are 2 types of var in the same list (python doesn't matter)
listOfStrings[24] = False #Placing a bool in the 25th element

There is a workaround to this: you can create a function that handles the array (or use a class too, but I don't know your Python level).
I'm typing a basic function for you that you can adjust for your needs

def fillArrayWithElement(array, element):
    if not str(type(array)) == "<class 'list'>":
        # The array is not an array
        raise ValueError('The first parameter must be list type')
        return
    if not str(type(prova2)) == "<class 'str'>":
        # The element to add is not a string
        raise ValueError('The element must be str type')
        return
    array.append(element)
    return array


问:
Eclipse IDE Scope Highlighting?
When I first learned Java, I was using an IDE called "BlueJ." It had this feature called "Scope Highlighting" which made it very easy to read blocks of code. Now I've moved on from BlueJ and began using Eclipse. I'm currently in the process of customizing Eclipse to my liking and would like this Scope Highlighting feature inside Eclipse.

I've searched everywhere for an answer on how to do it but I cannot find any information pointing to a solution for doing it in Eclipse.

Here's a picture to demonstrate what Scope Highlighting looks like:

答:
Maybe you will also like the VSCode extension "Blockman". It highlights nested code blocks based on curly/square/round brackets, html/xml tags and Python/Yaml indentation. (I am the author of Blockman).
.
https://i.ibb.co/31F0rm9/vscode-blockman-intro-leodevbro-extension3.png
.
.</p>

Title: Eclipse IDE Scope Highlighting?


问:
(Java) if statement not evaluating equality between int values
```<code>int count = charFreq.get(guessChar);
int matchedChars = updatedCharFreq.get('_');

if (updatedKeyVals.contains('_')) {

    if (count == matchedChars) {
        ;
    }

    if (count < matchedChars) {
        ;
    }

    else {
        count = count - matchedChars;
    }
</code>```

Method works if count < matchedChars, and also the else statement. It just skips past the if equality statement. I have been trying to figure it out, but just can't seem to.

答:
As commented, you neglected to chain the first if with an else.

I suggest accounting for all cases explicitly plus an extra final case that should never be reached. The extra check is for defensive programming, to guard against editing errors.

```<code>if (count == matchedChars) {
    // No code needed here.
} else if (count < matchedChars) {
    // No code needed here.
} else if (count > matchedChars) {
    count = count - matchedChars;
} else {
    throw new IllegalStateException( … ) ; // Should never reach this point.
}
</code>```

It seems you only care about the case where the first number is bigger than the second. So we could shorten this code.

```<code>if (count > matchedChars) {
    count = count - matchedChars;
}
</code>```

Alternatively, you can use the static method Integer.compare. To quote the Javadoc:

Returns: the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y

```<code>if( Integer.compare( count , matchedChars ) > 0 ) {
    count = count - matchedChars;
}
</code>```

Body:
int count = charFreq.get(guessChar);
int matchedChars = updatedCharFreq.get('_');

if (updatedKeyVals.contains('_')) {

    if (count == matchedChars) {
        ;
    }

    if (count < matchedChars) {
        ;
    }

    else {
        count = count - matchedChars;
    }

Method works if count < matchedChars, and also the else statement. It just skips past the if equality statement. I have been trying to figure it out, but just can't seem to.

Body:
As commented, you neglected to chain the first if with an else.

I suggest accounting for all cases explicitly plus an extra final case that should never be reached. The extra check is for defensive programming, to guard against editing errors.

if (count == matchedChars) {
    // No code needed here.
} else if (count < matchedChars) {
    // No code needed here.
} else if (count > matchedChars) {
    count = count - matchedChars;
} else {
    throw new IllegalStateException( … ) ; // Should never reach this point.
}

It seems you only care about the case where the first number is bigger than the second. So we could shorten this code.

if (count > matchedChars) {
    count = count - matchedChars;
}

Alternatively, you can use the static method Integer.compare. To quote the Javadoc:

Returns: the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y

if( Integer.compare( count , matchedChars ) > 0 ) {
    count = count - matchedChars;
}


问:
How to get the option to set behave as BDD framework in PyCharm?
I try to get BDD running in PyCharm 2016.2.3 with Gherkin and behave as shown in https://www.youtube.com/watch?v=nmBbR97Vsv8, but when I get to the part where I need to enter the BDD framework behave  I am not able to get anything like that:  How do I get this option?

Btw. I did install the Gherkin plugin.

答:
For community edition you can try this:

1.Open your project.

2.Click on setting icon.

3.Under your project name click on python interpreter.

4.Click on + icon

5.Then Search for Behave and install it and then add gherkin plug in


问:
How to pass different variables to multiple functons?
I am very new to python and I have three lists that I edited in a function and want to pass these three lists to multiple different functions,
This is basic example of what I mean:

```<code>def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]

def aa():

def bb():
</code>```

I would like to send firstlist to aa() and all three lists to bb() but I am confused. What would be the most efficient way to do that?

答:
You could work with global variables, but that is not good practice. Instead, return the lists from your function, as a tuple, and pass them as arguments into the other functions.

def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]

    return firstlist, seclist, thirdlist

def aa(firstlist):
    pass

def bb(firstlist, seclist, thirdlist):
    pass

one, two, three = editing()
aa(one)
bb(one, two, three)
```

Body:
I am very new to python and I have three lists that I edited in a function and want to pass these three lists to multiple different functions,
This is basic example of what I mean:

def editing():
    firstlist = [1,2,3]
    seclist = [4,5,6]
    thirdlist = [7,8,9]

def aa():

def bb():

I would like to send firstlist to aa() and all three lists to bb() but I am confused. What would be the most efficient way to do that?


问:
What are good tools for identifying potentially duplicated code for C# Express users?
see also "Any tools to check for duplicate VB.NET code?"

A friend of mine only has access to the Express editions of Visual Studio and I am trying to help him refactor to remove a lot of duplication.

答:
Try Atomiq:

Atomiq Code Similarity Finder is a tool for developers to find and eliminate duplicate code. It is designed for .NET developers, but works equally well for developers of other languages and even web designers!
  Atomiq works with a wide variety of source code:

We currently support C#, VB.Net, ASPX, Ruby, Python, Java, C, C++,
  ActionScript, and XAML, with more extensions on the way soon. It is
  the perfect companion tool for someone who updates their code
  infrequently and can't possibly remember everything in it or for a
  team of 2 or more developers working on the same project that don't
  know everything in it since they didn't write it all themselves.

Eliminate similar code

(and the banging your head against the wall that comes with it) Atomiq
  doesn't just find exact matches, it finds similar code. It ignores
  "fluff" like whitespace, string content, curly braces, comments and
  using/import statements so you can find the duplicate code that causes
  problems. In VB.NET, it will also ignore lines that contain only
  "Next", "End While", "End Try", "End If", "End Property", "End Get"
  and "End Set".