问:
"Cannot find module '@angular/compiler-cli/ngcc'" when running "ng serve" on my app
I'm trying to run my app and i get this error. I tried some solution I've found on internet,like uninstalling angular/cli,reinstalling it,checking if in my package.json the version was correct,if it was @angular/cli either than @angular-cli in devDependencies and some other stuff,like uninstalling and installing npm,deleting node modules and reinstalling it,but none of the previous solved my problem...
this is my package.json

```<code>    {
  "name": "techlog-admin",
  "version": "3.2.1",
  "license": "MIT",
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "IE 11"
  ],
  "scripts": {
    "ng": "ng",
    "conventional-changelog": "conventional-changelog",
    "start": "ng serve",
    "build": "ng build",
    "build:prod": "npm run build -- --prod --aot",
    "test": "ng test",
    "test:coverage": "rimraf coverage && npm run test -- --code-coverage",
    "lint": "ng lint",
    "lint:fix": "ng lint techlog-admin-demo --fix",
    "lint:styles": "stylelint ./src/**/*.scss",
    "lint:ci": "npm run lint && npm run lint:styles",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "ng e2e",
    "docs": "compodoc -p src/tsconfig.app.json -d docs",
    "docs:serve": "compodoc -p src/tsconfig.app.json -d docs -s",
    "prepush": "npm run lint:ci",
    "release:changelog": "npm run conventional-changelog -- -p angular -i CHANGELOG.md -s"
  },
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^7.2.13",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.11",
    "@angular/compiler": "^7.2.11",
    "@angular/core": "^7.2.11",
    "@angular/forms": "^7.2.11",
    "@angular/http": "^7.2.11",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.2.11",
    "@angular/platform-browser-dynamic": "^7.2.11",
    "@angular/router": "^7.2.11",
    "@asymmetrik/ngx-leaflet": "3.0.1",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.17",
    "@fortawesome/free-solid-svg-icons": "^5.8.1",
    "@nebular/auth": "3.4.2",
    "@nebular/bootstrap": "3.4.2",
    "@nebular/moment": "^3.4.0",
    "@nebular/security": "3.4.2",
    "@nebular/theme": "3.4.2",
    "@ng-bootstrap/ng-bootstrap": "^4.0.0",
    "@ng-idle/core": "^6.0.0-beta.5",
    "@ng-idle/keepalive": "^6.0.0-beta.5",
    "@ngx-translate/core": "^11.0.1",
    "@swimlane/ngx-charts": "^10.0.0",
    "angular-tree-component": "7.2.0",
    "angular2-chartjs": "0.4.1",
    "angular2-toaster": "^7.0.0",
    "bootstrap": "^4.3.1",
    "chart.js": "^2.8.0",
    "ckeditor": "4.7.3",
    "classlist.js": "1.1.20150312",
    "core-js": "2.5.1",
    "echarts": "^4.0.2",
    "eva-icons": "^1.1.0",
    "intl": "1.2.5",
    "ionicons": "2.0.1",
    "jquery": "^3.4.0",
    "leaflet": "1.2.0",
    "nebular-icons": "1.1.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-completer": "2.0.8",
    "ng2-smart-table": "1.3.5",
    "ngx-echarts": "^4.0.1",
    "ngx-show-hide-password": "^2.0.3",
    "ngx-spinner": "^7.1.4",
    "ngx-typeahead": "^6.2.0",
    "normalize.css": "6.0.0",
    "or": "^0.2.0",
    "pace-js": "1.0.2",
    "roboto-fontface": "0.8.0",
    "rxjs": "6.4.0",
    "rxjs-compat": "6.3.0",
    "socicon": "3.0.5",
    "tinymce": "4.5.7",
    "ts-md5": "^1.2.4",
    "tslib": "^1.9.0",
    "typeface-exo": "0.0.22",
    "web-animations-js": "2.2.5",
    "zone.js": "^0.8.29"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.801.3",
    "@angular/cli": "^8.1.3",
    "@angular/compiler-cli": "^7.2.15",
    "@angular/language-service": "7.2.11",
    "@compodoc/compodoc": "^1.1.10",
    "@fortawesome/fontawesome-free": "^5.2.0",
    "@types/d3-color": "1.0.5",
    "@types/googlemaps": "^3.30.4",
    "@types/jasmine": "2.5.54",
    "@types/jasminewd2": "2.0.3",
    "@types/leaflet": "1.2.3",
    "@types/node": "6.0.90",
    "codelyzer": "^4.5.0",
    "conventional-changelog-cli": "1.3.4",
    "husky": "0.13.3",
    "jasmine-core": "2.6.4",
    "jasmine-spec-reporter": "4.1.1",
    "karma": "1.7.1",
    "karma-chrome-launcher": "2.1.1",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "1.3.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "npm-run-all": "4.0.2",
    "protractor": "5.1.2",
    "rimraf": "2.6.1",
    "stylelint": "7.13.0",
    "ts-node": "3.2.2",
    "tslint": "5.7.0",
    "tslint-language-service": "^0.9.9",
    "typescript": "3.2.4"
  }
}
</code>```

If you need any more information ask me and I'll post as soon as I can! Thank you

答:
I've tried all the things I've found in other Stackoverflow and github threads, but the only things that worked for me was to downgraded the angular@cli to 7.2 (which is the current angular packages version in my project) and also install manually the following packages:

npm install @angular/compiler-cli --save

npm install @angular-devkit/build-angular

My package.json contains both of these dependencies, however it seemed that npm install couldn't install them. So I had to do it manually.

For what I understand, this is an issue between newer and older versions of the angular/cli.

Hope I could help!

Body:
I'm trying to run my app and i get this error. I tried some solution I've found on internet,like uninstalling angular/cli,reinstalling it,checking if in my package.json the version was correct,if it was @angular/cli either than @angular-cli in devDependencies and some other stuff,like uninstalling and installing npm,deleting node modules and reinstalling it,but none of the previous solved my problem...
this is my package.json

    {
  "name": "techlog-admin",
  "version": "3.2.1",
  "license": "MIT",
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "IE 11"
  ],
  "scripts": {
    "ng": "ng",
    "conventional-changelog": "conventional-changelog",
    "start": "ng serve",
    "build": "ng build",
    "build:prod": "npm run build -- --prod --aot",
    "test": "ng test",
    "test:coverage": "rimraf coverage && npm run test -- --code-coverage",
    "lint": "ng lint",
    "lint:fix": "ng lint techlog-admin-demo --fix",
    "lint:styles": "stylelint ./src/**/*.scss",
    "lint:ci": "npm run lint && npm run lint:styles",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "ng e2e",
    "docs": "compodoc -p src/tsconfig.app.json -d docs",
    "docs:serve": "compodoc -p src/tsconfig.app.json -d docs -s",
    "prepush": "npm run lint:ci",
    "release:changelog": "npm run conventional-changelog -- -p angular -i CHANGELOG.md -s"
  },
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^7.2.13",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.11",
    "@angular/compiler": "^7.2.11",
    "@angular/core": "^7.2.11",
    "@angular/forms": "^7.2.11",
    "@angular/http": "^7.2.11",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.2.11",
    "@angular/platform-browser-dynamic": "^7.2.11",
    "@angular/router": "^7.2.11",
    "@asymmetrik/ngx-leaflet": "3.0.1",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.17",
    "@fortawesome/free-solid-svg-icons": "^5.8.1",
    "@nebular/auth": "3.4.2",
    "@nebular/bootstrap": "3.4.2",
    "@nebular/moment": "^3.4.0",
    "@nebular/security": "3.4.2",
    "@nebular/theme": "3.4.2",
    "@ng-bootstrap/ng-bootstrap": "^4.0.0",
    "@ng-idle/core": "^6.0.0-beta.5",
    "@ng-idle/keepalive": "^6.0.0-beta.5",
    "@ngx-translate/core": "^11.0.1",
    "@swimlane/ngx-charts": "^10.0.0",
    "angular-tree-component": "7.2.0",
    "angular2-chartjs": "0.4.1",
    "angular2-toaster": "^7.0.0",
    "bootstrap": "^4.3.1",
    "chart.js": "^2.8.0",
    "ckeditor": "4.7.3",
    "classlist.js": "1.1.20150312",
    "core-js": "2.5.1",
    "echarts": "^4.0.2",
    "eva-icons": "^1.1.0",
    "intl": "1.2.5",
    "ionicons": "2.0.1",
    "jquery": "^3.4.0",
    "leaflet": "1.2.0",
    "nebular-icons": "1.1.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-completer": "2.0.8",
    "ng2-smart-table": "1.3.5",
    "ngx-echarts": "^4.0.1",
    "ngx-show-hide-password": "^2.0.3",
    "ngx-spinner": "^7.1.4",
    "ngx-typeahead": "^6.2.0",
    "normalize.css": "6.0.0",
    "or": "^0.2.0",
    "pace-js": "1.0.2",
    "roboto-fontface": "0.8.0",
    "rxjs": "6.4.0",
    "rxjs-compat": "6.3.0",
    "socicon": "3.0.5",
    "tinymce": "4.5.7",
    "ts-md5": "^1.2.4",
    "tslib": "^1.9.0",
    "typeface-exo": "0.0.22",
    "web-animations-js": "2.2.5",
    "zone.js": "^0.8.29"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.801.3",
    "@angular/cli": "^8.1.3",
    "@angular/compiler-cli": "^7.2.15",
    "@angular/language-service": "7.2.11",
    "@compodoc/compodoc": "^1.1.10",
    "@fortawesome/fontawesome-free": "^5.2.0",
    "@types/d3-color": "1.0.5",
    "@types/googlemaps": "^3.30.4",
    "@types/jasmine": "2.5.54",
    "@types/jasminewd2": "2.0.3",
    "@types/leaflet": "1.2.3",
    "@types/node": "6.0.90",
    "codelyzer": "^4.5.0",
    "conventional-changelog-cli": "1.3.4",
    "husky": "0.13.3",
    "jasmine-core": "2.6.4",
    "jasmine-spec-reporter": "4.1.1",
    "karma": "1.7.1",
    "karma-chrome-launcher": "2.1.1",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "1.3.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "npm-run-all": "4.0.2",
    "protractor": "5.1.2",
    "rimraf": "2.6.1",
    "stylelint": "7.13.0",
    "ts-node": "3.2.2",
    "tslint": "5.7.0",
    "tslint-language-service": "^0.9.9",
    "typescript": "3.2.4"
  }
}

