问:
How properly add MacOS Signature & Notarization to .app built with Qt
I have an application (built with Qt / QML) that I am trying to sign and notarize for Ad hoc distribution outside the App Store (it's for internal company use).  Apple confirms that my software has been notarized, and I then staple my .app - but Gatekeeper still stops the application from running and alerts users:

App Name can’t be opened because Apple cannot check it for malicious
  software.

What am I doing wrong?.

Here are the steps that I am following:

Ran QMake / Build in Qt Creator.

Modified the CFBundleIdentifier key in the generated Info.plist file to be com.myCompanyName.appName instead of com.yourcompany.appName as generated by Qt.

cd to my build dir.

Ran macdeployqt:
 /Users/<user>/Qt/5.13.0/clang_64/bin/macdeployqt <appName>.app -qmldir=<project source code dir>.

Code Sign:
 codesign --deep -f -s "Developer ID Application: <company name> (<team id>)" --options "runtime" "<appName>.app/"

(Where the developer id application is the name as it appears in KeychainAccess).

Verified that the signature:
 codesign -dv --verbose=4 <appName>.app
 Returns:

```<code>`Executable=<build dir>/<app name>.app/Contents/MacOS/<app name>
Identifier=com.<company name>.<app name>
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=53750 flags=0x10000(runtime) hashes=1674+3 location=embedded
Library validation warning=OS X SDK version before 10.9 does not support Library Validation
VersionPlatform=1
VersionMin=658432
VersionSDK=0
Hash type=sha256 size=32
CandidateCDHash sha256=*************************************
CandidateCDHashFull sha256=*************************************
Hash choices=sha256
CMSDigest=*************************************
CMSDigestType=2
Page size=4096
CDHash=*************************************
Signature size=8990
Authority=Developer ID Application: <my company name> (<my team ID>)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=May 27, 2020 at 2:35:38 PM
Info.plist entries=10
TeamIdentifier=V7L2LD4Q9S
Sealed Resources version=2 rules=13 files=1198
Internal requirements count=1 size=184
</code>```

Or if I look at a (chosen at random) executable from the Qt framework inside the app bundle:
 codesign -dv --verbose=4 <appName>.app/Contents/Frameworks/QtCore.framework/Versions/5/QtCore
 Returns:

```<code>Executable=<build dir>/<app name>.app/Contents/Frameworks/QtCore.framework/Versions/5/QtCore
Identifier=org.qt-project.QtCore
Format=bundle with Mach-O thin (x86_64)
CodeDirectory v=20500 size=49057 flags=0x10000(runtime) hashes=1526+3 location=embedded
VersionPlatform=1
VersionMin=658432
VersionSDK=658944
Hash type=sha256 size=32
CandidateCDHash sha256=*************************************
CandidateCDHashFull sha256=*************************************
Hash choices=sha256
CMSDigest=*************************************
CMSDigestType=2
Page size=4096
CDHash=*************************************
Signature size=8990
Authority=Developer ID Application: <my company name> (<my team ID>)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=May 27, 2020 at 2:35:37 PM
Info.plist entries=8
TeamIdentifier=V7L2LD4Q9S
Runtime Version=10.14.0
Sealed Resources version=2 rules=13 files=1
Internal requirements count=1 size=184
</code>```

zip: ditto -ck --rsrc --sequesterRsrc "<appName>.app" "<appName>.zip"

Upload for notarization:

xcrun altool --notarize-app -t osx -f <appName>.zip --primary-bundle-id="com.<my company name>.<appName>" -u "<develpper ID @ company name> -p "<app specific password>"

Receive an email that "Your Mac software was successfully notarized."

Staple: xcrun stapler staple "<appName>.app"

Returns: The staple and validate action worked!

Distribute:

Create a blank sparse bundle disk image.

Copy the appName.app bundle to it (along with a shortcut to /Applications).

Convert to read only.

Distribute to users.

If I look in Console.app - I can see in the logs that the app is being denied to open:

```<code>default 15:10:56.549137-0400    runningboardd   Invalidating assertion 294-139-3156 (target:executable<<appName>(501)>) from originator 139
default 15:11:01.061942-0400    runningboardd   [executable<<appName>(501)>:4893] Death sentinel fired!
</code>```

There is nothing in the console with XprotectService as this SO answer suggests.

If I try to use spctl to check the signature, it fails:

spctl -v -a -t open --context context:primary-signature <appName>.app

Returns:

```<code>opal.app: rejected
source=Unnotarized Developer ID
</code>```

spctl -a -t exec -vv <appName>.app produces

Returns:

```<code><appName>.app: rejected
source=Unnotarized Developer ID
origin=Developer ID Application: <my company name> (<team ID>)
produces: invalid API object reference
</code>```

However, if I use stapler to validate the app, it passes:

stapler validate <appName>.app

Returns:

```<code>Processing: /<build dir>/<appName>.app
The validate action worked!
</code>```

About my environment:

MacOS 10.15.3

Qt 5.13

Xcode 11.4

答:
The problem is that since you are distributing using a .dmg you need to notarize the .dmg as well. Please follow these steps:

1) Add your notarized and stapled app to the .dmg.

2) Notarize your .dmg file.

3) Staple the notarization to the .dmg file.

You can use the following bash script I created which allows you to create a notarization request, check notarization request staus and staple notarization:

#!/bin/bash

usage()
{
    # Display Help

   echo "*********************************************************************************************************************************************************"
   echo "  MacOS Application Notarization Script"
   echo "*********************************************************************************************************************************************************"
   echo
   echo "   Requirements"
   echo "    - XCode Installed"
   echo "    - Apple Id Account app-specific Password (https://support.apple.com/en-us/HT204397)"
   echo "    - Apple Developer ID Application Certificate created and installed in keychain (https://developer.apple.com/support/developer-id/)"
   echo
   echo "   Instructions"
   echo "    1. Run notarize option to code sign application and create notarization request"
   echo "    2. Run check option with the request UUID of the previous step to check the notarization status"
   echo "    3. Run staple option only if the notarization status was successful and package was approved"
   echo "    4. You are now ready to distribute, if you want to create an installer you can use this option https://github.com/sindresorhus/create-dmg."
   echo "       Note that if you distribute your app in a .dmg, follow these steps:"
   echo
   echo "      - Add your notarized and stapled app to the DMG."
   echo "      - Notarize your .dmg file."
   echo "             Example: sh $0 --notarize -a MyApp.dmg  -b com.company.myapp  -u myappleaccount@gmail.com -p aaaa-aaaa-aaaa-aaa -v FFFFFFFF)"
   echo "      - Staple the notarization to the .dmg file: xcrun stapler staple MyApp.dmg."
   echo "             Example: sh $0 --staple --file MyApp.dmg"
   echo "________________________________________________________________________________________________________________________________________________________"
   echo
   echo "  Usage"
   echo "   $0 [-n|s|c] [ -a APP_NAME ] [ -i SIGNING_IDENTITY ] [ -e ENTITLEMENTS ]  [ -b BUNDLE_ID ] [ -u USERNAME ] [ -p PASSWORD ] [ -v PROVIDER ] [ -k UUID ]"
   echo
   echo "________________________________________________________________________________________________________________________________________________________"
   echo
   echo "  Options:"
   echo
   notarizeHelp
   checkHelp
   stapleHelp

  return
}
notarizeHelp()
{
   echo "    ======================================================================="
   echo "    -n | --notarize  Notarize file"
   echo "    ======================================================================="
   echo "    Syntax:"
   echo "              [ -n | --notarize ] [ -a | --file APP_NAME ] [ -i SIGNING_IDENTITY ] [ -e ENTITLEMENTS ]  [ -b BUNDLE_ID ] [ -u USERNAME ] [ -p PASSWORD ] [ -v PROVIDER ]"
   echo "    Parameters:"
   echo "              [ -a | --file  ]        - File name"
   echo "              [ -i ]                  - Apple Signing identity"
   echo "              [ -e ]                  - Application entitlements file"
   echo "              [ -b ]                  - Application Bundle identifier"
   echo "              [ -u ]                  - Apple Developer ID Username"
   echo "              [ -p ]                  - Application Specific password"
   echo "              [ -v ]                  - Access Provider"
   echo "    Example:"
   echo "       .app   sh $0 --notarize -a MyApp.app  -b com.company.myapp  -u myappleaccount@gmail.com -p aaaa-aaaa-aaaa-aaa -v FFFFFFFF -e App.entitlements -i \"Developer ID Application: COMPANY\""
   echo "       .zip   sh $0 --notarize -a MyApp.app.zip  -b com.company.myapp  -u myappleaccount@gmail.com -p aaaa-aaaa-aaaa-aaa -v FFFFFFFF"
   echo "       .dmg   sh $0 --notarize -a MyApp.dmg  -b com.company.myapp  -u myappleaccount@gmail.com -p aaaa-aaaa-aaaa-aaa -v FFFFFFFF"
   echo
}
checkHelp()
{
   echo "    ======================================================================="
   echo "    -c | --check     Check notarization status"
   echo "    ======================================================================="
   echo "    Syntax:"
   echo "              [ -c | --check ] [ -u USERNAME ] [ -p PASSWORD ] [ -k UUID ]"
   echo "    Parameters:"
   echo "              [ -u ]                  - Apple Developer ID Username"
   echo "              [ -p ]                  - Application Specific password"
   echo "              [ -k ]                  - Notarization Request UUID"
   echo "    Example:"
   echo "              sh $0 --check  -u myappleaccount@gmail.com -p aaaa-aaaa-aaaa-aaa -k ffff-ffffff-ffffff-ffffffffff"
   echo
}
stapleHelp()
{
   echo "    ======================================================================="
   echo "    -s | --staple    Staple file"
   echo "    ======================================================================="
   echo "    Syntax:"
   echo "              [ -s | --staple ] [ -a | --file APP_NAME ]"
   echo "    Parameters:"
   echo "              [ -a | --file  ]        - File name"
   echo "    Example:"
   echo "              sh $0 --staple --file MyApp.app"
   echo
}

#Help Dictionary
helpFunction()
{

   echo ""
   usage
   exit 1
}

# Transform long options to short ones
for arg in "$@"; do
  shift
  case "$arg" in
    "--notarize") set -- "$@" "-n" ;;
    "--staple")   set -- "$@" "-s" ;;
    "--check")    set -- "$@" "-c" ;;
    "--file")     set -- "$@" "-a" ;;
    *)            set -- "$@" "$arg"
  esac
done

while getopts "nsca:i:e:b:v:u:k:p:" option
do
case "${option}"
in
n) ACTION=NOTARIZE;;
s) ACTION=STAPLE;;
c) ACTION=CHECK;;
a) APP_NAME=${OPTARG};;
i) SIGNING_IDENTITY=${OPTARG};;
e) ENTITLEMENTS=${OPTARG};;
b) BUNDLE_ID=${OPTARG};;
p) PASSWORD=${OPTARG};;
v) PROVIDER=${OPTARG};;
u) USERNAME=${OPTARG};;
k) UUID=${OPTARG};;
?) helpFunction ;;
esac
done

do_check()
{
    echo "$UUID"
    if [ -z "${UUID}" ]; then
        echo "[Error] Didn't specify notarization request UUID";
    fi

    if [ -z "${USERNAME}" ]; then
        echo "[Error] Apple ID username is required";
    fi

    if [ -z "${PASSWORD}" ]; then
        echo "[Error] App Specific password is required";
    fi

    if [ -z "${UUID}" ] || [ -z "${USERNAME}" ] || [ -z "${PASSWORD}" ]; then
        echo
        checkHelp
        exit 1
    fi
    echo "[INFO] Checking Notarization status for $UUID"
    xcrun altool --notarization-info "$UUID" -u "$USERNAME" -p "$PASSWORD" --output-format xml

    exit 1
}

sign()
{
    if [ -z "${APP_NAME}" ]; then
        echo "[Error] Didn't specify a filename";
    fi
    if [ -z "${SIGNING_IDENTITY}" ]; then
        echo "[Error] Didn't specify signing identity";
    fi
    if [ -z "${ENTITLEMENTS}" ]; then
        echo "[Error] Didn't specify entitlements file";
    fi
    if [ -z "${BUNDLE_ID}" ]; then
        echo "[Error] Didn't specify bundle identifier";
    fi
    if [ -z "${PROVIDER}" ]; then
        echo "[Error] Didn't specify access provider";
    fi
    if [ -z "${USERNAME}" ]; then
        echo "[Error] Apple ID username is required";
    fi
    if [ -z "${PASSWORD}" ]; then
        echo "[Error] App Specific password is required";
    fi

    if  [ -z "${APP_NAME}" ] || [ -z "${USERNAME}" ] || [ -z "${PASSWORD}" ] || [ -z "${PROVIDER}" ]  || [ -z "${ENTITLEMENTS}" ] || [ -z "${SIGNING_IDENTITY}" ]; then
        echo
        notarizeHelp
        exit 1
    fi

    echo "[INFO] Signing app contents"
    find "$APP_NAME/Contents"|while read fname; do
        if [[ -f $fname ]]; then
            echo "[INFO] Signing $fname"
            codesign --force --timestamp --options=runtime --entitlements "$ENTITLEMENTS" --sign "$SIGNING_IDENTITY" $fname
        fi
    done

    echo "[INFO] Signing app file"

    codesign --force --timestamp --options=runtime --entitlements "$ENTITLEMENTS" --sign "$SIGNING_IDENTITY" "$APP_NAME"

    echo "[INFO] Verifying Code Sign"

    codesign --verify --verbose "$APP_NAME"

    echo "[INFO] Zipping $APP_NAME to ${APP_NAME}.zip"

    ditto -c -k --rsrc --keepParent "$APP_NAME" "${APP_NAME}.zip"

    #echo "[INFO] Uploading $APP_NAME for notarization"

    #xcrun altool --notarize-app -t osx -f "${APP_NAME}.zip" --primary-bundle-id "$BUNDLE_ID" -u "$USERNAME" -p "$PASSWORD" --asc-provider "$PROVIDER"  --output-format xml

    notarizationUpload "${APP_NAME}.zip"
}

notarize()
{

    if [ -z "${APP_NAME}" ]; then
        echo "[Error] Didn't specify a filename";
    fi
    if [ -z "${BUNDLE_ID}" ]; then
        echo "[Error] Didn't specify bundle identifier";
    fi
    if [ -z "${PROVIDER}" ]; then
        echo "[Error] Didn't specify access provider";
    fi
    if [ -z "${USERNAME}" ]; then
        echo "[Error] Apple ID username is required";
    fi
    if [ -z "${PASSWORD}" ]; then
        echo "[Error] App Specific password is required";
    fi

    if  [ -z "${APP_NAME}" ] || [ -z "${USERNAME}" ] || [ -z "${BUNDLE_ID}" ] || [ -z "${PASSWORD}" ] || [ -z "${PROVIDER}" ]; then
        echo
        notarizeHelp
        exit 1
    fi

case "$APP_NAME" in
    *.app)  sign;;
    *.zip)  notarizationUpload "$APP_NAME";;
    *.dmg)  notarizationUpload "$APP_NAME";;
esac

}

notarizationUpload()
{
    echo "[INFO] Uploading $APP_NAME for notarization"
    xcrun altool --notarize-app -t osx -f "$1" --primary-bundle-id "$BUNDLE_ID" -u "$USERNAME" -p "$PASSWORD" --asc-provider "$PROVIDER"  --output-format xml

}

do_staple()
{

    if [ -z "${APP_NAME}" ]; then
        echo "[Error] Didn't specify a filename";
        echo
        stapleHelp
        exit 1
    fi

    echo "[INFO] Stapling $APP_NAME"
    xcrun stapler staple "$APP_NAME"
    echo "[INFO] Validating Staple for $APP_NAME"
    xcrun stapler validate "$APP_NAME"
}

#Excute Action base on the option  -s -n -c
case $ACTION in
STAPLE) do_staple;;
CHECK) do_check;;
NOTARIZE) notarize;;
*) helpFunction;
esac

unset APP_NAME ACTION SIGNING_IDENTITY BUNDLE_ID ENTITLEMENTS USERNAME PASSWORD PROVIDER UUID
```

Body:
I have an application (built with Qt / QML) that I am trying to sign and notarize for Ad hoc distribution outside the App Store (it's for internal company use).  Apple confirms that my software has been notarized, and I then staple my .app - but Gatekeeper still stops the application from running and alerts users:

App Name can’t be opened because Apple cannot check it for malicious
  software.

What am I doing wrong?.

Here are the steps that I am following:

Ran QMake / Build in Qt Creator.

Modified the CFBundleIdentifier key in the generated Info.plist file to be com.myCompanyName.appName instead of com.yourcompany.appName as generated by Qt.

cd to my build dir.

Ran macdeployqt:
 /Users/<user>/Qt/5.13.0/clang_64/bin/macdeployqt <appName>.app -qmldir=<project source code dir>.

Code Sign:
 codesign --deep -f -s "Developer ID Application: <company name> (<team id>)" --options "runtime" "<appName>.app/"

(Where the developer id application is the name as it appears in KeychainAccess).

Verified that the signature:
 codesign -dv --verbose=4 <appName>.app
 Returns:

`Executable=<build dir>/<app name>.app/Contents/MacOS/<app name>
Identifier=com.<company name>.<app name>
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=53750 flags=0x10000(runtime) hashes=1674+3 location=embedded
Library validation warning=OS X SDK version before 10.9 does not support Library Validation
VersionPlatform=1
VersionMin=658432
VersionSDK=0
Hash type=sha256 size=32
CandidateCDHash sha256=*************************************
CandidateCDHashFull sha256=*************************************
Hash choices=sha256
CMSDigest=*************************************
CMSDigestType=2
Page size=4096
CDHash=*************************************
Signature size=8990
Authority=Developer ID Application: <my company name> (<my team ID>)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=May 27, 2020 at 2:35:38 PM
Info.plist entries=10
TeamIdentifier=V7L2LD4Q9S
Sealed Resources version=2 rules=13 files=1198
Internal requirements count=1 size=184

Or if I look at a (chosen at random) executable from the Qt framework inside the app bundle:
 codesign -dv --verbose=4 <appName>.app/Contents/Frameworks/QtCore.framework/Versions/5/QtCore
 Returns:

Executable=<build dir>/<app name>.app/Contents/Frameworks/QtCore.framework/Versions/5/QtCore
Identifier=org.qt-project.QtCore
Format=bundle with Mach-O thin (x86_64)
CodeDirectory v=20500 size=49057 flags=0x10000(runtime) hashes=1526+3 location=embedded
VersionPlatform=1
VersionMin=658432
VersionSDK=658944
Hash type=sha256 size=32
CandidateCDHash sha256=*************************************
CandidateCDHashFull sha256=*************************************
Hash choices=sha256
CMSDigest=*************************************
CMSDigestType=2
Page size=4096
CDHash=*************************************
Signature size=8990
Authority=Developer ID Application: <my company name> (<my team ID>)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=May 27, 2020 at 2:35:37 PM
Info.plist entries=8
TeamIdentifier=V7L2LD4Q9S
Runtime Version=10.14.0
Sealed Resources version=2 rules=13 files=1
Internal requirements count=1 size=184

zip: ditto -ck --rsrc --sequesterRsrc "<appName>.app" "<appName>.zip"

Upload for notarization:

xcrun altool --notarize-app -t osx -f <appName>.zip --primary-bundle-id="com.<my company name>.<appName>" -u "<develpper ID @ company name> -p "<app specific password>"

Receive an email that "Your Mac software was successfully notarized."

Staple: xcrun stapler staple "<appName>.app"

Returns: The staple and validate action worked!

Distribute:

Create a blank sparse bundle disk image.

Copy the appName.app bundle to it (along with a shortcut to /Applications).

Convert to read only.

Distribute to users.

If I look in Console.app - I can see in the logs that the app is being denied to open:

default 15:10:56.549137-0400    runningboardd   Invalidating assertion 294-139-3156 (target:executable<<appName>(501)>) from originator 139
default 15:11:01.061942-0400    runningboardd   [executable<<appName>(501)>:4893] Death sentinel fired!

There is nothing in the console with XprotectService as this SO answer suggests.

If I try to use spctl to check the signature, it fails:

spctl -v -a -t open --context context:primary-signature <appName>.app

Returns:

opal.app: rejected
source=Unnotarized Developer ID

spctl -a -t exec -vv <appName>.app produces

Returns:

<appName>.app: rejected
source=Unnotarized Developer ID
origin=Developer ID Application: <my company name> (<team ID>)
produces: invalid API object reference

However, if I use stapler to validate the app, it passes:

stapler validate <appName>.app

Returns:

Processing: /<build dir>/<appName>.app
The validate action worked!

About my environment:

MacOS 10.15.3

Qt 5.13

Xcode 11.4


来源: stackexchange

问:
Remove current view from superview
Let's say I have a viewcontroller "ViewBViewController". In that viewcontroller I create an instance of the "ViewAViewController" and use the addSubView: method to display this ViewAViewController. It then processes a bunch of information, and is now done. I want it to automatically get removed as a subview when it's done.

I was looking at the removeFromSuperview method, but can't seem to call that from within the viewcontroller whose view I'm trying to remove (my first instinct was [self.view removeFromSuperview], but that gets rid of the entire view, not just the subview I'm after).

The only way I can think of is setting up a delegate protocol, and have View B take care of the unloading of View A on behalf of View A as its delegate. However this approach seems a bit overkill. Am I missing an easier solution?

Thanks in advance!

答: Have you tried: setHidden: YES ?

ContentLicense: CC BY-SA 3.0

Title: Remove current view from superview

Body: Have you tried: setHidden: YES ?


问:
How to improve the performance of 'for loop' to integrate some objects in JS
I have three for loop as below to integrate their objects.

The problem is the length of 'cars' array is 20,000.

So it should runs every 20,000 times for finding same id between company.user and cars.

But the id of cars is unique.

Can I reduce this repeat number in JS?
I want to reduce the taking time.

Thank you for reading it.

p.s. I uploaded same question adding the concrete logic inside of for loop.

```<code>for (let i = 0; i < company.length; i += 1) {
  for (let j = 0; j < company[i].user.length; j += 1) {
    for (let k = 0; k < cars.length; k += 1) {
      if (company[i].user[j].id === cars[k].id) {
        company[i].user[j] = {
          ...company[i].user[j],
          ...cars[k]
        }
      }
    }
  }
}
</code>```

答:
this will optimize your code a little more, but ziga1337 is right, the only effective way is to sort your two objects

```<code>// company: [ { user: [ { id: '?1'
// cars: [ { id: '?2'

for (let iCompagny of compagny) {
  for (let iUser of iCompagny.user) {
    let fCar = cars.find(xCar.id===iUser.id)
    if (fCar) Object.assign(iUser, fCar)
  }
}
</code>```

in case there is always a car.id unique to each user.id:

```<code>let indexCars = cars.reduce((a,c)=>{ a[c.id]=c; return a },{})

compagny.forEach(iCompagny=>{
  iCompagny.user.forEach(iUser=>{ Object.assign(iUser, indexCars[iUser.id]) })
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three for loop as below to integrate their objects.

The problem is the length of 'cars' array is 20,000.

So it should runs every 20,000 times for finding same id between company.user and cars.

But the id of cars is unique.

Can I reduce this repeat number in JS?
I want to reduce the taking time.

Thank you for reading it.

p.s. I uploaded same question adding the concrete logic inside of for loop.

for (let i = 0; i < company.length; i += 1) {
  for (let j = 0; j < company[i].user.length; j += 1) {
    for (let k = 0; k < cars.length; k += 1) {
      if (company[i].user[j].id === cars[k].id) {
        company[i].user[j] = {
          ...company[i].user[j],
          ...cars[k]
        }
      }
    }
  }
}

Body:
this will optimize your code a little more, but ziga1337 is right, the only effective way is to sort your two objects

// company: [ { user: [ { id: '?1'
// cars: [ { id: '?2'

for (let iCompagny of compagny) {
  for (let iUser of iCompagny.user) {
    let fCar = cars.find(xCar.id===iUser.id)
    if (fCar) Object.assign(iUser, fCar)
  }
}

in case there is always a car.id unique to each user.id:

let indexCars = cars.reduce((a,c)=>{ a[c.id]=c; return a },{})

compagny.forEach(iCompagny=>{
  iCompagny.user.forEach(iUser=>{ Object.assign(iUser, indexCars[iUser.id]) })
})


问:
How to restrict gerrit repository options configurations?
Right now anyone belonging to a generic group can change repository options configurations like state, submit type, etc. How do I restrict this to just a certain group? Thinking maybe it's in the ACL?

答:
Someone can change repository options if he/she has the "ALLOW" permission in the "Owner" control access on "refs/*" reference:

See more details in the Gerrit documentation here and here.


问:
Joining Models in Python DRF Serializer without introducing Foreign key
So I am relatively new to Django, and DRF. I recently started a project to learn more about the platform.

I also found best practice guide line which I am following at the moment. Here is the Django Style Guide

The guild line says that every App should completely decouple itself and use UUID instead of foreign key,
And every business rule should go into services.py (Which I like btw.)

Here comes the problem. I am not sure how I can construct two models together to produce a nested JSON Output.

Ex: I have Post() model and Comments() model. and Comment model uses uuid of Post model as a referential id.

Now in my API.py, I am not sure how I can join these two together in the Serializer.py

FYI the code below is only for demo purposes, may not be executable

Model

```<code>class Post(models.Model):
    user_id = models.UUIDField(default=uuid.uuid4)
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    pictures = models.CharField(max_length=100)
    lat = models.CharField(max_length=16)
    long = models.CharField(max_length=16)
    vote = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    post_id =  models.UUIDField(default=uuid.uuid4)
    parent_id = models.ForeignKey("self", on_delete=models.CASCADE)
    text = models.CharField(max_length=1000)
    up_vote = models.IntegerField()
    down_vote = models.IntegerField()
    user_id = models.UUIDField(default=uuid.uuid4)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)
</code>```

Service

```<code>def get_report(id) -> Dict:
    logger.info('Get an Report by Id')

    post= Post.objects.get(id=id)

    return {
        'post'= post
    }

def get_comments(id) -> Dict:
    logger.info('Get an Report by Id')

    comments = Comment.objects.filter(post_id=id)

    return {
        'comments' = comments
    }
</code>```

API

```<code>class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentsSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)
</code>```

答:
You could create one serializer called OutputSerializer and include the comments as its own field? if you change comments = OutputCommentSerializer to comments = CommentsSerializer(many=True, read_only=True) I believe that will depict what you want...(example below).  You already defined CommentSerializer, thus you can use it.

```<code>class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)
</code>```

Body:
So I am relatively new to Django, and DRF. I recently started a project to learn more about the platform.

I also found best practice guide line which I am following at the moment. Here is the Django Style Guide

The guild line says that every App should completely decouple itself and use UUID instead of foreign key,
And every business rule should go into services.py (Which I like btw.)

Here comes the problem. I am not sure how I can construct two models together to produce a nested JSON Output.

Ex: I have Post() model and Comments() model. and Comment model uses uuid of Post model as a referential id.

Now in my API.py, I am not sure how I can join these two together in the Serializer.py

FYI the code below is only for demo purposes, may not be executable

Model

class Post(models.Model):
    user_id = models.UUIDField(default=uuid.uuid4)
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    pictures = models.CharField(max_length=100)
    lat = models.CharField(max_length=16)
    long = models.CharField(max_length=16)
    vote = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    post_id =  models.UUIDField(default=uuid.uuid4)
    parent_id = models.ForeignKey("self", on_delete=models.CASCADE)
    text = models.CharField(max_length=1000)
    up_vote = models.IntegerField()
    down_vote = models.IntegerField()
    user_id = models.UUIDField(default=uuid.uuid4)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

Service

def get_report(id) -> Dict:
    logger.info('Get an Report by Id')

    post= Post.objects.get(id=id)

    return {
        'post'= post
    }

def get_comments(id) -> Dict:
    logger.info('Get an Report by Id')

    comments = Comment.objects.filter(post_id=id)

    return {
        'comments' = comments
    }

API

class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentsSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)

Body:
You could create one serializer called OutputSerializer and include the comments as its own field? if you change comments = OutputCommentSerializer to comments = CommentsSerializer(many=True, read_only=True) I believe that will depict what you want...(example below).  You already defined CommentSerializer, thus you can use it.

class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)


问:
ScreenUpdating does not allow to close workbooks
I have some problem with closing workbooks in my macro. I wanted to speed up my macro by using:

```<code>Application.ScreenUpdating = False
'my code
Application.ScreenUpdating = True
</code>```

But when it finish, suddenly all workbooks which I have been using open together. I wanted to close them so I add * Workbooks.Close * lines. Unfortunately, error appears when VBA reaches this code line.It is because excel "can't see" my workbooks. When I close error windows and try to run closing lines once again everything works properly, because workbooks had enough time to open. Probably excel need some time to update and open all workbooks, so I should postpone my code. I have tried * Application.Wait * and * Do Until loop *, but it did't work. I also have tried to close those workbooks before screen updating but excel just  ignored those lines.

My last code lines:

```<code>Application.ScreenUpdating = True

Application.DisplayAlerts = False

Workbooks(wb_1).Close
Workbooks(wb_2).Close

Application.DisplayAlerts = True
</code>```

Thanks in advance for help!

答:
As Damian said,
try to add:

```<code>Workbooks(wb_1).Close savechanges:=false
Workbooks(wb_2).Close savechanges:=false
</code>```

or true if needed

Body:
I have some problem with closing workbooks in my macro. I wanted to speed up my macro by using:

Application.ScreenUpdating = False
'my code
Application.ScreenUpdating = True

But when it finish, suddenly all workbooks which I have been using open together. I wanted to close them so I add * Workbooks.Close * lines. Unfortunately, error appears when VBA reaches this code line.It is because excel "can't see" my workbooks. When I close error windows and try to run closing lines once again everything works properly, because workbooks had enough time to open. Probably excel need some time to update and open all workbooks, so I should postpone my code. I have tried * Application.Wait * and * Do Until loop *, but it did't work. I also have tried to close those workbooks before screen updating but excel just  ignored those lines.

My last code lines:

Application.ScreenUpdating = True

Application.DisplayAlerts = False

Workbooks(wb_1).Close
Workbooks(wb_2).Close

Application.DisplayAlerts = True

Thanks in advance for help!

Body:
As Damian said,
try to add:

Workbooks(wb_1).Close savechanges:=false
Workbooks(wb_2).Close savechanges:=false

or true if needed


问:
day wise contingency table in R using table()
I have a datatable with timestamp, temperature and status columns. I am trying to find out a contingency table in R using some frequency ranges. Now I am getting it. I have a column for timestamp in my data. I need to get day wise contingency table.

```<code>result = as.data.frame(table(cut(df$temp,breaks=c(0,30,60,80,100,1000),labels=c("0-30","30-60","60-80","80-100","100>"))))
</code>```

Output :

```<code>Var1    Freq
0-30    1398
30-60   1051
60-80   1006
80-100  36
100>    2
</code>```

Expected output:

```<code>Date             Var1    Freq
05-01-2020      0-30    1398
05-01-2020      30-60   1051
05-01-2020      60-80   1006
05-01-2020      80-100  36
05-01-2020      100>    2
06-01-2020      0-30    1398
06-01-2020      30-60   1051
06-01-2020      60-80   1006
06-01-2020      80-100  36
06-01-2020      100>    2
</code>```

Also, I have status column with 1 and 0 as values. How to add that also along with date in the output.

Body:
I have a datatable with timestamp, temperature and status columns. I am trying to find out a contingency table in R using some frequency ranges. Now I am getting it. I have a column for timestamp in my data. I need to get day wise contingency table.

result = as.data.frame(table(cut(df$temp,breaks=c(0,30,60,80,100,1000),labels=c("0-30","30-60","60-80","80-100","100>"))))

Output :

Var1    Freq
0-30    1398
30-60   1051
60-80   1006
80-100  36
100>    2

Expected output:

Date             Var1    Freq
05-01-2020      0-30    1398
05-01-2020      30-60   1051
05-01-2020      60-80   1006
05-01-2020      80-100  36
05-01-2020      100>    2
06-01-2020      0-30    1398
06-01-2020      30-60   1051
06-01-2020      60-80   1006
06-01-2020      80-100  36
06-01-2020      100>    2

Also, I have status column with 1 and 0 as values. How to add that also along with date in the output.

Body:
Your desired output with some created dates:

library(lubridate)

df <- read_table2("Var1    Freq
0-30    1398
30-60   1051
60-80   1006
80-100  36
100>    2")

date <- data.frame(Date=seq(dmy("05-01-2020"), length=2, by="1 day"))

df <- merge(df, date, all=TRUE)
df
# > df
#      Var1 Freq       Days
# 1    0-30 1398 2020-01-05
# 2   30-60 1051 2020-01-05
# 3   60-80 1006 2020-01-05
# 4  80-100   36 2020-01-05
# 5    100>    2 2020-01-05
# 6    0-30 1398 2020-01-06
# 7   30-60 1051 2020-01-06
# 8   60-80 1006 2020-01-06
# 9  80-100   36 2020-01-06
# 10   100>    2 2020-01-06


问:
Finding the Output file in CodeBlocks
I wanted to know where the output of CodeBlocks is located (i.e whatever information is shown in the Debugger Window.)
And also i wanted to export this output file to a text or xml or an html file.
Can someone please suggest how this process should be carried out.  </p>

答:
I guess you are searching freopen() function in c++. In that case you can try freopen('example.txt','w',stdout) to write your outputs in example.txt file.

This may help you- http://www.cplusplus.com/reference/cstdio/freopen/

Title: Finding the Output file in CodeBlocks


问:
Docker Swarm and Postgraphile: How to add DATABASE_URL_FILE environment variable?
I am actually new to programming and Docker. I tried to rebuild the graphile/postgraphile:4.7.0 image to add DATABASE_URL_FILE environment variable support. This is what I do and the output.

Dockerfile

```<code>FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"

# Install PostGraphile and PostGraphile connection filter plugin
RUN npm install -g postgraphile
RUN npm install -g postgraphile-plugin-connection-filter

EXPOSE 5000

# patch postgraphile:4.7.1; DATABASE_URL_FILE environment variable implementation.
RUN apk add bash
COPY docker-entrypoint.sh /usr/local/bin/
RUN ln -s /usr/local/bin/docker-entrypoint.sh / # backwards compat
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["postgraphile", "-n", "0.0.0.0"]
</code>```

docker-entrypoint.sh copied from postgres docker-entrypoint.sh

```<code>#!/usr/bin/env bash

# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
    local var="$1"
    local fileVar="${var}_FILE"
    local def="${2:-}"
    if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
        echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
        exit 1
    fi
    local val="$def"
    if [ "${!var:-}" ]; then
        val="${!var}"
    elif [ "${!fileVar:-}" ]; then
        val="$(< "${!fileVar}")"
    fi
    export "$var"="$val"
    unset "$fileVar"
}

# Loads various settings that are used elsewhere in the script
# This should be called before any other functions
docker_setup_env() {
    file_env 'DATABASE_URL'
}
</code>```

output

```<code>$ docker-compose up postgraphile
Attaching to test_postgraphile_1
test_postgraphile_1  | exited with code 0
</code>```

Sincerely,
kidfrom

答:
Edit: Benjie (Postgraphile maintainer) helped me alot on this one. This should work as is.

Dockerfile

```<code>FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"

# Install PostGraphile and PostGraphile connection filter plugin
RUN npm install -g postgraphile
RUN npm install -g postgraphile-plugin-connection-filter

EXPOSE 5000

# patch postgraphile:4.7.1; DATABASE_URL_FILE environment variable implementation.
RUN apk add bash
COPY docker-entrypoint.sh /usr/local/bin/
RUN ln -s /usr/local/bin/docker-entrypoint.sh / # backwards compat
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["postgraphile", "-n", "0.0.0.0"]
</code>```

docker-entrypoint.sh copied from postgres docker-entrypoint.sh

```<code>#!/usr/bin/env bash

# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
    local var="$1"
    local fileVar="${var}_FILE"
    local def="${2:-}"
    if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
        echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
        exit 1
    fi
    local val="$def"
    if [ "${!var:-}" ]; then
        val="${!var}"
    elif [ "${!fileVar:-}" ]; then
        val="$(< "${!fileVar}")"
    fi
    export "$var"="$val"
    unset "$fileVar"
}

# Loads various settings that are used elsewhere in the script
# This should be called before any other functions
docker_setup_env() {
    file_env 'DATABASE_URL'
}

# call the function
docker_setup_env

# call postgraphile
exec "$@"
</code>```

Sincerely,
kidfrom

Body:
I am actually new to programming and Docker. I tried to rebuild the graphile/postgraphile:4.7.0 image to add DATABASE_URL_FILE environment variable support. This is what I do and the output.

Dockerfile

FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"

# Install PostGraphile and PostGraphile connection filter plugin
RUN npm install -g postgraphile
RUN npm install -g postgraphile-plugin-connection-filter

EXPOSE 5000

# patch postgraphile:4.7.1; DATABASE_URL_FILE environment variable implementation.
RUN apk add bash
COPY docker-entrypoint.sh /usr/local/bin/
RUN ln -s /usr/local/bin/docker-entrypoint.sh / # backwards compat
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["postgraphile", "-n", "0.0.0.0"]

docker-entrypoint.sh copied from postgres docker-entrypoint.sh

#!/usr/bin/env bash

# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
    local var="$1"
    local fileVar="${var}_FILE"
    local def="${2:-}"
    if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
        echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
        exit 1
    fi
    local val="$def"
    if [ "${!var:-}" ]; then
        val="${!var}"
    elif [ "${!fileVar:-}" ]; then
        val="$(< "${!fileVar}")"
    fi
    export "$var"="$val"
    unset "$fileVar"
}

# Loads various settings that are used elsewhere in the script
# This should be called before any other functions
docker_setup_env() {
    file_env 'DATABASE_URL'
}

output

$ docker-compose up postgraphile
Attaching to test_postgraphile_1
test_postgraphile_1  | exited with code 0

Sincerely,
kidfrom

Body:
Edit: Benjie (Postgraphile maintainer) helped me alot on this one. This should work as is.

Dockerfile

FROM node:alpine
LABEL description="Instant high-performance GraphQL API for your PostgreSQL database https://github.com/graphile/postgraphile"

# Install PostGraphile and PostGraphile connection filter plugin
RUN npm install -g postgraphile
RUN npm install -g postgraphile-plugin-connection-filter

EXPOSE 5000

# patch postgraphile:4.7.1; DATABASE_URL_FILE environment variable implementation.
RUN apk add bash
COPY docker-entrypoint.sh /usr/local/bin/
RUN ln -s /usr/local/bin/docker-entrypoint.sh / # backwards compat
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["postgraphile", "-n", "0.0.0.0"]

docker-entrypoint.sh copied from postgres docker-entrypoint.sh

#!/usr/bin/env bash

# usage: file_env VAR [DEFAULT]
#    ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
#  "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
    local var="$1"
    local fileVar="${var}_FILE"
    local def="${2:-}"
    if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
        echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
        exit 1
    fi
    local val="$def"
    if [ "${!var:-}" ]; then
        val="${!var}"
    elif [ "${!fileVar:-}" ]; then
        val="$(< "${!fileVar}")"
    fi
    export "$var"="$val"
    unset "$fileVar"
}

# Loads various settings that are used elsewhere in the script
# This should be called before any other functions
docker_setup_env() {
    file_env 'DATABASE_URL'
}

# call the function
docker_setup_env

# call postgraphile
exec "$@"

Sincerely,
kidfrom


问:
Python - count number of elements that are equal between two columns of two dataframes
I have two dataframes: df1, df2
that contain two columns, col1 and col2. I would like to calculate the number of elements in column col1 of df1 that are equal to col2 of df2. How can I do that?

答:
You can use Series.isin df1.col1.isin(df2.col2).sum():

df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6]})
df2 = pd.DataFrame({'col2': [1, 3, 5, 7]})