If you need any more information ask me and I'll post as soon as I can! Thank you


来源: stackexchange

问:
Recursive API Calls using AWS Lambda Functions Python
I've never written a recursive python script before. I'm used to splitting up a monolithic function into sub AWS Lambda functions. However, this particular script I am working on is challenging to break up into smaller functions.

Here is the code I am currently using for context. I am using one api request to return a list of objects within a table.

```<code>url_pega_EEvisa = requests.get('https://cloud.xxxx.com:443/prweb/api/v1/data/D_pxCaseList?caseClass=xx-xx-xx-xx', auth=(username, password))
pega_EEvisa_raw = url_pega_EEvisa.json()
pega_EEvisa = pega_EEvisa_raw['pxResults']
</code>```

This returns every object(primary key) within a particular table as a list. For example,

```<code>['XX-XXSALES-WORK%20PO-1', 'XX-XXSALES-WORK%20PO-10', 'XX-XXSALES-WORK%20PO-100', 'XX-XXSALES-WORK%20PO-101', 'XX-XXSALES-WORK%20PO-102', 'XX-XXSALES-WORK%20PO-103', 'XX-XXSALES-WORK%20PO-104', 'XX-XXSALES-WORK%20PO-105', 'XX-XXSALES-WORK%20PO-106', 'XX-XXSALES-WORK%20PO-107']
</code>```

I then use this list to populate more get requests using a for loop which then grabs me all the data per object.

```<code>for t in caseid:
    url = requests.get(('https://cloud.xxxx.com:443/prweb/api/v1/cases/{}'.format(t)), auth=(username, password)).json()
    data.append(url)
</code>```

This particular lambda function takes about 15min which is the limit for one AWS Lambda function. Ideally, I'd like to split up the list into smaller parts and run the same process. I am struggling marking the point where it last ran before failure and passing that information on to the next function.

Any help is appreciated!

答:
I'm not sure if I entirely understand what you want to do with the data once you've fetched all the information about the case, but it terms of breaking up the work once lambda is doing into many lambdas, you should be able to chunk out the list of cases and pass them to new invocations of the same lambda. Python psuedocode below, hopefully it helps illustrate the idea. I stole the chunks method from this answer that would help break the list into batches

import boto3
import json

client = boto3.client('lambda')

def handler
  url_pega_EEvisa = requests.get('https://cloud.xxxx.com:443/prweb/api/v1/data/D_pxCaseList?caseClass=xx-xx-xx-xx', auth=(username, password))
  pega_EEvisa_raw = url_pega_EEvisa.json()
  pega_EEvisa = pega_EEvisa_raw['pxResults']

  for chunk in chunks(pega_EEvisa, 10)
    client.invoke(
      FunctionName='lambdaToHandleBatchOfTenCases',
      Payload=json.dumps(chunk)
    )
```

Hopefully that helps? Let me know if this was not on target

ContentLicense: CC BY-SA 4.0

Body:
I've never written a recursive python script before. I'm used to splitting up a monolithic function into sub AWS Lambda functions. However, this particular script I am working on is challenging to break up into smaller functions.

Here is the code I am currently using for context. I am using one api request to return a list of objects within a table.

url_pega_EEvisa = requests.get('https://cloud.xxxx.com:443/prweb/api/v1/data/D_pxCaseList?caseClass=xx-xx-xx-xx', auth=(username, password))
pega_EEvisa_raw = url_pega_EEvisa.json()
pega_EEvisa = pega_EEvisa_raw['pxResults']

This returns every object(primary key) within a particular table as a list. For example,

['XX-XXSALES-WORK%20PO-1', 'XX-XXSALES-WORK%20PO-10', 'XX-XXSALES-WORK%20PO-100', 'XX-XXSALES-WORK%20PO-101', 'XX-XXSALES-WORK%20PO-102', 'XX-XXSALES-WORK%20PO-103', 'XX-XXSALES-WORK%20PO-104', 'XX-XXSALES-WORK%20PO-105', 'XX-XXSALES-WORK%20PO-106', 'XX-XXSALES-WORK%20PO-107']

I then use this list to populate more get requests using a for loop which then grabs me all the data per object.

for t in caseid:
    url = requests.get(('https://cloud.xxxx.com:443/prweb/api/v1/cases/{}'.format(t)), auth=(username, password)).json()
    data.append(url)

This particular lambda function takes about 15min which is the limit for one AWS Lambda function. Ideally, I'd like to split up the list into smaller parts and run the same process. I am struggling marking the point where it last ran before failure and passing that information on to the next function.

Any help is appreciated!

Body:
I'm not sure if I entirely understand what you want to do with the data once you've fetched all the information about the case, but it terms of breaking up the work once lambda is doing into many lambdas, you should be able to chunk out the list of cases and pass them to new invocations of the same lambda. Python psuedocode below, hopefully it helps illustrate the idea. I stole the chunks method from this answer that would help break the list into batches

import boto3
import json

client = boto3.client('lambda')

def handler
  url_pega_EEvisa = requests.get('https://cloud.xxxx.com:443/prweb/api/v1/data/D_pxCaseList?caseClass=xx-xx-xx-xx', auth=(username, password))
  pega_EEvisa_raw = url_pega_EEvisa.json()
  pega_EEvisa = pega_EEvisa_raw['pxResults']

  for chunk in chunks(pega_EEvisa, 10)
    client.invoke(
      FunctionName='lambdaToHandleBatchOfTenCases',
      Payload=json.dumps(chunk)
    )

Hopefully that helps? Let me know if this was not on target


问:
How to segment similar looking areas (color wise) inside a image that belong to biosamples with opencv and python?
I'm trying to analyze images of bio-films of pseudomona, I'm doing this in order to find some kind of correlation between its grow and distribution with some independent variables. I've applied a segmentation to obtain a circular area of interest and now I was thinking in applying some color segmentation to the image with its HSV values to just leave the areas with bio-film.  I've trying to think in a way to completely isolate all the areas that are important, I applied a bitwise_not to the image to see the negative and have found that is visually more easy to distinguish, all the areas that are yellowish have bacteria on it.

Original image:

Negative:

With the code I've written, I've got to segment big spots of the bacteria, but not all the areas that really have it.

```<code>import cv2
import numpy as np
import os
def color_segmentation(image):
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask1 = cv2.inRange(hsv, (90,90,50), (179,255,160))
    target = cv2.bitwise_and(image, image, mask=mask1)
    return target
test = cv2.imread(path)
result = color_segmentation(test)
cv2.imshow('result', result)
</code>```

I already know that the code it's really simple, so it didn't surprise me when I couldn't isolate all the areas of interest, do you think that if apply more masks could I extract all the yellowish areas? Or maybe someone could say an algorithm that's somewhat similar to what I'm looking. Thanks in advance to anyone interested.

Result:

答:
One idea is to perform Kmeans color quantization to cluster the image into a distinct amount of colors. Afterwards, we can convert the image to HSV format and perform color thresholding using cv2.inRange with a lower/upper color threshold to obtain a binary mask. Finally we apply this mask onto the original image using cv2.bitwise_and.

Original image -> Kmeans color quantization with clusters=5

Notice the subtle difference in that the entire image is segmented into five colors. Here's a visualization of each color cluster and the color distribution percentage. Based on the color segmentation, we can estimate that the first three colors (ignoring black) have bacteria on it.

```<code>[ 67.70980019  86.19251507 121.19410086] 0.87%
[120.61108133 146.00169267 159.48142297] 9.78%
[0.18113609 0.22505063 0.25559479] 21.40%
[134.06236381 170.04397205 167.3696234 ] 23.44%
[140.53640479 189.4275781  171.19319177] 44.50%
</code>```

Next we perform color thresholding to obtain a mask with this lower/upper color range

```<code>lower = np.array([84, 0, 0])
upper = np.array([179, 255, 255])
</code>```

We apply the mask onto the original image to get our result

Remember how there were three color distributions we used to determine if there was bacteria? If we change the color threshold range, we can further segment the image into large, medium, and small regions of bacteria.

We can isolate only the large bacteria regions using this color range

```<code>lower = np.array([104, 0, 0])
upper = np.array([179, 255, 255])
</code>```

Mask -> Result

For the medium regions

```<code>lower = np.array([90, 0, 0])
upper = np.array([102, 255, 255])
</code>```

Finally, to obtain the small regions

```<code>lower = np.array([84, 0, 0])
upper = np.array([98, 255, 255])
</code>```

Code

```<code>import cv2
import numpy as np

# Kmeans color segmentation
def kmeans_color_quantization(image, clusters=8, rounds=1):
    h, w = image.shape[:2]
    samples = np.zeros([h*w,3], dtype=np.float32)
    count = 0

    for x in range(h):
        for y in range(w):
            samples[count] = image[x][y]
            count += 1

    compactness, labels, centers = cv2.kmeans(samples,
            clusters,
            None,
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
            rounds,
            cv2.KMEANS_RANDOM_CENTERS)

    centers = np.uint8(centers)
    res = centers[labels.flatten()]
    return res.reshape((image.shape))

# Load original image
original = cv2.imread('2.png')

# Perform kmeans color segmentation
kmeans = kmeans_color_quantization(original, clusters=5)

# Color threshold on kmeans image
hsv = cv2.cvtColor(kmeans, cv2.COLOR_BGR2HSV)
lower = np.array([84, 0, 0])
upper = np.array([179, 255, 255])
mask = cv2.inRange(hsv, lower, upper)

# Apply mask onto original image
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)

# Display
cv2.imshow('kmeans', kmeans)
cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.waitKey()
</code>```

This HSV color thresholder script was used to determine the lower/upper color ranges

```<code>import cv2
import numpy as np

def nothing(x):
    pass

# Load image
image = cv2.imread('1.png')

# Create a window
cv2.namedWindow('image')

# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)

# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

while(1):
    # Get current positions of all trackbars
    hMin = cv2.getTrackbarPos('HMin', 'image')
    sMin = cv2.getTrackbarPos('SMin', 'image')
    vMin = cv2.getTrackbarPos('VMin', 'image')
    hMax = cv2.getTrackbarPos('HMax', 'image')
    sMax = cv2.getTrackbarPos('SMax', 'image')
    vMax = cv2.getTrackbarPos('VMax', 'image')

    # Set minimum and maximum HSV values to display
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # Convert to HSV format and color threshold
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    result = cv2.bitwise_and(image, image, mask=mask)

    # Print if there is a change in HSV value
    if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # Display result image
    cv2.imshow('image', result)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
</code>```

Body:
I'm trying to analyze images of bio-films of pseudomona, I'm doing this in order to find some kind of correlation between its grow and distribution with some independent variables. I've applied a segmentation to obtain a circular area of interest and now I was thinking in applying some color segmentation to the image with its HSV values to just leave the areas with bio-film.  I've trying to think in a way to completely isolate all the areas that are important, I applied a bitwise_not to the image to see the negative and have found that is visually more easy to distinguish, all the areas that are yellowish have bacteria on it.

Original image:

Negative:

With the code I've written, I've got to segment big spots of the bacteria, but not all the areas that really have it.

import cv2
import numpy as np
import os
def color_segmentation(image):
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask1 = cv2.inRange(hsv, (90,90,50), (179,255,160))
    target = cv2.bitwise_and(image, image, mask=mask1)
    return target
test = cv2.imread(path)
result = color_segmentation(test)
cv2.imshow('result', result)

I already know that the code it's really simple, so it didn't surprise me when I couldn't isolate all the areas of interest, do you think that if apply more masks could I extract all the yellowish areas? Or maybe someone could say an algorithm that's somewhat similar to what I'm looking. Thanks in advance to anyone interested.

Result:

Body:
One idea is to perform Kmeans color quantization to cluster the image into a distinct amount of colors. Afterwards, we can convert the image to HSV format and perform color thresholding using cv2.inRange with a lower/upper color threshold to obtain a binary mask. Finally we apply this mask onto the original image using cv2.bitwise_and.

Original image -> Kmeans color quantization with clusters=5

Notice the subtle difference in that the entire image is segmented into five colors. Here's a visualization of each color cluster and the color distribution percentage. Based on the color segmentation, we can estimate that the first three colors (ignoring black) have bacteria on it.

[ 67.70980019  86.19251507 121.19410086] 0.87%
[120.61108133 146.00169267 159.48142297] 9.78%
[0.18113609 0.22505063 0.25559479] 21.40%
[134.06236381 170.04397205 167.3696234 ] 23.44%
[140.53640479 189.4275781  171.19319177] 44.50%

Next we perform color thresholding to obtain a mask with this lower/upper color range

lower = np.array([84, 0, 0])
upper = np.array([179, 255, 255])

We apply the mask onto the original image to get our result

Remember how there were three color distributions we used to determine if there was bacteria? If we change the color threshold range, we can further segment the image into large, medium, and small regions of bacteria.

We can isolate only the large bacteria regions using this color range

lower = np.array([104, 0, 0])
upper = np.array([179, 255, 255])

Mask -> Result

For the medium regions

lower = np.array([90, 0, 0])
upper = np.array([102, 255, 255])

Finally, to obtain the small regions

lower = np.array([84, 0, 0])
upper = np.array([98, 255, 255])

Code

import cv2
import numpy as np

# Kmeans color segmentation
def kmeans_color_quantization(image, clusters=8, rounds=1):
    h, w = image.shape[:2]
    samples = np.zeros([h*w,3], dtype=np.float32)
    count = 0

    for x in range(h):
        for y in range(w):
            samples[count] = image[x][y]
            count += 1

    compactness, labels, centers = cv2.kmeans(samples,
            clusters,
            None,
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
            rounds,
            cv2.KMEANS_RANDOM_CENTERS)

    centers = np.uint8(centers)
    res = centers[labels.flatten()]
    return res.reshape((image.shape))

# Load original image
original = cv2.imread('2.png')

# Perform kmeans color segmentation
kmeans = kmeans_color_quantization(original, clusters=5)

# Color threshold on kmeans image
hsv = cv2.cvtColor(kmeans, cv2.COLOR_BGR2HSV)
lower = np.array([84, 0, 0])
upper = np.array([179, 255, 255])
mask = cv2.inRange(hsv, lower, upper)

# Apply mask onto original image
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)

# Display
cv2.imshow('kmeans', kmeans)
cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.waitKey()

This HSV color thresholder script was used to determine the lower/upper color ranges

import cv2
import numpy as np

def nothing(x):
    pass

# Load image
image = cv2.imread('1.png')

# Create a window
cv2.namedWindow('image')

# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)

# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

while(1):
    # Get current positions of all trackbars
    hMin = cv2.getTrackbarPos('HMin', 'image')
    sMin = cv2.getTrackbarPos('SMin', 'image')
    vMin = cv2.getTrackbarPos('VMin', 'image')
    hMax = cv2.getTrackbarPos('HMax', 'image')
    sMax = cv2.getTrackbarPos('SMax', 'image')
    vMax = cv2.getTrackbarPos('VMax', 'image')

    # Set minimum and maximum HSV values to display
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # Convert to HSV format and color threshold
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    result = cv2.bitwise_and(image, image, mask=mask)

    # Print if there is a change in HSV value
    if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # Display result image
    cv2.imshow('image', result)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()


问:
Are there limits to the number of tables that can be joined in Oracle?
I'm writing a fairly large query, and I have 2 tables, inner joined and 15 tables left-outer joined. when I add the 16, I get ORA-03113: end-of-file on communication channel. If I remove a table to add the new one, the query works fine.

The query runs fine for SQL Server, it's just Oracle that seems to be struggling.

答:
I got problems like this too and they were related to bugs in Oracle.
Lately I haven't had any of these, probably due to the many patches applied to our database by a hired DBA.

This problem doesn't occur because of joining 15 tables. I've built queries joining a lot more. I believe the largest query I wrote was about 450 lines, joining at least 50 tables in many different ways.

Sometimes it works writing a query differently. Could you maybe post your query? I may recognise a certain pattern that caused me troubles too, and suggest an alternative.

I'd like to add that the running time of the query is hardly ever the cause of this. I've seen queries running for minutes without any problems, while others gave this problem in seconds.

ContentLicense: CC BY-SA 3.0


问:
SCSS Webfont (Font Awesome) Compilation Corruption Using Webpack
When compiling font content declarations in SCSS, the output is getting corrupted. Instead of outputting the character escape sequence as I would expect e.g., content: \f26e;, the sass-loader is outputting a single undisplayable character, represented as a square e.g., content: ""; The characters can be found both in the js bundle as well as the extracted CSS.

You can see clearly in the CSS that comes down with the Font Awesome node package of how it should be written to the file

.fa-500px:before {
  content: "\f26e"; }
```

<p>How it gets written to my file</p>

<pre class="lang-css prettyprint-override"><code>.fa-500px:before {
  content: "";
}
</code>```

I was attempting to build styles off of Font Awesome styles when I discovered the issue. I decided to just try to recompile Font Awesome but the issue persisted there too. I have searched around and haven't found any resources that indicate that I'm doing it wrong, but that's my assumption and not that there is something wrong with the Webpack sass-loader.

I have created a repo that demonstrates the issue: https://github.com/rlvandaveer/sass-loader-fontawesome-gist

答:
Digging into this more I've determined that this is not actually an issue. The two cases above are equivalent. The first is an ASCII escape code and the second is the corresponding literal unicode character (which isn't rendered properly). The example repo uses the dart sass implementation which operates differently than the node-sass implementation which I was accustomed to. This dart-sass issue confirms the difference between the two implementations.

Hopefully this answer will save someone from similar n00by confusion.

Body:
When compiling font content declarations in SCSS, the output is getting corrupted. Instead of outputting the character escape sequence as I would expect e.g., content: \f26e;, the sass-loader is outputting a single undisplayable character, represented as a square e.g., content: ""; The characters can be found both in the js bundle as well as the extracted CSS.

You can see clearly in the CSS that comes down with the Font Awesome node package of how it should be written to the file

.fa-500px:before {
  content: "\f26e"; }

How it gets written to my file

.fa-500px:before {
  content: "";
}

I was attempting to build styles off of Font Awesome styles when I discovered the issue. I decided to just try to recompile Font Awesome but the issue persisted there too. I have searched around and haven't found any resources that indicate that I'm doing it wrong, but that's my assumption and not that there is something wrong with the Webpack sass-loader.

I have created a repo that demonstrates the issue: https://github.com/rlvandaveer/sass-loader-fontawesome-gist


问:
Understanding what fc1000_softmax output from tensorflow CNN classification means
I am using python 3.6.10 and tensorflow 1.5 on a cpu. I have trained a cnn and saved it as a .onnx file. I am now trying to make a binary classification of my images using the code below:

import onnx
import warnings
from onnx_tf.backend import prepare
import numpy as np
from numpy import array
from IPython.display import display
from PIL import Image

warnings.filterwarnings('ignore')
onnx_model = onnx.load("trainednet.onnx")  # load onnx model
tf_rep = prepare(onnx_model) # Import the ONNX model to Tensorflow

img = Image.open('Im025.jpg').resize((224, 224))
img = array(img).reshape(1,3, 224,224)

classification = tf_rep.run(img)
print(classification)
```

The print(classification) gives me an output like this:

Outputs(fc1000_softmax=array([[9.9967182e-01, 3.2823894e-04]], dtype=float32))

What does this output mean and how can I use it to understand what tensorflow classified my image as?

答:
Well, what you have is the array of the output of the softmax layer of your model. This output can be interpreted as a probability assigned to each class ( in your case 2). You can also see it as "how confident the model is for each class".

So to have the final classification you need to take the max value of this array and map it to your label map { 0 -> class_one, 1-> class_two}.

Body:
I am using python 3.6.10 and tensorflow 1.5 on a cpu. I have trained a cnn and saved it as a .onnx file. I am now trying to make a binary classification of my images using the code below:

import onnx
import warnings
from onnx_tf.backend import prepare
import numpy as np
from numpy import array
from IPython.display import display
from PIL import Image