nb_comon_elements = df1.col1.isin(df2.col2).sum()

assert nb_comon_elements == 3
```

<p>Be cautious depending on your use case because: </p>

<pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'col1': [1, 1, 1, 2, 7]})
df1.col1.isin(df2.col2).sum()
</code>```

Would return 4 and not 2, because all 1 from df1.col1 are present in df2.col2. If that's not the expected behaviour you could drop duplicates from df1.col1 before testing the intersection size:

df1.col1.drop_duplicates().isin(df2.col2).sum()
```

<p>Which in this example would return 2.</p>

<p>To better understand why this is happening you can have look at what <code>.isin</code> is returning: </p>

<pre class="lang-py prettyprint-override"><code>df1['isin df2.col2'] = df1.col1.isin(df2.col2)
</code>```

Which gives:

   col1  isin df2.col2
0     1           True
1     1           True
2     1           True
3     2          False
4     7           True
```

Now .sum() adds up the booleans from column isin df2.col2 (a total of 4 True).

Body:
You can use Series.isin df1.col1.isin(df2.col2).sum():

df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6]})
df2 = pd.DataFrame({'col2': [1, 3, 5, 7]})

nb_comon_elements = df1.col1.isin(df2.col2).sum()

assert nb_comon_elements == 3

Be cautious depending on your use case because:

df1 = pd.DataFrame({'col1': [1, 1, 1, 2, 7]})
df1.col1.isin(df2.col2).sum()

Would return 4 and not 2, because all 1 from df1.col1 are present in df2.col2. If that's not the expected behaviour you could drop duplicates from df1.col1 before testing the intersection size:

df1.col1.drop_duplicates().isin(df2.col2).sum()

Which in this example would return 2.

To better understand why this is happening you can have look at what .isin is returning:

df1['isin df2.col2'] = df1.col1.isin(df2.col2)

Which gives:

   col1  isin df2.col2
0     1           True
1     1           True
2     1           True
3     2          False
4     7           True

Now .sum() adds up the booleans from column isin df2.col2 (a total of 4 True).


问:
How to integrate sign in with apple in iOS 12 or earlier?
My app was rejected due to a third-party login service.
So I've implemented Sign in with Apple for iOS 13.
Problem is how to provide backward compatibility for iOS 12 or earlier.</p>

答:
Apple nowadays recommends it's Sign in with Apple JS in combination with their REST API.

You basically create an own button that uses the Apple Marketing resource images and then call their REST API to initiate the authorization flow. For the initial log-in window, you can use a WKWebView and handle the callback URL via the successful / failed redirect.


问:
How to get a scrollable left-hand-side menu in this Wordpress theme
I am trying to modify the CSS code for the underlying Worpress theme for this site: https://isspm2021.webs.upv.es/. The theme is this one: https://wordpress.org/themes/escapade/.

What I am trying to do is get a vertically scrollable left menu when the screen size is, say, 1024 × 768.

This is what I get now:

As you can see, the last items of the left menu remain hidden and inaccessible, depending on the screen size. I would like the left-hand-side menu to be vertically scrollable when needed.

I've tried several CSS instructions, like overflow:scroll, without success.

I think it is because of the theme itself; more precisely, because of the way the different div elements are defined to be placed regarding others (position:relative and so on).

Any hint of how to modify the CSS style of this theme to get what I need?

答:
If you can accept the full left navbar scrollable, you may add overflow: auto property in .side-masthead:

```<code>.side-masthead {
    background-color: #f5f5f5;
    overflow: auto; /* Add overflow property */
}
</code>```

Body:
If you can accept the full left navbar scrollable, you may add overflow: auto property in .side-masthead:

.side-masthead {
    background-color: #f5f5f5;
    overflow: auto; /* Add overflow property */
}


问:
Adding SSH Keys to Windows Azure
I'm trying to setup continuous deployment for an Azure website using bitbucket.

The problem is I'm using a submodule (which I own) that Azure doesn't have permission to, because it doesn't add that by default.

I'm trying to figure out how to add an SSH key so that Azure can connect and get the submodule.

Steps I've taken.

Created a New Public/Private Key with PuttyGen, Added the public key to my bitbucket account under the name Azure

FTPed into Azure, and added both the public and private key files (.ppk) to the .ssh directory (yeah I didn't know which one I was suppose to add).  They are named azurePrivateKey.ppk, and azurePublicKey.

Updated my config file to look like this

```<code> HOST *
StrictHostKeyChecking no