warnings.filterwarnings('ignore')
onnx_model = onnx.load("trainednet.onnx")  # load onnx model
tf_rep = prepare(onnx_model) # Import the ONNX model to Tensorflow

img = Image.open('Im025.jpg').resize((224, 224))
img = array(img).reshape(1,3, 224,224)

classification = tf_rep.run(img)
print(classification)

The print(classification) gives me an output like this:

Outputs(fc1000_softmax=array([[9.9967182e-01, 3.2823894e-04]], dtype=float32))

What does this output mean and how can I use it to understand what tensorflow classified my image as?


问:
Include code from file into RMarkdown when filename is variable
I want to have an R chunk in RMarkdown that includes code from an external file.

I want to include the file, rather than embed its contents directly, because the external file contains code that is shared between various projects and scripts, and I want to be sure that each program uses the most recent version.  The code = ... chunk option is made for this.

The following method works fine if I knit the whole document.  However, if I try to run the individual chunks inside Rstudio (as required during development) I get an error "Error in readLines(include_file) : object 'include_file' not found".

How do I get this to work so I can run chunks from within Rstudio?

Reproducible example:

First create some include files

```<code>write_lines("x = 1", 'include_1.r')
write_lines("x = 2", 'include_2.r')
write_lines("x = 3", 'include_3.r')
write_lines("x = 4", 'include_4.r')
</code>```

Then put the following into a .Rmd file

```<code>---
title: "Untitled"
output: html_document
---

```{r setup}
knitr::opts_chunk$set(echo = TRUE)
include_file = list.files(pattern = '^include_.+[Rr]$')
include_file = include_file[which.max(file.info(include_file)$mtime)]
```

I want to embed an R code from a file like this:

```{r, code = readLines(include_file)}
```

Then use the objects from the include file

```{r}
print(x)
```
</code>```

This is what the output looks like when I knit the whole document

答:
Assuming you have a file source.R with the following content:

```<code># first code chunk to be included
## @knitr cc_1
var1 <- runif(10)
var2 <- runif(10)
tmp <- sum(var1)
## @knitr end_cc_1

# second code chunk to be included
## @knitr cc_2
prod(var1, var2)
## @knitr end_cc_2
</code>```

Then you first have to read the file:

```<code>```{r}
knitr::read_chunk("source.R")
```
</code>```

then you can call the code chunks from the source file like so:

```<code>```{r}
<<cc_1>>
print(tmp)
<<cc_2>>
```
</code>```

Note that everything can be in the same code chunk but read_chunk()
must be called before <<cc_1>> and as in this case <<cc_2>> requires tmp
<<cc_1>> must be called before <<cc_2>>.

BTW if you want to evaluate a bunch of code silently you can use include = FALSE,
e.g.

```<code>```{r include = FALSE}
<<cc_1>>
```
</code>```

then, you can call element of <<cc_1>>, e.g.

```<code>```{r}
print(tmp)
```
</code>```

Body:
I want to have an R chunk in RMarkdown that includes code from an external file.

I want to include the file, rather than embed its contents directly, because the external file contains code that is shared between various projects and scripts, and I want to be sure that each program uses the most recent version.  The code = ... chunk option is made for this.

The following method works fine if I knit the whole document.  However, if I try to run the individual chunks inside Rstudio (as required during development) I get an error "Error in readLines(include_file) : object 'include_file' not found".

How do I get this to work so I can run chunks from within Rstudio?

Reproducible example:

First create some include files

write_lines("x = 1", 'include_1.r')
write_lines("x = 2", 'include_2.r')
write_lines("x = 3", 'include_3.r')
write_lines("x = 4", 'include_4.r')

Then put the following into a .Rmd file

---
title: "Untitled"
output: html_document
---

```{r setup}
knitr::opts_chunk$set(echo = TRUE)
include_file = list.files(pattern = '^include_.+[Rr]$')
include_file = include_file[which.max(file.info(include_file)$mtime)]
```

I want to embed an R code from a file like this:

```{r, code = readLines(include_file)}
```

Then use the objects from the include file

```{r}
print(x)
```

This is what the output looks like when I knit the whole document

Body:
Assuming you have a file source.R with the following content:

# first code chunk to be included
## @knitr cc_1
var1 <- runif(10)
var2 <- runif(10)
tmp <- sum(var1)
## @knitr end_cc_1

# second code chunk to be included
## @knitr cc_2
prod(var1, var2)
## @knitr end_cc_2

Then you first have to read the file:

```{r}
knitr::read_chunk("source.R")
```

then you can call the code chunks from the source file like so:

```{r}
<<cc_1>>
print(tmp)
<<cc_2>>
```

Note that everything can be in the same code chunk but read_chunk()
must be called before <<cc_1>> and as in this case <<cc_2>> requires tmp
<<cc_1>> must be called before <<cc_2>>.

BTW if you want to evaluate a bunch of code silently you can use include = FALSE,
e.g.

```{r include = FALSE}
<<cc_1>>
```

then, you can call element of <<cc_1>>, e.g.

```{r}
print(tmp)
```


问:
Appending %20 in the path of the url in Gatsby Blog
I have set up a blog using Gatsby's starter template. Right now, when I open an article, the url it shows is- http://localhost:8000/JavaScript:%20Behind%20The%20Scenes/. I looked up this answer and changed the path property but then the page wouldn't load, it just showed an empty page with the same url. I don't know why it's appending %20 in the path.

Note: The path is actually the folder name. For example, in the directory /content/blog/JavaScript:Behind The Scenes/index.md, path that goes in the url is actually the folder name. I don't know why. Path should've been the title that I've written in index.md of that folder.

index.md

---
title: 'The Execution Context'
date: '2020-02-16'
category: "JavaScript"
---

Blog Content..............
```

<p><strong>gatsby-node.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPostTemplate = path.resolve(`./src/templates/blog-post.js`)

  return graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
                category
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create blog posts pages.
    const posts = result.data.allMarkdownRemark.edges.filter(
      ({ node }) => !!node.frontmatter.category
    )

    posts.forEach((post, index) => {
      const previous = index === posts.length - 1 ? null : posts[index + 1].node
      const next = index === 0 ? null : posts[index - 1].node

      createPage({
        path: post.node.fields.slug,
        component: blogPostTemplate,
        context: {
          slug: post.node.fields.slug,
          previous,
          next,
        },
      })
    })
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })

    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}
</code>```

Also, I have some problem with the Github and Twitter links. When I click them, it shows page not found. It's showing weird url: https://github.com/https://github.com/myGithubName
https://twitter.com/https://twitter.com/myTwitterName

I checked in where is this located and found out:

gatsby-meta-config.js

module.exports = {
  title: `My Blog`,
  description: `Blog posted about ...`,
  author: `myName`,
  introduction: `I explain with words and code.`,
  siteUrl: `https://gatsby-starter-bee.netlify.com`, // Your blog site url
  social: {
    twitter: `https://twitter.com/myTwitterName`, // Your Twitter account
    github: `https://github.com/myGithubName`,
    medium: ``,
    facebook: ``

  },
  icon: `content/assets/profile.jpeg`, // Add your favicon
  keywords: [`blog`],
  comment: {
    disqusShortName: '', // Your disqus-short-name. check disqus.com.
    utterances: 'JaeYeopHan/gatsby-starter-bee', // Your repository for archive comment
  },
  configs: {
    countOfInitialPost: 10, // Config your initial count of post
  },
  sponsor: {
    buyMeACoffeeId: 'jbee',
  },
  share: {
    facebookAppId: '', // Add facebookAppId for using facebook share feature v3.2
  },
  ga: '', // Add your google analytics tranking ID
}
```

The links seem correct in gatsby-meta-config.js.

答:
I don't know why it's appending %20 in the path.

%20 is the HTML encoding for a space inside the url. You cannot have spaces in your url so it is by default escaped by the HTML encoding.

the url is actually the folder name. I don't know why. Path should've been the title that I've written in index.md of that folder.

You do not do any formatting to your slug in gatsby-node.js:

```<code>    createNodeField({
      name: `slug`,
      node,
      value,
    })
</code>```

Without formatting the slug, your url defaults to the path inside your project.

My advise: Don't format the slug. Remove spaces from your folder path and you have a nice url: /content/blog/javascript-behind-the-scenes/index.md. The use of the hypen character - is also recommened by Google. Having an URL like that ranks better in SEO.

Also, I have some problem with the Github and Twitter links. When I click them, it shows page not found. Weird url it shows is: https://github.com/https://github.com/myGithubName https://twitter.com/https://twitter.com/myTwitterName

Supply only your social network's username in your gatsby-config.js:

```<code>  social: {
    twitter: `myTwitterName`, // remove everything before your username
    github: `myGithubName`, // remove everything before your username
    medium: ``,
    facebook: ``
  },
</code>```

Body:
I have set up a blog using Gatsby's starter template. Right now, when I open an article, the url it shows is- http://localhost:8000/JavaScript:%20Behind%20The%20Scenes/. I looked up this answer and changed the path property but then the page wouldn't load, it just showed an empty page with the same url. I don't know why it's appending %20 in the path.

Note: The path is actually the folder name. For example, in the directory /content/blog/JavaScript:Behind The Scenes/index.md, path that goes in the url is actually the folder name. I don't know why. Path should've been the title that I've written in index.md of that folder.

index.md

---
title: 'The Execution Context'
date: '2020-02-16'
category: "JavaScript"
---

Blog Content..............

gatsby-node.js

const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPostTemplate = path.resolve(`./src/templates/blog-post.js`)

  return graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
                category
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create blog posts pages.
    const posts = result.data.allMarkdownRemark.edges.filter(
      ({ node }) => !!node.frontmatter.category
    )

    posts.forEach((post, index) => {
      const previous = index === posts.length - 1 ? null : posts[index + 1].node
      const next = index === 0 ? null : posts[index - 1].node

      createPage({
        path: post.node.fields.slug,
        component: blogPostTemplate,
        context: {
          slug: post.node.fields.slug,
          previous,
          next,
        },
      })
    })
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })

    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}

Also, I have some problem with the Github and Twitter links. When I click them, it shows page not found. It's showing weird url: https://github.com/https://github.com/myGithubName
https://twitter.com/https://twitter.com/myTwitterName

I checked in where is this located and found out:

gatsby-meta-config.js

module.exports = {
  title: `My Blog`,
  description: `Blog posted about ...`,
  author: `myName`,
  introduction: `I explain with words and code.`,
  siteUrl: `https://gatsby-starter-bee.netlify.com`, // Your blog site url
  social: {
    twitter: `https://twitter.com/myTwitterName`, // Your Twitter account
    github: `https://github.com/myGithubName`,
    medium: ``,
    facebook: ``

  },
  icon: `content/assets/profile.jpeg`, // Add your favicon
  keywords: [`blog`],
  comment: {
    disqusShortName: '', // Your disqus-short-name. check disqus.com.
    utterances: 'JaeYeopHan/gatsby-starter-bee', // Your repository for archive comment
  },
  configs: {
    countOfInitialPost: 10, // Config your initial count of post
  },
  sponsor: {
    buyMeACoffeeId: 'jbee',
  },
  share: {
    facebookAppId: '', // Add facebookAppId for using facebook share feature v3.2
  },
  ga: '', // Add your google analytics tranking ID
}

The links seem correct in gatsby-meta-config.js.

Body:
I don't know why it's appending %20 in the path.

%20 is the HTML encoding for a space inside the url. You cannot have spaces in your url so it is by default escaped by the HTML encoding.

the url is actually the folder name. I don't know why. Path should've been the title that I've written in index.md of that folder.

You do not do any formatting to your slug in gatsby-node.js:

    createNodeField({
      name: `slug`,
      node,
      value,
    })

Without formatting the slug, your url defaults to the path inside your project.

My advise: Don't format the slug. Remove spaces from your folder path and you have a nice url: /content/blog/javascript-behind-the-scenes/index.md. The use of the hypen character - is also recommened by Google. Having an URL like that ranks better in SEO.

Also, I have some problem with the Github and Twitter links. When I click them, it shows page not found. Weird url it shows is: https://github.com/https://github.com/myGithubName https://twitter.com/https://twitter.com/myTwitterName

Supply only your social network's username in your gatsby-config.js:

  social: {
    twitter: `myTwitterName`, // remove everything before your username
    github: `myGithubName`, // remove everything before your username
    medium: ``,
    facebook: ``
  },


问:
Only 1 textbox will populate with parameters passed from another form. Why?
I have a form frmControlSystem that connects to an exterior data source from which I receive strings that go into an array. This form opens another form frmResult_Vote to display that information.
The 2nd form is passed the string array as a parameter along with an integer of how many items to display and one other parameter. This 2nd form will properly enable the .Visible for the needed textBoxes. but only the first textBox will actually show text in it; the others are blank.

The first form uses this code to display the 2nd form:

```<code>frmResult_Vote results = new frmResult_Vote(memberDisplayName, iMemberQty, ConstMembersPlusOne);
results.Show()
</code>```

The second form creates an array of textBoxes so I can loop and make visible only the ones that I want to use as well as populating the .Text attribute. This code is:

```<code>public frmResult_Vote(string[] myVoteMembers, int iMemberQty, int ConstMembersPlusOne)
        {
            InitializeComponent();
            textBox1.Text = "FU";

            TextBox[] memberTextBoxes = new TextBox[ConstMembersPlusOne];

            memberTextBoxes[1] = txtDisplayName1; memberTextBoxes[2] = txtDisplayName2; memberTextBoxes[3] = txtDisplayName3; memberTextBoxes[4] = txtDisplayName4;
            memberTextBoxes[5] = txtDisplayName5; memberTextBoxes[6] = txtDisplayName6; memberTextBoxes[7] = txtDisplayName7; memberTextBoxes[8] = txtDisplayName8;
            memberTextBoxes[9] = txtDisplayName9; memberTextBoxes[10] = txtDisplayName10; memberTextBoxes[11] = txtDisplayName11; memberTextBoxes[12] = txtDisplayName12;

            for (int i = 1; i <= iMemberQty; i++)
            {
                memberTextBoxes[i].Text = myVoteMembers[i];
                memberTextBoxes[i].Visible = true;
            }
        }
</code>```

When the 2nd form displays, the proper quantity of textBoxes will enable, but only the first one will show text.

The second form has 12 textBoxes on it named txtDisplayName1 thru txtDisplayName12. These are what I am using to populate the TextBox array.

Last bits of oddity (at least to me): Every other textBox on the second form was drawn with a different BackColor. That never shows when the first form show() the second form; they all show with the color of white.

In trying to get something to show in the other textBoxes, I have also tried to specifically call by the non-array names like this:

```<code>txtDisplayName1.Text = myVoteMembers[1];
</code>```

This didn't do anything at all.

I have also placed a random textBox on the second form and tried to populate it with this line:

```<code>textBox1.Text = "FU";
</code>```

that textBox also would not populate... but if I comment out the for loop, that textBox1.Text assignment will work. It is called before everything else, as well.

I have verified that the array myVoteMembers has strings in it and when I step through the code I can see the assignment happening here:

```<code>memberTextBoxes[i].Text = myVoteMembers[i];
</code>```

What am I missing here?

答:
You have an exception - possibly here:

```<code>for (int i = 1; i <= iMemberQty; i++)
{
     memberTextBoxes[i].Text = myVoteMembers[i];
     memberTextBoxes[i].Visible = true;
}
</code>```

myVoteMembers array will start from 0 and have iMemberQty number of items. Which means 0-iMemberQty-1 indexes. While you are accessing iMemberQty'th index which throws Index out of Bound Exception

Body:
I have a form frmControlSystem that connects to an exterior data source from which I receive strings that go into an array. This form opens another form frmResult_Vote to display that information.
The 2nd form is passed the string array as a parameter along with an integer of how many items to display and one other parameter. This 2nd form will properly enable the .Visible for the needed textBoxes. but only the first textBox will actually show text in it; the others are blank.

The first form uses this code to display the 2nd form:

frmResult_Vote results = new frmResult_Vote(memberDisplayName, iMemberQty, ConstMembersPlusOne);
results.Show()

The second form creates an array of textBoxes so I can loop and make visible only the ones that I want to use as well as populating the .Text attribute. This code is:

public frmResult_Vote(string[] myVoteMembers, int iMemberQty, int ConstMembersPlusOne)
        {
            InitializeComponent();
            textBox1.Text = "FU";

            TextBox[] memberTextBoxes = new TextBox[ConstMembersPlusOne];

            memberTextBoxes[1] = txtDisplayName1; memberTextBoxes[2] = txtDisplayName2; memberTextBoxes[3] = txtDisplayName3; memberTextBoxes[4] = txtDisplayName4;
            memberTextBoxes[5] = txtDisplayName5; memberTextBoxes[6] = txtDisplayName6; memberTextBoxes[7] = txtDisplayName7; memberTextBoxes[8] = txtDisplayName8;
            memberTextBoxes[9] = txtDisplayName9; memberTextBoxes[10] = txtDisplayName10; memberTextBoxes[11] = txtDisplayName11; memberTextBoxes[12] = txtDisplayName12;

            for (int i = 1; i <= iMemberQty; i++)
            {
                memberTextBoxes[i].Text = myVoteMembers[i];
                memberTextBoxes[i].Visible = true;
            }
        }

When the 2nd form displays, the proper quantity of textBoxes will enable, but only the first one will show text.

The second form has 12 textBoxes on it named txtDisplayName1 thru txtDisplayName12. These are what I am using to populate the TextBox array.

Last bits of oddity (at least to me): Every other textBox on the second form was drawn with a different BackColor. That never shows when the first form show() the second form; they all show with the color of white.

In trying to get something to show in the other textBoxes, I have also tried to specifically call by the non-array names like this:

txtDisplayName1.Text = myVoteMembers[1];

This didn't do anything at all.

I have also placed a random textBox on the second form and tried to populate it with this line:

textBox1.Text = "FU";

that textBox also would not populate... but if I comment out the for loop, that textBox1.Text assignment will work. It is called before everything else, as well.

I have verified that the array myVoteMembers has strings in it and when I step through the code I can see the assignment happening here:

memberTextBoxes[i].Text = myVoteMembers[i];

What am I missing here?

Body:
You have an exception - possibly here:

for (int i = 1; i <= iMemberQty; i++)
{
     memberTextBoxes[i].Text = myVoteMembers[i];
     memberTextBoxes[i].Visible = true;
}

myVoteMembers array will start from 0 and have iMemberQty number of items. Which means 0-iMemberQty-1 indexes. While you are accessing iMemberQty'th index which throws Index out of Bound Exception


问:
My navbar isn't scrolling when I use position: sticky
I have looked over some of the other questions regarding non-sticking nav bars, but I still haven't fixed it. It might have something to do with the way I placed my tags, but I'm not quite sure. I might just be placing the sticky code in the wrong CSS selector.

Here is my code:

#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <header>
      <div id="banner-container">
        <img id="topper" src="./newstop.png" />
      </div>
      <nav id="navbar">
        <div id="side-icon">
          <img src="../copo.png"/>
        </div>
        <div class="link-container">
          <ul id="list-container">
            <li>
              <div class="links">
                <span>Our Story</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Our Vehicles</span></a>
              </div>
            </li>
            <li>
              <div class="links">
                <span>News</span>
              </div>
            </li>
            <li>
              <div class="links">
                <a><span>Sign In</span></a>
              </div>
            </li>
          </ul>
        </div>
      </nav>
    </header></code>```

答:
You forgot to use top: 0; after position: sticky;

Like this

```<code>position: sticky;
top: 0;
</code>```

Body:
I have looked over some of the other questions regarding non-sticking nav bars, but I still haven't fixed it. It might have something to do with the way I placed my tags, but I'm not quite sure. I might just be placing the sticky code in the wrong CSS selector.

Here is my code:

#navbar {
  max-width: 100%;
  background-color: black;
  top: 0;
}

nav span:hover {
  border-bottom: 1px solid rgb(200, 140, 16);
}
nav a:hover {
  color: rgb(200, 140, 16);
}

ul {
  display: flex;
  height: 30px;
  padding: 0px;
}
nav {
  font-family: "Odibee Sans", cursive;
  font-size: 25px;
  margin: 0 auto;
  border-bottom: 1px solid rgb(200, 140, 16);
  z-index: 1;
  text-decoration: none;
  display: flex;
  justify-content: center;
  position: sticky;
}

                Our Story

                Our Vehicles

                News

                Sign In

Body:
You forgot to use top: 0; after position: sticky;

Like this

position: sticky;
top: 0;


问:
Python string input gives error unless with quotes
I thought the input method will take any numeric or string input and print it out. But for string it does not work unless string is in quoted. Why?

答:
In Python 2.7, input() evaluates the input as code, so strings need to be quoted. Python 2.7 has a method called raw_input() that treats all input as strings (no quotes needed).

In Python 3.x, the Python 2.7 raw_input() method was renamed input() and the Python 2.7 input() functionality was replaced by eval(input())

So you can use raw_input() in Python 2.7 or switch to Python 3.x


答:
Make sure that you are running the code on Python 3 and not Python 2.
On python 2 you are needed to quote your input with ""

it seems like there are multiple solution to this though:

input() error - NameError: name '...' is not defined

Title: Python string input gives error unless with quotes

Body: I thought the input method will take any numeric or string input and print it out. But for string it does not work unless string is in quoted. Why?


问:
Using Amazon EventBridge for cross-account event publishing and receiving within an organization
I have an AWS Organization with three AWS Accounts underneath:

master – contains master-bus (EventBridge bus) for the entire application

order-service – contains lambdas publishing to the master-bus

shipping-service – contains lambdas triggered by some rules from master-bus

The green flow is ideal. The red is what I currently have working:

order-service put events to its own local order-bus

order-bus sends all events to master-bus

master-bus sends all events to all child buses (order-bus, shipping-bus)

shipping-bus has a rule filtering for the initial event and sends to target shipping-service

Is it possible to stick to a single event bus in the master account? And then, have different accounts directly interact with it, without intermediate event buses in each separate account?

答: Yes, you don't need a unique bus in each account -- simply create a bus i.e 'master-bus' in all accounts and grants all accounts to put events into it... in each account, you would have a rule that forwards the events to the master account. In the master account, you would then create rules to filter and catch the events you need.</p>


问:
MongoDB: Matching points from one collection with polygons from another
I'm trying to match points in one collection with regions stored in another collection.
Here are examples of documents.

Points:

```<code>{
  "_id" : ObjectId("5e36d904618c0ea59f1eb04f"),
  "gps" : { "lat" : 50.073288, "lon" : 14.43979 },
  "timeAdded" : ISODate("2020-02-02T15:13:22.096Z")
}
</code>```

Regions:

```<code>{
  "_id" : ObjectId("5e49a469afae4a11c4ff3cf7"),
  "type" : "Feature",
  "geometry" : {
    "type" : "Polygon",
    "coordinates" : [
      [
        [ -748397.88, -1049211.61 ],
        [ -748402.77, -1049212.2 ],
        ...
        [ -748410.41, -1049213.11 ],
        [ -748403.05, -1049070.62 ]
      ]
    ]
  },
  "properties" : {
    "Name" : "Region 1"
  }
}
</code>```

And the query I'm trying to construct is something like this:

```<code>db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }},
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: {
            $geometry: {
              type: "Polygon",
              coordinates: "$geometry.coordinates"
            }
          }
        }
      }}
    ],
    as: "district"
  }}
])
</code>```

I'm getting an error:

assert: command failed: {

```<code>    "ok" : 0,
    "errmsg" : "Polygon coordinates must be an array",
    "code" : 2,
    "codeName" : "BadValue"
</code>```

} : aggregate failed

I've noticed the structure of $geoWithin document is same as structure of one I have for each region. So I tried such query:

```<code>db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }},
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: "$geometry.coordinates"
        }
      }}
    ],
    as: "district"
  }}
])
</code>```

The error was same.

I looked up for geoqueries but surprisingly all found mentions had static region document instead of one taken from a collection. So I'm wondering - is it ever possible to map points with regions having that both document collections aren't static and taken from DB?

答:
Unfortunately not possible

You could perform query below if $geometry could deal with MongoDB Aggregation Expressions.

```<code>db.points.aggregate([
  {
    $lookup: {
      from: "regions",
      let: {
        coordinates: [
          "$gps.lon",
          "$gps.lat"
        ]
      },
      pipeline: [
        {
          $addFields: {
            coordinates: "$$coordinates"
          }
        },
        {
          $match: {
            coordinates: {
              $geoWithin: {
                $geometry: {
                  type: "Polygon",
                  coordinates: "$geometry.coordinates"
                }
              }
            }
          }
        }
      ],
      as: "district"
    }
  }
])
</code>```

Body:
I'm trying to match points in one collection with regions stored in another collection.
Here are examples of documents.

Points:

{
  "_id" : ObjectId("5e36d904618c0ea59f1eb04f"),
  "gps" : { "lat" : 50.073288, "lon" : 14.43979 },
  "timeAdded" : ISODate("2020-02-02T15:13:22.096Z")
}

Regions:

{
  "_id" : ObjectId("5e49a469afae4a11c4ff3cf7"),
  "type" : "Feature",
  "geometry" : {
    "type" : "Polygon",
    "coordinates" : [
      [
        [ -748397.88, -1049211.61 ],
        [ -748402.77, -1049212.2 ],
        ...
        [ -748410.41, -1049213.11 ],
        [ -748403.05, -1049070.62 ]
      ]
    ]
  },
  "properties" : {
    "Name" : "Region 1"
  }
}

And the query I'm trying to construct is something like this:

db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }},
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: {
            $geometry: {
              type: "Polygon",
              coordinates: "$geometry.coordinates"
            }
          }
        }
      }}
    ],
    as: "district"
  }}
])

I'm getting an error:

assert: command failed: {

    "ok" : 0,
    "errmsg" : "Polygon coordinates must be an array",
    "code" : 2,
    "codeName" : "BadValue"

} : aggregate failed

I've noticed the structure of $geoWithin document is same as structure of one I have for each region. So I tried such query:

db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }},
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: "$geometry.coordinates"
        }
      }}
    ],
    as: "district"
  }}
])

The error was same.

I looked up for geoqueries but surprisingly all found mentions had static region document instead of one taken from a collection. So I'm wondering - is it ever possible to map points with regions having that both document collections aren't static and taken from DB?

Body:
Unfortunately not possible

You could perform query below if $geometry could deal with MongoDB Aggregation Expressions.

db.points.aggregate([
  {
    $lookup: {
      from: "regions",
      let: {
        coordinates: [
          "$gps.lon",
          "$gps.lat"
        ]
      },
      pipeline: [
        {
          $addFields: {
            coordinates: "$$coordinates"
          }
        },
        {
          $match: {
            coordinates: {
              $geoWithin: {
                $geometry: {
                  type: "Polygon",
                  coordinates: "$geometry.coordinates"
                }
              }
            }
          }
        }
      ],
      as: "district"
    }
  }
])


问:
Why is it a bad idea to refresh access token every time when I sent request?
I was doing react native app and using OAuth2 and get access token, refresh token and expire in time when I log in my App. I checked my token expire in time when I send a request (GET, POST). If my token expired, then I used a refresh token to get a new access token. My co-worker told me, I don't need check expired time, just use a refresh token to get access token every time I sent the request. I know his way is not properly, but what could be happened if I use his way? Why is it bad to refresh access token every time when I sent requests?</p>

答:
Because it increases the network round trips and makes your application slower than it needs to be, and increases the load on the token service.

That way lies scaling problems and terrible user experience.


问:
Program that takes 2 numbers as an input and finds the factorials of those numbers and every number in between?
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.</p>

```<code>Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();

if (n > 0 && m > 0)             //want factorial greater than zero
for(int j = n; j <= m; j++)
{
    for(int i = 1; i <= j; i++)
    {
        result = result * i;    //find factorial
    }
    System.out.println(result);
}
    if(n <= 0 || m <= 0)        //if value is les than zero
    {
        System.out.println("Not Valid!");
    }
</code>```

答:
You forgot to reset 'result' to 1.

Also, there is no need to have another if statement if it is only checking for the negation of the first one, just use an else.

I also fixed the code style guidelines to follow the standard Java ones as:

The curly bracket style you used is the one usually used in C/C++.

Even if if-statements or loops contain only one line after them, it is good etiquette to use curly brackets anyway, in Java.

Take a look at the Google Java Style Guide if you want to know more.

```<code>    Scanner scan = new Scanner(System.in);
    long result = 1;
    int m = scan.nextInt();
    int n = scan.nextInt();
    scan.close();

    if (n > 0 && m > 0){
        for(int j = n; j <= m; j++){
            result = 1; //You forgot to reset 'result'
            for(int i = 1; i <= j; i++){
                result *= i;
            }
        System.out.println(result);
    } else { // No need for another if statement
        System.out.println("Not Valid!");
    }
</code>```

Body:
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.

Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();

if (n > 0 && m > 0)             //want factorial greater than zero
for(int j = n; j <= m; j++)
{
    for(int i = 1; i <= j; i++)
    {
        result = result * i;    //find factorial
    }
    System.out.println(result);
}
    if(n <= 0 || m <= 0)        //if value is les than zero
    {
        System.out.println("Not Valid!");
    }

Body:
You forgot to reset 'result' to 1.

Also, there is no need to have another if statement if it is only checking for the negation of the first one, just use an else.

I also fixed the code style guidelines to follow the standard Java ones as:

The curly bracket style you used is the one usually used in C/C++.

Even if if-statements or loops contain only one line after them, it is good etiquette to use curly brackets anyway, in Java.

Take a look at the Google Java Style Guide if you want to know more.

    Scanner scan = new Scanner(System.in);
    long result = 1;
    int m = scan.nextInt();
    int n = scan.nextInt();
    scan.close();

    if (n > 0 && m > 0){
        for(int j = n; j <= m; j++){
            result = 1; //You forgot to reset 'result'
            for(int i = 1; i <= j; i++){
                result *= i;
            }
        System.out.println(result);
    } else { // No need for another if statement
        System.out.println("Not Valid!");
    }


问:
Is this the correct way to use ConfigureAwait(false)?
I am building a WPF application and calling this custom event.
The question here is should I call ConfigureAwait(false) at everywhere? As you can see now that I am calling it 2 times. Or even 3 times in second approach with double ConfigureAwait(false) in the same line.

```<code>// First approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
}