Host bitbucket.org
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/azurePrivateKey.ppk
</code>```

(no clue if that's right)

Updated my Known Hosts to look like this

```<code>bitbucket.org,131.103.20.168, <!--some key here...it was here when i opened the file, assuming it's the public key for the repo i tried to add-->
bitbucket.org,131.103.20.168, <!--the new public key i tried to add-->
</code>```

And I still get the same error, no permission to get submodule.  So i'm having trouble figuring out which step I did incorrectly as I've never done this before.

答:
So if you like me had multiple private submodules on the same github account as the app service is deployed at you can give your service access to all your modules by moving the deployment key.

Go to the repo where your service is hosted.

In settings go to deploy keys.

Remove the deployment key.

Get the public key from https://[your-web-app].scm.azurewebsites.net/api/sshkey?ensurePublicKey=1

Add the key to your SSH keys in the account settings for github.

If you have modules on several accounts you can add the same key to each account.

After this the service can access private repos on all accounts with the key.

Title: Adding SSH Keys to Windows Azure

Body:
I'm trying to setup continuous deployment for an Azure website using bitbucket.

The problem is I'm using a submodule (which I own) that Azure doesn't have permission to, because it doesn't add that by default.

I'm trying to figure out how to add an SSH key so that Azure can connect and get the submodule.

Steps I've taken.

Created a New Public/Private Key with PuttyGen, Added the public key to my bitbucket account under the name Azure

FTPed into Azure, and added both the public and private key files (.ppk) to the .ssh directory (yeah I didn't know which one I was suppose to add).  They are named azurePrivateKey.ppk, and azurePublicKey.

Updated my config file to look like this

 HOST *
StrictHostKeyChecking no

Host bitbucket.org
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/azurePrivateKey.ppk

(no clue if that's right)

Updated my Known Hosts to look like this

bitbucket.org,131.103.20.168,
bitbucket.org,131.103.20.168,

And I still get the same error, no permission to get submodule.  So i'm having trouble figuring out which step I did incorrectly as I've never done this before.


问:
Spring Cloud Kubernetes + Spring Cloud Gateway: Unable to find instance for k8s service
I am using Spring Cloud Kubernetes + Spring Cloud Gateway(SCG) and I have some trouble to deploy my app on GKE.
SCG does not find k8s service, I still get this error:

```<code>There was an unexpected error (type=Service Unavailable, status=503).
Unable to find instance for uiservice
</code>```

uiservice is Angular app.

When I take a look at .../actuator/gateway/routes I have this result:

```<code>[
  {
    "route_id": "CompositeDiscoveryClient_gateway",
    "route_definition": {
      "id": "CompositeDiscoveryClient_gateway",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "pattern": "/gateway/**"
          }
        }
      ],
      "filters": [
        {
          "name": "RewritePath",
          "args": {
            "regexp": "/gateway/(?<remaining>.*)",
            "replacement": "/${remaining}"
          }
        }
      ],
      "uri": "lb://gateway",
      "order": 0
    },
    "order": 0
  },
  {
    "route_id": "CompositeDiscoveryClient_uiservice",
    "route_definition": {
      "id": "CompositeDiscoveryClient_uiservice",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "pattern": "/uiservice/**"
          }
        }
      ],
      "filters": [
        {
          "name": "RewritePath",
          "args": {
            "regexp": "/uiservice/(?<remaining>.*)",
            "replacement": "/${remaining}"
          }
        }
      ],
      "uri": "lb://uiservice",
      "order": 0
    },
    "order": 0
  },
  {
    "route_id": "uiservice_route",
    "route_definition": {
      "id": "uiservice_route",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "_genkey_0": "/*"
          }
        }
      ],
      "filters": [],
      "uri": "lb://uiservice",
      "order": 0
    },
    "order": 0
  },
  ....
]
</code>```

Please note that services are well discovered because of that: "route_id": "CompositeDiscoveryClient_gateway" and "route_id": "CompositeDiscoveryClient_uiservice", those routes are not mine (I did not define them).

I took a look at this post:How to set up Spring Cloud Gateway application so it can use the Service Discovery of Spring Cloud Kubernetes?
without success.

My configuration:

```<code>   spring:
      profiles:
        active: prod
      cloud:
        kubernetes:
          reload:
            enabled: true
        gateway:
          discovery:
            locator:
              enabled: true
              lower-case-service-id: true
          globalcors:
            cors-configurations:
              '[/**]':
                allowedOrigins: uiservice
                allowedMethods: "*"
                allowCredentials: true
                maxAge: 7200
                allowedHeaders: "*"
                exposedHeaders:
                - "Access-Control-Allow-Origin"
                - "Access-Control-Allow-Methods"
                - "Access-Control-Max-Age"
                - "Access-Control-Allow-Headers"
                - "Cache-Control"
                - "Authorization"
                - "Content-Type"
          routes:
          #======UISERVICE========
          - id: uiservice_route
            uri: lb://uiservice
            predicates:
            - Path=/* #default route

          - id: uiservice_route_assets
            uri: lb://uiservice
            predicates:
            - Path=/assets/**
   management:
      endpoints:
        web:
          exposure:
            include: "*"
      endpoint:
          restart:
            enabled: true
</code>```

Also, how can I disable gateway autodiscovering? I don't want the "route_id": "CompositeDiscoveryClient_gateway"

Dependencies:

```<code><dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-all</artifactId>
</dependency>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

Thanks for your help

答:
It should be look like this:

```<code>spring:
  application.name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          url-expression: "'http://'+serviceId+':'+getPort()"
          lower-case-service-id: true
</code>```

When call http://gateway/my-service-name/api/etc, and then will call my-service-name/api/etc if the service is present in kubernetes

So you need makesure there have a service like :

```<code>apiVersion: v1
kind: Service
metadata:
  name: my-service-name
  namespace: default
  labels:
    app: my-service-name
spec:
  type: NodePort
  ports:
    - port: 8080
      nodePort: 30080
  selector:
    app: my-service-name
</code>```

Body:
I am using Spring Cloud Kubernetes + Spring Cloud Gateway(SCG) and I have some trouble to deploy my app on GKE.
SCG does not find k8s service, I still get this error:

There was an unexpected error (type=Service Unavailable, status=503).
Unable to find instance for uiservice

uiservice is Angular app.

When I take a look at .../actuator/gateway/routes I have this result:

[
  {
    "route_id": "CompositeDiscoveryClient_gateway",
    "route_definition": {
      "id": "CompositeDiscoveryClient_gateway",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "pattern": "/gateway/**"
          }
        }
      ],
      "filters": [
        {
          "name": "RewritePath",
          "args": {
            "regexp": "/gateway/(?<remaining>.*)",
            "replacement": "/${remaining}"
          }
        }
      ],
      "uri": "lb://gateway",
      "order": 0
    },
    "order": 0
  },
  {
    "route_id": "CompositeDiscoveryClient_uiservice",
    "route_definition": {
      "id": "CompositeDiscoveryClient_uiservice",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "pattern": "/uiservice/**"
          }
        }
      ],
      "filters": [
        {
          "name": "RewritePath",
          "args": {
            "regexp": "/uiservice/(?<remaining>.*)",
            "replacement": "/${remaining}"
          }
        }
      ],
      "uri": "lb://uiservice",
      "order": 0
    },
    "order": 0
  },
  {
    "route_id": "uiservice_route",
    "route_definition": {
      "id": "uiservice_route",
      "predicates": [
        {
          "name": "Path",
          "args": {
            "_genkey_0": "/*"
          }
        }
      ],
      "filters": [],
      "uri": "lb://uiservice",
      "order": 0
    },
    "order": 0
  },
  ....
]

Please note that services are well discovered because of that: "route_id": "CompositeDiscoveryClient_gateway" and "route_id": "CompositeDiscoveryClient_uiservice", those routes are not mine (I did not define them).

I took a look at this post:How to set up Spring Cloud Gateway application so it can use the Service Discovery of Spring Cloud Kubernetes?
without success.

My configuration:

   spring:
      profiles:
        active: prod
      cloud:
        kubernetes:
          reload:
            enabled: true
        gateway:
          discovery:
            locator:
              enabled: true
              lower-case-service-id: true
          globalcors:
            cors-configurations:
              '[/**]':
                allowedOrigins: uiservice
                allowedMethods: "*"
                allowCredentials: true
                maxAge: 7200
                allowedHeaders: "*"
                exposedHeaders:
                - "Access-Control-Allow-Origin"
                - "Access-Control-Allow-Methods"
                - "Access-Control-Max-Age"
                - "Access-Control-Allow-Headers"
                - "Cache-Control"
                - "Authorization"
                - "Content-Type"
          routes:
          #======UISERVICE========
          - id: uiservice_route
            uri: lb://uiservice
            predicates:
            - Path=/* #default route

          - id: uiservice_route_assets
            uri: lb://uiservice
            predicates:
            - Path=/assets/**
   management:
      endpoints:
        web:
          exposure:
            include: "*"
      endpoint:
          restart:
            enabled: true

Also, how can I disable gateway autodiscovering? I don't want the "route_id": "CompositeDiscoveryClient_gateway"

Dependencies:

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-kubernetes-all</artifactId>
</dependency>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Thanks for your help

Body:
It should be look like this:

spring:
  application.name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          url-expression: "'http://'+serviceId+':'+getPort()"
          lower-case-service-id: true

When call http://gateway/my-service-name/api/etc, and then will call my-service-name/api/etc if the service is present in kubernetes

So you need makesure there have a service like :

apiVersion: v1
kind: Service
metadata:
  name: my-service-name
  namespace: default
  labels:
    app: my-service-name
spec:
  type: NodePort
  ports:
    - port: 8080
      nodePort: 30080
  selector:
    app: my-service-name


问:
Perform animation by adding a class to an element
I'm trying to create a menu which plays an animation on click (div with text flies in). When clicking another item in the menu the current div fades and the next one flies in.

I'm trying to do this by adding a class, transorm transiracy, and playing the animation. I've been trying for several hours now, yet nothing works. Can anyone see what I'm doing wrong?

document.getElementsByClassName('.link').onclick = function("myFunction");

function myFunction() {
  var element = document.getElementById("panel");
  element.classList.add("textcss");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</nav>
<div class="text">
  <div class="panel1" id='panel'>
    <p>PANEL1 <br><br></p>
  </div>
  <div class="panel2" id='panel'>
    <p>PANEL2</p>
  </div>
  <div class="panel3" id='panel'>
    <p>PANEL 3</p>
  </div>
</div></code>```

答:
https://jsfiddle.net/chille1987/60uqp7jt/9/

JS - Jquery

```<code>let link = $('.link');
let panel = $('.panel');

link.click(function() {
    let dataId = $(this).attr('data-id');
    panel.hide();
    $('#'+ dataId).show();
});
</code>```

CSS

```<code>.panel {
    display: none;
}
</code>```

HTML

```<code><nav>
  <ul>
    <li><a class="link" href="#0" data-id="panel-1">1</a></li>
    <li><a class="link" href="#0" data-id="panel-2">2</a></li>
    <li><a class="link" href="#0" data-id="panel-3">3</a></li>
  </ul>
</nav>
<div class="text">
  <div class="panel" id="panel-1">
    <p>PANEL1 <br><br></p>
  </div>
  <div class="panel" id="panel-2">
    <p>PANEL2</p>
  </div>
  <div class="panel" id="panel-3">
    <p>PANEL 3</p>
  </div>
</div>
</code>```

Body:
I'm trying to create a menu which plays an animation on click (div with text flies in). When clicking another item in the menu the current div fades and the next one flies in.

I'm trying to do this by adding a class, transorm transiracy, and playing the animation. I've been trying for several hours now, yet nothing works. Can anyone see what I'm doing wrong?

document.getElementsByClassName('.link').onclick = function("myFunction");

function myFunction() {
  var element = document.getElementById("panel");
  element.classList.add("textcss");
}

1

2

3

PANEL1

PANEL2

PANEL 3

Body:
https://jsfiddle.net/chille1987/60uqp7jt/9/

JS - Jquery

let link = $('.link');
let panel = $('.panel');

link.click(function() {
    let dataId = $(this).attr('data-id');
    panel.hide();
    $('#'+ dataId).show();
});

CSS

.panel {
    display: none;
}

HTML

<nav>
  <ul>
    <li><a class="link" href="#0" data-id="panel-1">1</a></li>
    <li><a class="link" href="#0" data-id="panel-2">2</a></li>
    <li><a class="link" href="#0" data-id="panel-3">3</a></li>
  </ul>
</nav>
<div class="text">
  <div class="panel" id="panel-1">
    <p>PANEL1 <br><br></p>
  </div>
  <div class="panel" id="panel-2">
    <p>PANEL2</p>
  </div>
  <div class="panel" id="panel-3">
    <p>PANEL 3</p>
  </div>
</div>


问:
jquery find select options attributes
I know how to get the attributes of an element, using jquery.  But I'm not sure how to do it with the actual options in a select field.

```<code><select referenceID="55" name="test" id="test">
  <option value="1">first option</option>
  <option value="2">second option</option>
  <option value="3">third option</option>
</select>
</code>```

To get the referenceID I would just do this:

```<code>$("#test").attr("referenceID");
</code>```

And when I want to get the value:

```<code>$("#test").val();
</code>```

But I want to get a little more interesting.  I want to put some specific info into each option:

```<code><select name="test" id="test">
  <option value="1" title="something here"*>first option</option>
  <option value="2" title="something else here">second option</option>
  <option value="3" title="another thing here">third option</option>
</select>
</code>```

Is it possible to grab an attribute within the options tags?

I intend to have an onselect function that reads the title tag, and does helps me with some other things.

答:
Presuming you want to find the title attribute of the selected option...

```<code>$('#test option:selected').attr('title');
</code>```

That is, find the descendant element of #test that is (a) an option element and (b) is selected.

If you already have a selection containing #test, you can do this with find:

```<code>$('#test').find('option:selected').attr('title');
</code>```

Title: jquery find select options attributes

Body:
I know how to get the attributes of an element, using jquery.  But I'm not sure how to do it with the actual options in a select field.

<select referenceID="55" name="test" id="test">
  <option value="1">first option</option>
  <option value="2">second option</option>
  <option value="3">third option</option>
</select>

To get the referenceID I would just do this:

$("#test").attr("referenceID");

And when I want to get the value:

$("#test").val();

But I want to get a little more interesting.  I want to put some specific info into each option:

<select name="test" id="test">
  <option value="1" title="something here"*>first option</option>
  <option value="2" title="something else here">second option</option>
  <option value="3" title="another thing here">third option</option>
</select>

Is it possible to grab an attribute within the options tags?

I intend to have an onselect function that reads the title tag, and does helps me with some other things.

Body:
Presuming you want to find the title attribute of the selected option...

$('#test option:selected').attr('title');

That is, find the descendant element of #test that is (a) an option element and (b) is selected.

If you already have a selection containing #test, you can do this with find:

$('#test').find('option:selected').attr('title');


问:
Does assigning a list equivalent to deepcopy() or copy()?
Does the assignment operator work as a deepcopy() or copy()?

For example, if I assign a list a to list b, does it create a shallow copy or a deep copy of list a?

答:
It is neither copy() nor deepcopy().

In Python, all variables are of reference type. So once you assign one list to another then they both represent the same address. So if you update/add/delete element of the list then the same changes will happen in list b also.

So if the list is having only immutable elements then you can use copy() to create a copy but if the list is having mutable elements as well so you need to use deepcopy()

```<code>import copy
b=a.copy()    #If list a elements are immutable
c=a.deepcopy()   #If list a elements are mutable
</code>```

Body:
It is neither copy() nor deepcopy().

In Python, all variables are of reference type. So once you assign one list to another then they both represent the same address. So if you update/add/delete element of the list then the same changes will happen in list b also.

So if the list is having only immutable elements then you can use copy() to create a copy but if the list is having mutable elements as well so you need to use deepcopy()

import copy
b=a.copy()    #If list a elements are immutable
c=a.deepcopy()   #If list a elements are mutable


问:
RREF not defined in Julia
I just install Julia, along with LinearAlgebra package.

When I type

```<code>A = [1 2 3 4; 4 5 6 7]
rref(A)
</code>```

My terminal said

```<code>ERROR: UndefVarError: rref not defined
Stacktrace:
 [1] top-level scope at REPL[22]:1
</code>```

I am sort of confused. Do I need to install certain package in order to use reef function?

答: There s no such function in the LinearAlgebra package. There used to be a long time ago, but is has since moved to https://github.com/blegat/RowEchelon.jl.

Title: RREF not defined in Julia

Body:
I just install Julia, along with LinearAlgebra package.

When I type

A = [1 2 3 4; 4 5 6 7]
rref(A)

My terminal said

ERROR: UndefVarError: rref not defined
Stacktrace:
 [1] top-level scope at REPL[22]:1

I am sort of confused. Do I need to install certain package in order to use reef function?


问:
Angular Reactive Form - FormArray ChangeDection onPush not working
We are using ChangeDetectionStrategy Onpush in all the components, so we are following dump/smart component approach, so we are keeping all the logical part in service/facade side.

Right now we need to generate dynamic controls using Reactive Forms, FormGroup, FormArray,

So we are preparing FormGroup and FormArray in service side, and passing these to dump component as Input parameter, in this case I couldn't pass these as behaviour subject as observable, I'm directly passing as Input parameter.

If anything changes in FormArray, it doesn't not reflect in dump component due to the OnPush changeDectionStrategy.

I have mocked the implementation in this stackblitz

In this sample, I have prepared FormArray, FormGroup in service file, and passing to dump component via smart component.

I couldn't find proper samples on Behavioursubject and Abstract control,

If it is possible to pass FormArray, FormGroup as Observable, Kindly help me to know.

答:
In the stackblitz example, both the FormGroup and FormArrays are undefined even from the Layer-Container Component because the variables are taken from the service before the initial data is loaded. If you do that, and then fetch the service variables and pass it to the child component, then the values will be obtained.

```<code>import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { LayerService } from '../layer.service';

@Component({
  selector: 'app-layer-container',
  templateUrl: './layer-container.component.html',
  styleUrls: ['./layer-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayerContainerComponent implements OnInit {
layerFormGroup ;
layerFormArray ;

  constructor(private service : LayerService) {
    this.service.loadInitialData();
    this.layerFormGroup = this.service.layerFormGroup;
    this.layerFormArray = this.service.layerFormArray;
  }

  ngOnInit() {
    this.service.loadInitialData();
  }

}
</code>```

And since both FormArray and FormGroup are not primitive data types, the @Input() cannot recognize the changes and we probably will not be able to detect the changes. Passing a new reference of these variables might just do the trick.

Body:
In the stackblitz example, both the FormGroup and FormArrays are undefined even from the Layer-Container Component because the variables are taken from the service before the initial data is loaded. If you do that, and then fetch the service variables and pass it to the child component, then the values will be obtained.

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { LayerService } from '../layer.service';

@Component({
  selector: 'app-layer-container',
  templateUrl: './layer-container.component.html',
  styleUrls: ['./layer-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayerContainerComponent implements OnInit {
layerFormGroup ;
layerFormArray ;

  constructor(private service : LayerService) {
    this.service.loadInitialData();
    this.layerFormGroup = this.service.layerFormGroup;
    this.layerFormArray = this.service.layerFormArray;
  }

  ngOnInit() {
    this.service.loadInitialData();
  }

}

And since both FormArray and FormGroup are not primitive data types, the @Input() cannot recognize the changes and we probably will not be able to detect the changes. Passing a new reference of these variables might just do the trick.


问:
How to express this concept without dynamic dispatch?
I am building a simulation (the coding equivalent of a model train set). It is a simulated economy with various economic agents interacting with each other. The main mode of interaction between economic agents is a transaction. At each "tic", each agent generates a list of zero or more proposed transactions (such as buying food). At each "toc" all the counter-parties process the proposed transactions that have been targeted at them in random order so that no biases are introduced. In these snippets a proposed transaction is represented as a u32.

My goal is to simulate as many of these economic agents as possible so performance is key. I am new to rust (or any kind of low level language for that matter) and my understanding from reading the rust book is if I want maximum performance then use "zero cost abstractions" and avoid dynamic dispatch.

So with that out the way I have come up with the following 3 approaches.

Option 1

```<code>trait EconomicAgent {
    fn proposed_transactions(&self) -> Vec<u32>;
}

struct Person {
    health:f64,
    energy:f64,
    nutrition:f64,
    money:f64,
    food:f64
}

impl EconomicAgent for Person {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![1, 2, 3]
    }
}

struct FoodStore {
    money:f64,
    food:f64
}

impl EconomicAgent for FoodStore {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![4, 5, 6]
    }
}
</code>```

A person and a food store are different types that implement the EconomicAgent trait. I can then iterate over a vector of trait objects to get a list of proposed transactions. Each call is dynamically dispatched, I believe.

Option 2

```<code>enum EconomicAgent2 {
    Person(Person),
    FoodStore(FoodStore)
}

impl EconomicAgent2 {
    fn proposed_transactions(&self) -> Vec<u32> {
        match self{
            EconomicAgent2::Person(person) => person.proposed_transactions(),
            EconomicAgent2::FoodStore(food_store) => food_store.proposed_transactions()
        }
    }
}
</code>```

Here, an EconomicAgent is not a trait, but rather an enum and, well you can see how it works.

Option 3

```<code>const HEALTH_INDEX : u8 = 0;
const ENERGY_INDEX : u8 = 1;
const NUTRITION_INDEX : u8 = 2;
const MONEY_INDEX : u8 = 3;
const FOOD_INDEX : u8 = 4;

enum EconomicAgentTag {
    Person,
    FoodStore
}
struct EconomicAgent3 {
    tag: EconomicAgentTag,
    resources:[f64; 5],
    proposed_transactions: Box<fn(&EconomicAgent3) -> Vec<u32>>
}

fn new_person() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::Person,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![1, 2, 3])
    }
}

fn new_food_Store() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::FoodStore,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![4, 5, 6])
    }
}
</code>```

Here an economic agent is more abstract representation.

Now imagine that there a many different types of economic agents (banks, mines, farms, clothing stores etc). They all interact by proposing and accepting transactions. Option 1 seems to suffer from dynamic dispatch. Option 2 seems to be my own version of dynamic dispatch via a match expression so is probably no better, right? Option 3 seems like it should be the most performant but does not really allow much cognitive ease on the part of the programmer.

So finally the questions:

Clearly dynamic dispatch is involved in option 1. What about options 2 and 3?

Which is expected to be most performant? Note I am not really in a position to do testing as the full idea (only on paper right now) is obviously more complex than these snippets and the choice now will affect the entire structure for the whole project.

What would be an idiomatic choice here?

答:
How to avoid dynamic dispatch?

You could go with option 1 and instead of having vector of trait objects, keep each type in its own vector and iterate them individually. It is not nice solution, so...

Instead...

Choose whichever option allows you to model your simulation best and don't worry about the const of dynamic dispatch. The overhead is small. There are other things that will impact the performance more, such as allocating new Vec for every call.

The main cost of dynamic dispatch is indirect branch predictor making wrong guess. To help your cpu make better guesses, you may try to keep objects of the same type next to each other in the vector. For example sort it by type.

Which one is idiomatic?

The option 1 has an issue that to store objects of different types into vector, you must go thru indirection. The easiest is to Box every object, but that means every access will have not only dynamic dispatch for the function, but will also have to follow extra pointer to get to the data.

The option 2 with enum is (in my opinion) more idiomatic - you have all your data together in continuous memory. But beware that the size of an enum is bigger (or equal) to its largest variant. So if you agents vary in size, it may be better to go with option 1.

Body:
I am building a simulation (the coding equivalent of a model train set). It is a simulated economy with various economic agents interacting with each other. The main mode of interaction between economic agents is a transaction. At each "tic", each agent generates a list of zero or more proposed transactions (such as buying food). At each "toc" all the counter-parties process the proposed transactions that have been targeted at them in random order so that no biases are introduced. In these snippets a proposed transaction is represented as a u32.

My goal is to simulate as many of these economic agents as possible so performance is key. I am new to rust (or any kind of low level language for that matter) and my understanding from reading the rust book is if I want maximum performance then use "zero cost abstractions" and avoid dynamic dispatch.

So with that out the way I have come up with the following 3 approaches.

Option 1

trait EconomicAgent {
    fn proposed_transactions(&self) -> Vec<u32>;
}

struct Person {
    health:f64,
    energy:f64,
    nutrition:f64,
    money:f64,
    food:f64
}

impl EconomicAgent for Person {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![1, 2, 3]
    }
}

struct FoodStore {
    money:f64,
    food:f64
}

impl EconomicAgent for FoodStore {
    fn proposed_transactions(&self) -> Vec<u32> {
        vec![4, 5, 6]
    }
}

A person and a food store are different types that implement the EconomicAgent trait. I can then iterate over a vector of trait objects to get a list of proposed transactions. Each call is dynamically dispatched, I believe.

Option 2

enum EconomicAgent2 {
    Person(Person),
    FoodStore(FoodStore)
}

impl EconomicAgent2 {
    fn proposed_transactions(&self) -> Vec<u32> {
        match self{
            EconomicAgent2::Person(person) => person.proposed_transactions(),
            EconomicAgent2::FoodStore(food_store) => food_store.proposed_transactions()
        }
    }
}

Here, an EconomicAgent is not a trait, but rather an enum and, well you can see how it works.

Option 3

const HEALTH_INDEX : u8 = 0;
const ENERGY_INDEX : u8 = 1;
const NUTRITION_INDEX : u8 = 2;
const MONEY_INDEX : u8 = 3;
const FOOD_INDEX : u8 = 4;

enum EconomicAgentTag {
    Person,
    FoodStore
}
struct EconomicAgent3 {
    tag: EconomicAgentTag,
    resources:[f64; 5],
    proposed_transactions: Box<fn(&EconomicAgent3) -> Vec<u32>>
}

fn new_person() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::Person,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![1, 2, 3])
    }
}

fn new_food_Store() -> EconomicAgent3 {
    EconomicAgent3 {
        tag: EconomicAgentTag::FoodStore,
        resources: [0.0,0.0,0.0,0.0,0.0],
        proposed_transactions: Box::new(|_| vec![4, 5, 6])
    }
}

Here an economic agent is more abstract representation.

Now imagine that there a many different types of economic agents (banks, mines, farms, clothing stores etc). They all interact by proposing and accepting transactions. Option 1 seems to suffer from dynamic dispatch. Option 2 seems to be my own version of dynamic dispatch via a match expression so is probably no better, right? Option 3 seems like it should be the most performant but does not really allow much cognitive ease on the part of the programmer.

So finally the questions:

Clearly dynamic dispatch is involved in option 1. What about options 2 and 3?

Which is expected to be most performant? Note I am not really in a position to do testing as the full idea (only on paper right now) is obviously more complex than these snippets and the choice now will affect the entire structure for the whole project.

What would be an idiomatic choice here?


问:
Python requiring an attribute be converted to a string
```<code>from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()
</code>```

Trace back i get in terminal is:

```<code>    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string
</code>```

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

答:
```<code>def __init__(self, start, quips):
</code>```

...

```<code>e = Engine(m, "princess_lives_here")
</code>```

This is your problem.  The second line calls init with arguments m and "princess_lives_here".  The first argument should be "princess_lives_here" and the second should be the "quips" list.

Body:
from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()

Trace back i get in terminal is:

    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

Body:
def __init__(self, start, quips):

...

e = Engine(m, "princess_lives_here")

This is your problem.  The second line calls init with arguments m and "princess_lives_here".  The first argument should be "princess_lives_here" and the second should be the "quips" list.


问:
Retrieve params and set params as argument in fetch request within useEffect Hook
I am developing a MERN application. Presently I working on my Password Reset Emails, Validate ResetToken, Reset and Update password. So far, I have been able to complete All at the backend.

On the front-end, I have completed the ForgotPassword request which sends the user a mail with the reset token.

The problem is right now is that I  have not been able to retrieve the token at the front-end.

In my backend, the restPassword :

userRouter.get('/reset/:token', (req, res) => {
    User.findOne({
        resetPasswordToken: req.params.token,
        resetPasswordExpires: { $gt : Date.now() },
    }).then((user) => {
      if (user == null) {
        console.error('password reset link is invalid or has expired');
        res.status(403).json({message : {msgBody : "password reset link is invalid or has expired", msgError: true}});
      } else {
        res.status(200).send({
          username: user.username,
          resetPasswordToken: user.resetPasswordToken,
          message: {msgBody : "password reset link a-ok", msgError: true},
        });
      }
    });
  });```
</div>
</div>
</p>

<p>When tested with a valid URL like this, I get the right response</p>

<p><img src="https://i.stack.imgur.com/iypPi.png" alt="enter image description here"></p>

<p>On my front-end my router is setup like this </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function App() {

    return (
        <div className="App">
            <Router >
                <Switch>

          ...

                    <UnPrivateRoute
                    path="/forgotPassword"
                    component={ForgotPassword} />

                    <UnPrivateRoute
                    path="/reset/:token"
                    component={ResetPassword} />

                    <UnPrivateRoute
                    path="/login"
                    component={Login} />
          ...
               </Switch>

            </Router>
        </div>
    );

}

export default App;</code>```

I try to retrieve the param (token) appended to the path (http://localhost:3000/reset/c25d7b114e99e8720761732eb1670a3d0a084877) in the email sent to the user so I can use it in my fetch request but so far I cant.

The console log of my response data is status 401 (Response {type: "basic", url: "http://localhost:3000/user/reset/", redirected: false, status: 401, ok: false, …})

Here is my code. Any valid solution will be much appreciated. Thanks

const ResetPassword = props => {

  var url = new URL('http://localhost:3000/user/reset/?');
  var token = new URLSearchParams(url.search);

  useEffect(()=>{
    fetch('http://localhost:3000/user/reset/'+ token).then(data =>{
      console.log(data);
    });

  },[token]);

  });
  return (
   <>
    </>
  );
}

export default ResetPassword;```

答:
So after some digging, I got the answer,

First thing I had to do was to update my "react-router" and "react-router-dom".

From what I gathered, you need at least a 5.1.2 version to do this.

Also, ensure that you are running the same version for both dependencies.

So in my case, I have updated to

"react-router": "5.2.0",
 "react-router-dom": "5.2.0",

The next thing I did was to import { useLocation, useHistory ,  useParams} from 'react-router-dom';

import React, {useState,useRef,useEffect} from 'react';
import { useLocation, useHistory ,  useParams} from 'react-router-dom';

const ResetPassword = props => {
  let { token } = useParams()
  console.log(token);
  const history = useHistory();
  const location = useLocation();
  console.log(location);

  useEffect(()=>{

    const currentPath = location.pathname;
    const searchParams = new URLSearchParams(location.search);
    console.log(currentPath);
    console.log(searchParams)

  },[location]);

  });
  return (
    <>

    </>
  );
}

export default ResetPassword;```
</div>
</div>
</p>

<p>In my router I have the route for the page set thus</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>                    <UnPrivateRoute
                    path="/reset/:token"
                    component={ResetPassword} /></code>```

So the present browser URL is http://localhost:3000/reset/ab4794396674412e00406beda674349400c1f5ad

on the console as logged above. I have the following results.
console.log(token);
result: ab4794396674412e00406beda674349400c1f5ad

console.log(location);
Result: {pathname: "/reset/ab4794396674412e00406beda674349400c1f5ad", search: "", hash: "", state: undefined}

console.log(currentPath);
Result: /reset/ab4794396674412e00406beda674349400c1f5ad

console.log(searchParams);
Result: URLSearchParams {append: function, delete: function, get: function, …}

Body:
I am developing a MERN application. Presently I working on my Password Reset Emails, Validate ResetToken, Reset and Update password. So far, I have been able to complete All at the backend.

On the front-end, I have completed the ForgotPassword request which sends the user a mail with the reset token.

The problem is right now is that I  have not been able to retrieve the token at the front-end.

In my backend, the restPassword :

userRouter.get('/reset/:token', (req, res) => {
    User.findOne({
        resetPasswordToken: req.params.token,
        resetPasswordExpires: { $gt : Date.now() },
    }).then((user) => {
      if (user == null) {
        console.error('password reset link is invalid or has expired');
        res.status(403).json({message : {msgBody : "password reset link is invalid or has expired", msgError: true}});
      } else {
        res.status(200).send({
          username: user.username,
          resetPasswordToken: user.resetPasswordToken,
          message: {msgBody : "password reset link a-ok", msgError: true},
        });
      }
    });
  });

When tested with a valid URL like this, I get the right response

On my front-end my router is setup like this

function App() {

    return (

            <Router >
                <Switch>

          ...

                    <UnPrivateRoute
                    path="/forgotPassword"
                    component={ForgotPassword} />

                    <UnPrivateRoute
                    path="/reset/:token"
                    component={ResetPassword} />

                    <UnPrivateRoute
                    path="/login"
                    component={Login} />
          ...
               </Switch>

            </Router>

    );

}

export default App;

I try to retrieve the param (token) appended to the path (http://localhost:3000/reset/c25d7b114e99e8720761732eb1670a3d0a084877) in the email sent to the user so I can use it in my fetch request but so far I cant.

The console log of my response data is status 401 (Response {type: "basic", url: "http://localhost:3000/user/reset/", redirected: false, status: 401, ok: false, …})

Here is my code. Any valid solution will be much appreciated. Thanks

const ResetPassword = props => {

  var url = new URL('http://localhost:3000/user/reset/?');
  var token = new URLSearchParams(url.search);

  useEffect(()=>{
    fetch('http://localhost:3000/user/reset/'+ token).then(data =>{
      console.log(data);
    });

  },[token]);

  });
  return (
   <>
    </>
  );
}

export default ResetPassword;

Body:
So after some digging, I got the answer,

First thing I had to do was to update my "react-router" and "react-router-dom".

From what I gathered, you need at least a 5.1.2 version to do this.

Also, ensure that you are running the same version for both dependencies.

So in my case, I have updated to

"react-router": "5.2.0",
 "react-router-dom": "5.2.0",

The next thing I did was to import { useLocation, useHistory ,  useParams} from 'react-router-dom';

import React, {useState,useRef,useEffect} from 'react';
import { useLocation, useHistory ,  useParams} from 'react-router-dom';

const ResetPassword = props => {
  let { token } = useParams()
  console.log(token);
  const history = useHistory();
  const location = useLocation();
  console.log(location);

  useEffect(()=>{

    const currentPath = location.pathname;
    const searchParams = new URLSearchParams(location.search);
    console.log(currentPath);
    console.log(searchParams)

  },[location]);

  });
  return (
    <>

    </>
  );
}

export default ResetPassword;

In my router I have the route for the page set thus

                    <UnPrivateRoute
                    path="/reset/:token"
                    component={ResetPassword} />

So the present browser URL is http://localhost:3000/reset/ab4794396674412e00406beda674349400c1f5ad

on the console as logged above. I have the following results.
console.log(token);
result: ab4794396674412e00406beda674349400c1f5ad

console.log(location);
Result: {pathname: "/reset/ab4794396674412e00406beda674349400c1f5ad", search: "", hash: "", state: undefined}

console.log(currentPath);
Result: /reset/ab4794396674412e00406beda674349400c1f5ad

console.log(searchParams);
Result: URLSearchParams {append: function, delete: function, get: function, …}


问:
Change naming strategy in Aqueduct ORM
Is it possible to setup Aqueduct ORM to use underscored names for database columns (so if I have field "someField" in model class it will be stored as "some_field" in the database)? Or may be it is at least possible to override column name by some annotation? I have legacy database schema with underscored names and I cannot change it).</p>

答: This is not supported yet, as of May 2020. Please upvote the associated Github issue.</p>

Title: Change naming strategy in Aqueduct ORM