// Second approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
}

// This function is in a singleton class
public async Task ProcessMethod()
{
    var result = await GetInstance.GetFinalResultFromHttpClientAsync().ConfigureAwait(false);
}
</code>```

答:
Welcome to SO!

If you're writing application code then you probably shouldn't be using it at all. There's a big discussion about this in the ConfigureAwait FAQ on MSDN.

TL;DR:

use ConfigureAwait(false) if you’re writing general-purpose library /
  app-model-agnostic code, and otherwise don’t.

That said, it's a bit of a complex topic, so I'm sure there will be plenty of others here that will disagree. I've written some extremely complex multi-tasked WPF applications, and off the top of my head I can't remember any cases where I've actually needed to use it in application code.

Body:
I am building a WPF application and calling this custom event.
The question here is should I call ConfigureAwait(false) at everywhere? As you can see now that I am calling it 2 times. Or even 3 times in second approach with double ConfigureAwait(false) in the same line.

// First approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod()).ConfigureAwait(false);
}

// Second approach
void RaiseProcessEvent(object sender, EventArgs e)
{
    Task.Run(async () => await APIManager.GetInstance.ProcessMethod().ConfigureAwait(false)).ConfigureAwait(false);
}

// This function is in a singleton class
public async Task ProcessMethod()
{
    var result = await GetInstance.GetFinalResultFromHttpClientAsync().ConfigureAwait(false);
}


问:
Using two independent paths in React Router
I am currently using React Router and have routes that use the browserHistory, for example:

```<code>import { Router, Route, IndexRedirect, browserHistory } from 'react-router';

<Router history={browserHistory}>
  <Route path="tasks" component={Tasks}>
    <IndexRoute component={List} />
    <Route path="/:id" component={Item} />
  </Route>
</Router>
</code>```

Which allows me to do routes such as:

/tasks/

/tasks/1234

This works, but we have come across a situation where we have two views that are displayed at the same time. We'd like for the link to be shareable and have the app open with both views.

So for example, if we have tasks on the left side of the screen, and a shop  on the right, we'd like for there to be two independent parts of the path, something like:

/tasks/1234/#/shop/item/xyz

The shop route should be independent of the left of the hash, and the tasks route should be independent of the right of the hash, so that /new-feature/xyz/#/shop/item/xyz should still render the same view on the right side of the window.

Is it possible to have React Router do routes like this? Or will I have to write a custom router to solve this?

I'm guessing I'd basically have to combine the browserHistory and hashHistory together, but I don't think that's possible with React Router out of the box.

答:
We have developed our own router Boring Router with "parallel routing" support, though it depends on MobX and works differently with React Router in many ways.

In Boring Router, a parallel route is stored as query string parameter prefixed with _. E.g., /app/workbench?_sidebar=/achievements.

Check out a complete example here.

Body:
I am currently using React Router and have routes that use the browserHistory, for example:

import { Router, Route, IndexRedirect, browserHistory } from 'react-router';

<Router history={browserHistory}>
  <Route path="tasks" component={Tasks}>
    <IndexRoute component={List} />
    <Route path="/:id" component={Item} />
  </Route>
</Router>

Which allows me to do routes such as:

/tasks/

/tasks/1234

This works, but we have come across a situation where we have two views that are displayed at the same time. We'd like for the link to be shareable and have the app open with both views.

So for example, if we have tasks on the left side of the screen, and a shop  on the right, we'd like for there to be two independent parts of the path, something like:

/tasks/1234/#/shop/item/xyz

The shop route should be independent of the left of the hash, and the tasks route should be independent of the right of the hash, so that /new-feature/xyz/#/shop/item/xyz should still render the same view on the right side of the window.

Is it possible to have React Router do routes like this? Or will I have to write a custom router to solve this?

I'm guessing I'd basically have to combine the browserHistory and hashHistory together, but I don't think that's possible with React Router out of the box.


问:
How to call old intent when app starts with sharing?
I want to explain my app logic. My app is viewing PDFs. There are 2 ways to show pdfs.

The user logins the app and clicks the Show PDF button. Then, App opens a new window and the user selects a pdf for see it.

The user opens a pdf from his phone storage and shares that pdf to my application. (If the user didn't login to the app before, App opens the login page.)

The first one works fine. But when the user shares a pdf to my app from his phone storage, Application opens my HomePape Automatically.

There are 2 public LoginPage(){} in the app.

1.public LoginPage()

2.public LoginPage(string _pdfUri)

The first one lets user login the app.
The second one if user didn't login the app and shares a pdf to the app. In this way, the app gets pdfpath and opens the PdfShowPage.

Lets check the code,

App.xaml.cs:

/* I debugged this. App always comes here even when The user shares Pdf. Because of this,
PdfShowPage LoginPage works and LoginPage(string _pdfUri) does not work. The app opens HomePage.
Basicly;

LoginPage()  -> HomePage

LoginPage(string _pdfUri) -> PdfShowPage

*/

```<code> public App()
        {
            InitializeComponent();
                MainPage = new NavigationPage(new LoginPage())
                {
                    BarBackgroundColor = Color.FromHex("008000"),
                    BarTextColor = Color.FromHex("E8E8E8")
                };
        }

protected override void OnStart()
        {
           // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
</code>```

MainActivity.cs,

```<code>protected override async void OnCreate(Bundle savedInstanceState)
        {

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            ZXing.Net.Mobile.Forms.Android.Platform.Init();
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

            Share();

        }

private void Share()
{
   //Some codes for share
   Navigate(path);
}

public async void Navigate(string path)
{
            await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new LoginPage(path));

}
</code>```

LoginPage.cs,

```<code>public LoginPage(string _pdfUri)
{
 this.PdfUri = _pdfUri;

 CheckSessionWithUri(_pdfUri); //it checks session and send pdf path to PDFshowPage.
}

public LoginPage()
{

 CheckSession(); //it sends user to the HomePage if the user correctly login or the user has login before.
}
</code>```

I want to control when the user shares a pdf to my app, The app must send him To PdfShowPage. Should we control this on App.xaml.cs or somewhere else ?

Thanks.

答:
Maybe you could pass the _pdfUri to App class,then open LoginPage base on the _pdfUri. like:

```<code>protected override async void OnCreate(Bundle savedInstanceState)
    {

        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        ZXing.Net.Mobile.Forms.Android.Platform.Init();
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        Share();

    }

private void Share()
{
  //Some codes for share
   LoadApplication(new App(_pdfUri));
}
</code>```

then

```<code>public App(string _pdfUri)
    {
        InitializeComponent();
        if(path !=null){
           MainPage = new NavigationPage(new LoginPage(_pdfUri))
            {
                BarBackgroundColor = Color.FromHex("008000"),
                BarTextColor = Color.FromHex("E8E8E8")
            };
        }else{
           MainPage = new NavigationPage(new LoginPage())
            {
                BarBackgroundColor = Color.FromHex("008000"),
                BarTextColor = Color.FromHex("E8E8E8")
            };
        }

    }
</code>```

Body:
I want to explain my app logic. My app is viewing PDFs. There are 2 ways to show pdfs.

The user logins the app and clicks the Show PDF button. Then, App opens a new window and the user selects a pdf for see it.

The user opens a pdf from his phone storage and shares that pdf to my application. (If the user didn't login to the app before, App opens the login page.)

The first one works fine. But when the user shares a pdf to my app from his phone storage, Application opens my HomePape Automatically.

There are 2 public LoginPage(){} in the app.

1.public LoginPage()

2.public LoginPage(string _pdfUri)

The first one lets user login the app.
The second one if user didn't login the app and shares a pdf to the app. In this way, the app gets pdfpath and opens the PdfShowPage.

Lets check the code,

App.xaml.cs:

/* I debugged this. App always comes here even when The user shares Pdf. Because of this,
PdfShowPage LoginPage works and LoginPage(string _pdfUri) does not work. The app opens HomePage.
Basicly;

LoginPage()  -> HomePage

LoginPage(string _pdfUri) -> PdfShowPage

*/

 public App()
        {
            InitializeComponent();
                MainPage = new NavigationPage(new LoginPage())
                {
                    BarBackgroundColor = Color.FromHex("008000"),
                    BarTextColor = Color.FromHex("E8E8E8")
                };
        }

protected override void OnStart()
        {
           // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }

MainActivity.cs,

protected override async void OnCreate(Bundle savedInstanceState)
        {

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            ZXing.Net.Mobile.Forms.Android.Platform.Init();
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

            Share();

        }

private void Share()
{
   //Some codes for share
   Navigate(path);
}

public async void Navigate(string path)
{
            await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new LoginPage(path));

}

LoginPage.cs,

public LoginPage(string _pdfUri)
{
 this.PdfUri = _pdfUri;

 CheckSessionWithUri(_pdfUri); //it checks session and send pdf path to PDFshowPage.
}

public LoginPage()
{

 CheckSession(); //it sends user to the HomePage if the user correctly login or the user has login before.
}

I want to control when the user shares a pdf to my app, The app must send him To PdfShowPage. Should we control this on App.xaml.cs or somewhere else ?

Thanks.

Body:
Maybe you could pass the _pdfUri to App class,then open LoginPage base on the _pdfUri. like:

protected override async void OnCreate(Bundle savedInstanceState)
    {

        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        ZXing.Net.Mobile.Forms.Android.Platform.Init();
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        Share();

    }

private void Share()
{
  //Some codes for share
   LoadApplication(new App(_pdfUri));
}

then

public App(string _pdfUri)
    {
        InitializeComponent();
        if(path !=null){
           MainPage = new NavigationPage(new LoginPage(_pdfUri))
            {
                BarBackgroundColor = Color.FromHex("008000"),
                BarTextColor = Color.FromHex("E8E8E8")
            };
        }else{
           MainPage = new NavigationPage(new LoginPage())
            {
                BarBackgroundColor = Color.FromHex("008000"),
                BarTextColor = Color.FromHex("E8E8E8")
            };
        }

    }


问:
Google Scripts - Add multiple guests to a calendar event from a single cell in a google sheet
I have a Google spreadsheet that we're using to deliver single calendar events to multiple accounts. Code below. I am getting an "Invalid argument" error for .addguest whenever there is more than one email address in the cell I'm trying to pull from (separated by commas).

The code below will pull correctly if only one account is in the cell, but not if multiple accounts are listed with commas in that same cell.

All ideas appreciated.

Thank you!

--Drew

```<code> function onOpen() {
 var s = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "Add Events to Google Calendar", functionName: "scheduleClass"}];
   s.addMenu("Google Calendar Functions", menuEntries);
 }

function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendar = CalendarApp.getCalendarById("primary@group.calendar.google.com");

  var title = sheet.getRange('A2:A').getValues();
  var startTime = sheet.getRange('E2:E').getValues();
  var endTime = sheet.getRange('F2:F').getValues();
  var theDescription = sheet.getRange('G2:G').getValues();
  var theLocation = sheet.getRange('H2:H').getValues();
  var theGuests = sheet.getRange('K2:K').getValues();

  for(var i = 0; i < title.length+1; i++){
    if(title[i][0] != ""){
      calendar.createEvent(title[i][0], startTime[i][0], endTime[i][0]).addGuest(theGuests[i][0]).setLocation(theLocation[i][0]).setDescription(theDescription[i][0]);

    }
  }
}

function toString(value){
  var newString = "" + value;
  return newString;
}
</code>```

答:
You want to create the calendar events with the multiple guests.

In your situation, the value of column "K" is like sample1@gmail.com,sample2@gmail.com which is separated by ,.

The values of columns "A", "E", "F", "G", "H" and "K" in the active sheet are title, start time, end time, description, location and guests, respectively.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

When the guests are separated by ,, you can retrieve each email using split(). And they can be added with addGuest(email).

In your script, an error occurs at the loop by title.length+1 of for(var i = 0; i < title.length+1; i++){.

When you retrieve the values from the data range of "A2:K#", the process cost can be reduced. This was mentioned by Cooper's comment and discussions.

When these points are reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, the calendar service of CalendarApp is used. In this case, scheduleClass() was modified.

Modified script:

```<code>function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendar = CalendarApp.getCalendarById("primary@group.calendar.google.com");
  var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
  for(var i = 0; i < values.length; i++){
    var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
    if(title != "") {
      var event = calendar.createEvent(title, startTime, endTime)
        .setLocation(theLocation)
        .setDescription(theDescription);
      theGuests.split(",").forEach(function(e) {event.addGuest(e.trim())});
    }
  }
}
</code>```

Pattern 2:

In this pattern, Calendar API is used.

Modified script:

When you use this script, please enable Calendar API at Advanced Google services.

```<code>function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendarId = "primary@group.calendar.google.com";
  var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
  for(var i = 0; i < values.length; i++){
    var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
    if(title != "") {
      var resource = {
        start: {dateTime: startTime.toISOString()},
        end: {dateTime: endTime.toISOString()},
        summary: title,
        description: theDescription,
        location: theLocation,
        attendees: theGuests.split(",").map(function(e) {return {email: e.trim()}})
      };
      Calendar.Events.insert(resource, calendarId);
    }
  }
}
</code>```

Note:

Above both modified scripts are the same results.

References:

split()

forEach()

map()

addGuest(email)

Advanced Google services

Events: insert

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
I have a Google spreadsheet that we're using to deliver single calendar events to multiple accounts. Code below. I am getting an "Invalid argument" error for .addguest whenever there is more than one email address in the cell I'm trying to pull from (separated by commas).

The code below will pull correctly if only one account is in the cell, but not if multiple accounts are listed with commas in that same cell.

All ideas appreciated.

Thank you!

--Drew

 function onOpen() {
 var s = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "Add Events to Google Calendar", functionName: "scheduleClass"}];
   s.addMenu("Google Calendar Functions", menuEntries);
 }

function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendar = CalendarApp.getCalendarById("primary@group.calendar.google.com");

  var title = sheet.getRange('A2:A').getValues();
  var startTime = sheet.getRange('E2:E').getValues();
  var endTime = sheet.getRange('F2:F').getValues();
  var theDescription = sheet.getRange('G2:G').getValues();
  var theLocation = sheet.getRange('H2:H').getValues();
  var theGuests = sheet.getRange('K2:K').getValues();

  for(var i = 0; i < title.length+1; i++){
    if(title[i][0] != ""){
      calendar.createEvent(title[i][0], startTime[i][0], endTime[i][0]).addGuest(theGuests[i][0]).setLocation(theLocation[i][0]).setDescription(theDescription[i][0]);

    }
  }
}

function toString(value){
  var newString = "" + value;
  return newString;
}

Body:
You want to create the calendar events with the multiple guests.

In your situation, the value of column "K" is like sample1@gmail.com,sample2@gmail.com which is separated by ,.

The values of columns "A", "E", "F", "G", "H" and "K" in the active sheet are title, start time, end time, description, location and guests, respectively.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

When the guests are separated by ,, you can retrieve each email using split(). And they can be added with addGuest(email).

In your script, an error occurs at the loop by title.length+1 of for(var i = 0; i < title.length+1; i++){.

When you retrieve the values from the data range of "A2:K#", the process cost can be reduced. This was mentioned by Cooper's comment and discussions.

When these points are reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, the calendar service of CalendarApp is used. In this case, scheduleClass() was modified.

Modified script:

function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendar = CalendarApp.getCalendarById("primary@group.calendar.google.com");
  var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
  for(var i = 0; i < values.length; i++){
    var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
    if(title != "") {
      var event = calendar.createEvent(title, startTime, endTime)
        .setLocation(theLocation)
        .setDescription(theDescription);
      theGuests.split(",").forEach(function(e) {event.addGuest(e.trim())});
    }
  }
}

Pattern 2:

In this pattern, Calendar API is used.

Modified script:

When you use this script, please enable Calendar API at Advanced Google services.

function scheduleClass(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendarId = "primary@group.calendar.google.com";
  var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 11).getValues();
  for(var i = 0; i < values.length; i++){
    var [title,,,,startTime,endTime,theDescription,theLocation,,,theGuests] = values[i];
    if(title != "") {
      var resource = {
        start: {dateTime: startTime.toISOString()},
        end: {dateTime: endTime.toISOString()},
        summary: title,
        description: theDescription,
        location: theLocation,
        attendees: theGuests.split(",").map(function(e) {return {email: e.trim()}})
      };
      Calendar.Events.insert(resource, calendarId);
    }
  }
}

Note:

Above both modified scripts are the same results.

References:

split()

forEach()

map()

addGuest(email)

Advanced Google services

Events: insert

If I misunderstood your question and this was not the direction you want, I apologize.


问:
UWP C# Toggleswitch inside Listview - How to get items of Row when clicked on Toggleswitch
So i'm having this Listview with on Toggleswitch. What i want is to do is to fire an event like ItemClick="Event_Overview_Teams_ItemClick"
but with
Toggled="TeamPresent_Toggled"
and work on with the items like TeamID of the clicked row.

```<code><ListView x:Name="Event_Overview_Teams" HorizontalAlignment="Center" Width="1787" Margin="0,48,0,10" IsItemClickEnabled="True" ItemClick="Event_Overview_Teams_ItemClick" SelectionMode="None">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Grid Width="900">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <TextBlock x:Name="TeamName" Grid.Column="0" Text="{Binding TeamName}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamID"   Grid.Column="1" Text="{Binding TeamID}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamNumber" Grid.Column="2" Text="{Binding TeamNumber}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamClass" Grid.Column="3" Text="{Binding TeamClass}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="DeliverTime" Grid.Column="4" Text="{Binding DeliverTime}" TextWrapping="Wrap" />
                                    <!--<TextBlock x:Name="TeamPresent" Grid.Column="5" Text="{Binding TeamPresent}" TextWrapping="Wrap" />-->
                                    <ToggleSwitch x:Name="TeamPresent" Grid.Column="5" IsOn="{Binding TeamPresent}" Toggled="TeamPresent_Toggled"/>
                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</code>```

Thank you very much in advance

答:
When you trigger the TeamPresent_Toggled event, you can get the viewmodel which bound with the current item by getting the DataContext of the ToggleSwitch. Then changing the property(e.g. TeamID) from the viewmodel you get.

```<code>private void TeamPresent_Toggled(object sender, RoutedEventArgs e)
{
    var toggle = (ToggleSwitch)sender;
    var dataContext = toggle.DataContext;
    MyViewModel dataItem = (MyViewModel)dataContext;
    dataItem.TeamID = "MyNewTeamId";
    ......
}
</code>```

Body:
So i'm having this Listview with on Toggleswitch. What i want is to do is to fire an event like ItemClick="Event_Overview_Teams_ItemClick"
but with
Toggled="TeamPresent_Toggled"
and work on with the items like TeamID of the clicked row.

<ListView x:Name="Event_Overview_Teams" HorizontalAlignment="Center" Width="1787" Margin="0,48,0,10" IsItemClickEnabled="True" ItemClick="Event_Overview_Teams_ItemClick" SelectionMode="None">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Grid Width="900">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <TextBlock x:Name="TeamName" Grid.Column="0" Text="{Binding TeamName}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamID"   Grid.Column="1" Text="{Binding TeamID}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamNumber" Grid.Column="2" Text="{Binding TeamNumber}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="TeamClass" Grid.Column="3" Text="{Binding TeamClass}" TextWrapping="Wrap" />
                                    <TextBlock x:Name="DeliverTime" Grid.Column="4" Text="{Binding DeliverTime}" TextWrapping="Wrap" />

                                    <ToggleSwitch x:Name="TeamPresent" Grid.Column="5" IsOn="{Binding TeamPresent}" Toggled="TeamPresent_Toggled"/>
                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

Thank you very much in advance

Body:
When you trigger the TeamPresent_Toggled event, you can get the viewmodel which bound with the current item by getting the DataContext of the ToggleSwitch. Then changing the property(e.g. TeamID) from the viewmodel you get.

private void TeamPresent_Toggled(object sender, RoutedEventArgs e)
{
    var toggle = (ToggleSwitch)sender;
    var dataContext = toggle.DataContext;
    MyViewModel dataItem = (MyViewModel)dataContext;
    dataItem.TeamID = "MyNewTeamId";
    ......
}