问:
Flutter Release APK for playstore
I am trying to generate a build apk, but getting following error.
this is compatible with flutter version 2.8.1

Getting following error while run flutter build apk

```<code>/home/dell/snap/flutter/common/flutter/bin/flutter --no-color build apk

Building without sound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety

Running Gradle task 'assembleRelease'...
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/geocoding-2.0.2/android/src/main/java/com/baseflow/geocoding/GeocodingPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/google_maps_flutter-2.1.1/android/src/main/java/io/flutter/plugins/googlemaps/Convert.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/path_provider_android-2.0.11/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
e: /var/projects/app/freshooo/android/app/src/main/kotlin/com/u6amtech/flutter_grocery/Application.kt: (11, 51): Unresolved reference: setPluginRegistrant
e: /var/projects/app/freshooo/android/app/src/main/kotlin/com/u6amtech/flutter_grocery/FirebaseCloudMessagingPluginRegistrant.kt: (15, 44): Unresolved reference: registerWith
</code>```

FAILURE: Build failed with an exception.

```<code>* What went wrong:
Execution failed for task ':app:compileReleaseKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 6s
Running Gradle task 'assembleRelease'...                          126.8s
Gradle task assembleRelease failed with exit code 1
</code>```

pubspec.yaml

```<code>name: flutter_grocery
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.1.0+2

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^1.0.2
  get_it: ^6.0.0
  provider: ^5.0.0
  http: ^0.13.1
  freezed: ^0.14.1
  shared_preferences: ^2.0.5
  photo_view: ^0.12.0
  dio: ^4.0.0-prev2
  image_picker: ^0.7.3
  pin_code_fields: ^7.0.0
  google_maps_flutter_web: ^0.3.0
  google_maps_flutter: ^2.0.3
  flutter_google_places: ^0.3.0
  geocoding: ^2.0.0
  geolocator: ^7.0.1
  shimmer_animation: ^2.0.0
  url_launcher: ^6.0.2
  webview_flutter: ^2.0.2
  firebase_core: ^1.7.0
  firebase_messaging: ^10.0.8
  flutter_local_notifications: ^8.2.0
  path_provider: ^2.0.1
  flutter_html: ^2.0.0-nullsafety.0
  connectivity: ^3.0.2
  carousel_slider: ^4.0.0-nullsafety.0
  fluro: ^2.0.3
  url_strategy: ^0.2.0
  universal_html: ^2.0.8
  universal_ui: ^0.0.8
  flutter_widget_from_html_core: ^0.6.1
  phone_number: ^0.11.0+2
  country_code_picker: ^2.0.2
  flutter_typeahead: ^3.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

  assets:
    - assets/image/
    - assets/language/

  fonts:
    - family: Poppins
      fonts:
        - asset: assets/font/Poppins-Light.ttf
          weight: 300
        - asset: assets/font/Poppins-Regular.ttf
          weight: 400
        - asset: assets/font/Poppins-Medium.ttf
          weight: 500
        - asset: assets/font/Poppins-SemiBold.ttf
          weight: 600
        - asset: assets/font/Poppins-Bold.ttf
          weight: 700
</code>```

app/build.gradle

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.fresh.grocery"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "com.google.firebase:firebase-messaging:21.0.1"
    implementation 'com.android.support:multidex:1.0.3'
}
</code>```

android/build.gradle

```<code>buildscript {
    ext.kotlin_version = '1.5.20'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.5'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    tasks.withType(JavaCompile) {
        options.compilerArgs << '-Xlint:-options'
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

gradle-wrapper.properties

```<code>#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-6.3-all.zip
</code>```

key.properties

```<code>storePassword=123456
keyPassword=123456
keyAlias=upload
storeFile=~/home/dell/upload-keystore.jks
</code>```

Project Setting

答:
Please don't show confidential code like your package name, key.properties file kindly edit and remove those to protect your app from malicious itentions.

Since your flutter version is 2.8.1 but your dart sdk in pubspec.yaml is sdk: ">=2.7.0 <3.0.0" it requires to enable null-safety for your project just change the 2.7.0 to 2.12.0 or above, and also do require changes for flutter null safety for more details check out this https://dart.dev/null-safety/unsound-null-safety

You maybe getting this error as some of the packages you used in your project use null-safety so migrate your app to null-safety.

You can check this for more details about generating production apps https://docs.flutter.dev/deployment/android

you can also use this code to generate a obfuscated apk

```<code>flutter build apk --release --obfuscate --split-debug-info={directory}
</code>```

similarly for appbundle:

```<code>flutter build appbundle --release --obfuscate --split-debug-info={directory}
</code>```

Title: Flutter Release APK for playstore

Body:
I am trying to generate a build apk, but getting following error.
this is compatible with flutter version 2.8.1

Getting following error while run flutter build apk

/home/dell/snap/flutter/common/flutter/bin/flutter --no-color build apk

Building without sound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety

Running Gradle task 'assembleRelease'...
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/geocoding-2.0.2/android/src/main/java/com/baseflow/geocoding/GeocodingPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/google_maps_flutter-2.1.1/android/src/main/java/io/flutter/plugins/googlemaps/Convert.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /home/dell/.pub-cache/hosted/pub.dartlang.org/path_provider_android-2.0.11/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
e: /var/projects/app/freshooo/android/app/src/main/kotlin/com/u6amtech/flutter_grocery/Application.kt: (11, 51): Unresolved reference: setPluginRegistrant
e: /var/projects/app/freshooo/android/app/src/main/kotlin/com/u6amtech/flutter_grocery/FirebaseCloudMessagingPluginRegistrant.kt: (15, 44): Unresolved reference: registerWith

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 6s
Running Gradle task 'assembleRelease'...                          126.8s
Gradle task assembleRelease failed with exit code 1

pubspec.yaml

name: flutter_grocery
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.1.0+2

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^1.0.2
  get_it: ^6.0.0
  provider: ^5.0.0
  http: ^0.13.1
  freezed: ^0.14.1
  shared_preferences: ^2.0.5
  photo_view: ^0.12.0
  dio: ^4.0.0-prev2
  image_picker: ^0.7.3
  pin_code_fields: ^7.0.0
  google_maps_flutter_web: ^0.3.0
  google_maps_flutter: ^2.0.3
  flutter_google_places: ^0.3.0
  geocoding: ^2.0.0
  geolocator: ^7.0.1
  shimmer_animation: ^2.0.0
  url_launcher: ^6.0.2
  webview_flutter: ^2.0.2
  firebase_core: ^1.7.0
  firebase_messaging: ^10.0.8
  flutter_local_notifications: ^8.2.0
  path_provider: ^2.0.1
  flutter_html: ^2.0.0-nullsafety.0
  connectivity: ^3.0.2
  carousel_slider: ^4.0.0-nullsafety.0
  fluro: ^2.0.3
  url_strategy: ^0.2.0
  universal_html: ^2.0.8
  universal_ui: ^0.0.8
  flutter_widget_from_html_core: ^0.6.1
  phone_number: ^0.11.0+2
  country_code_picker: ^2.0.2
  flutter_typeahead: ^3.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

  assets:
    - assets/image/
    - assets/language/

  fonts:
    - family: Poppins
      fonts:
        - asset: assets/font/Poppins-Light.ttf
          weight: 300
        - asset: assets/font/Poppins-Regular.ttf
          weight: 400
        - asset: assets/font/Poppins-Medium.ttf
          weight: 500
        - asset: assets/font/Poppins-SemiBold.ttf
          weight: 600
        - asset: assets/font/Poppins-Bold.ttf
          weight: 700

app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.fresh.grocery"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "com.google.firebase:firebase-messaging:21.0.1"
    implementation 'com.android.support:multidex:1.0.3'
}

android/build.gradle

buildscript {
    ext.kotlin_version = '1.5.20'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.5'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    tasks.withType(JavaCompile) {
        options.compilerArgs << '-Xlint:-options'
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

gradle-wrapper.properties

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-6.3-all.zip

key.properties

storePassword=123456
keyPassword=123456
keyAlias=upload
storeFile=~/home/dell/upload-keystore.jks

Project Setting

Body:
Please don't show confidential code like your package name, key.properties file kindly edit and remove those to protect your app from malicious itentions.

Since your flutter version is 2.8.1 but your dart sdk in pubspec.yaml is sdk: ">=2.7.0 <3.0.0" it requires to enable null-safety for your project just change the 2.7.0 to 2.12.0 or above, and also do require changes for flutter null safety for more details check out this https://dart.dev/null-safety/unsound-null-safety

You maybe getting this error as some of the packages you used in your project use null-safety so migrate your app to null-safety.

You can check this for more details about generating production apps https://docs.flutter.dev/deployment/android

you can also use this code to generate a obfuscated apk

flutter build apk --release --obfuscate --split-debug-info={directory}

similarly for appbundle:

flutter build appbundle --release --obfuscate --split-debug-info={directory}


来源: stackexchange

问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
If you have a DOM like structure, you need to recursively iterate through the elements. Something like that should work:</p>

```<code>function printArray(array) {
    for (var i = 0; i < array.length; i++) {
        var v = array[i];
        if (v instanceof Array) {
            printArray(v);
        } else {
            console.log(v);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
If you have a DOM like structure, you need to recursively iterate through the elements. Something like that should work:

function printArray(array) {
    for (var i = 0; i < array.length; i++) {
        var v = array[i];
        if (v instanceof Array) {
            printArray(v);
        } else {
            console.log(v);
        }
    }
}


问:
Getting Python assertRaises to check for message
I want to use assertRaises and check for the error message too. According to the docs I have to use it as a context manager.

```<code>with self.assertRaises(ValueError, msg='Invalid id format.'):
    api.get_by_id('a')
</code>```

This results in the following error:

```<code>TypeError: assertRaises() missing 1 required positional argument: 'callableObj'
</code>```

I get the exact same error if I use it without msg.

Using it like assertRaises(exception, callable, *args, **kwds) works fine, but that obviously can't process the error message.

I don't understand why Python can't recognise the use case I'm going for.

Python 3.7.10, MacOS Monterey 12.2

答:
Two things - first of all, it's hard to tell what actually happens but there must be some other error in your code because
with self.assertRaises(ValueError, msg='Invalid id format.'): should work perfectly fine (tested on Python 3.10)

2nd thing - msg argument does not do what you want it to do - self.assertRaises as a context manager with msg argument not working as expected

Link provided also explains how to check for error message with  assertRaisesRegex

ContentLicense: CC BY-SA 4.0

Body:
I want to use assertRaises and check for the error message too. According to the docs I have to use it as a context manager.

with self.assertRaises(ValueError, msg='Invalid id format.'):
    api.get_by_id('a')

This results in the following error:

TypeError: assertRaises() missing 1 required positional argument: 'callableObj'

I get the exact same error if I use it without msg.

Using it like assertRaises(exception, callable, *args, **kwds) works fine, but that obviously can't process the error message.

I don't understand why Python can't recognise the use case I'm going for.

Python 3.7.10, MacOS Monterey 12.2


问:
Why is a variable not passed to a template?
I have the following task in one of my roles:

- name: Moodle--{{ moodle_domain }}--Apache--Virtual Host--Configuration-- Copy
  become: yes
  loop:
    - src: ../templates/moodle.test.conf.j2
      dest: /etc/apache2/sites-enabled/{{ moodle_domain }}.conf
    - src: ../templates/moodle.test-ssl.conf.j2
      dest: /etc/apache2/sites-enabled/{{ moodle_domain }}-ssl.conf
  ansible.builtin.copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: u+rw,g+r,o+r
  notify: Apache--Service-- Restart
```
<p>One of the templates used above, look like this:</p>
```<VirtualHost *:80>
        ServerName {{ moodle_domain }}
        Redirect permanent / https://{{ moodle_domain }}/
</VirtualHost>
```

I know the moodle_domain variable is passed to the loop, because I can see that the file names on the target host are correct.

But it is not passed to the template. I know this, because on the target host, the files still contain {{ moodle_domain }} instead of the actual domain.

What am I doing wrong?

答: I should have ansible.builtin.template not ansible.builtin.copy. I previously had template, but copied the looping style from another role that did not need templating.</p>

Body:
I have the following task in one of my roles:

- name: Moodle--{{ moodle_domain }}--Apache--Virtual Host--Configuration-- Copy
  become: yes
  loop:
    - src: ../templates/moodle.test.conf.j2
      dest: /etc/apache2/sites-enabled/{{ moodle_domain }}.conf
    - src: ../templates/moodle.test-ssl.conf.j2
      dest: /etc/apache2/sites-enabled/{{ moodle_domain }}-ssl.conf
  ansible.builtin.copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: u+rw,g+r,o+r
  notify: Apache--Service-- Restart

One of the templates used above, look like this:

<VirtualHost *:80>
        ServerName {{ moodle_domain }}
        Redirect permanent / https://{{ moodle_domain }}/
</VirtualHost>

I know the moodle_domain variable is passed to the loop, because I can see that the file names on the target host are correct.

But it is not passed to the template. I know this, because on the target host, the files still contain {{ moodle_domain }} instead of the actual domain.

What am I doing wrong?


问:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token "Invalid Character" executing Selenium Java program
Code trials:

```<code>package split;

public class locators {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty(“webdriver.chrome.driver”, “C/Users/sai/Documents/chromedriver.exe);
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        driver.getTitle();
    }

}
</code>```

Errors:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Syntax error on token "Invalid Character", delete this token
    webdriver cannot be resolved to a variable
    Syntax error on tokens, delete these tokens
    Users cannot be resolved to a variable
    sai cannot be resolved to a variable
    Documents cannot be resolved to a variable
    chromedriver cannot be resolved to a variable
    WebDriver cannot be resolved to a type
    ChromeDriver cannot be resolved to a type

    at split.locators.main(locators.java:7)
</code>```

So how to fix this code?

答:
Just like the key webdriver.chrome.driver is enclosed within double quotes, the value also needs to be enclosed within double quotes properly.

Effectively your line of code will be:

```<code>System.setProperty("webdriver.chrome.driver", "C:\\Users\\sai\\Documents\\chromedriver.exe");
</code>```

Body:
Code trials:

package split;

public class locators {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty(“webdriver.chrome.driver”, “C/Users/sai/Documents/chromedriver.exe);
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        driver.getTitle();
    }

}

Errors:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Syntax error on token "Invalid Character", delete this token
    webdriver cannot be resolved to a variable
    Syntax error on tokens, delete these tokens
    Users cannot be resolved to a variable
    sai cannot be resolved to a variable
    Documents cannot be resolved to a variable
    chromedriver cannot be resolved to a variable
    WebDriver cannot be resolved to a type
    ChromeDriver cannot be resolved to a type

    at split.locators.main(locators.java:7)

So how to fix this code?

Body:
Just like the key webdriver.chrome.driver is enclosed within double quotes, the value also needs to be enclosed within double quotes properly.

Effectively your line of code will be:

System.setProperty("webdriver.chrome.driver", "C:\\Users\\sai\\Documents\\chromedriver.exe");


问:
How to I train a keras functional API model with batched tf Dataset objects? (BatchDataset)
I am constructing a tf keras model using the functional API. This model will train fine on large memory mapped arrays. However, for numerous reasons it can be advantageous to work with tensorflow Dataset objects. Therefore, I use from_tensor_slices() to convert my arrays to Dataset objects.
The problem is that the model will no longer train.

The keras docs: Model training APIs indicate that dataset objects are acceptable.

The guide I'm following on how to train is found here: Using tf.data with tf keras

Guides on how to use the keras functional API are here. However, training a functional API model with a tf Dataset object is not outlined.

A MWE is provided here:

```<code>import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers

print('numpy version: {}'.format(np.__version__))
print('keras version: {}'.format(keras.__version__))
print('tensorflow version: {}'.format(tf.__version__))
</code>```

numpy version: 1.21.4

keras version: 2.6.0

tensorflow version: 2.6.0

```<code>X = np.random.uniform(size=(1000,75))
Y = np.random.uniform(size=(1000))

data = tf.data.Dataset.from_tensor_slices((X, Y))
print(data.cardinality().numpy())
</code>```

1000

```<code>data.batch(batch_size=100, drop_remainder=True)
</code>```

<BatchDataset shapes: ((100, 75), (100,)), types: (tf.float64, tf.float64)>

```<code>def API_Model(input_shape, name="test_model"):

    inputs = layers.Input(shape=input_shape)
    x = layers.Dense(1)(inputs)
    outputs = layers.Activation('relu')(x)

    return keras.Model(inputs=inputs, outputs=outputs, name=name)

api_model = API_Model(input_shape=(X.shape[1],))
api_model.compile()
api_model.summary()
</code>```

```<code>Model: "test_model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_2 (InputLayer)         [(None, 75)]              0
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 76
_________________________________________________________________
activation_1 (Activation)    (None, 1)                 0
=================================================================
Total params: 76
Trainable params: 76
Non-trainable params: 0
_________________________________________________________________
</code>```

```<code>api_model.fit(data, epochs=10)
</code>```

Epoch 1/10
WARNING:tensorflow:Model was constructed with shape (None, 75) for input
KerasTensor(type_spec=TensorSpec(shape=(None, 75), dtype=tf.float32, name='input_2'),
name='input_2', description="created by layer 'input_2'"), but it was called on an input with
incompatible shape (75, 1).

The error I receive is: ValueError: Input 0 of layer dense_1 is incompatible with the layer: expected axis -1 of input shape to have value 75 but received input with shape (75, 1)

In addition, the error from my actual model I'm trying to train is slightly different but seems to be malfunctioning under the same principle. It is the following:

```<code>ValueError: Input 0 is incompatible with layer pfn_base: expected shape=(None, 1086, 5), found shape=(1086, 5)
</code>```

What is the proper way to train a keras functional API model on a BatchDataset object?

答:
You need to assign the batched dataset to a variable and you should also use a loss function in model.compile because the default value is None and you can't learn anything with it. Here is a working example:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers

print('numpy version: {}'.format(np.__version__))
print('keras version: {}'.format(keras.__version__))
print('tensorflow version: {}'.format(tf.__version__))
X = np.random.uniform(size=(1000,75))
Y = np.random.uniform(size=(1000))

data = tf.data.Dataset.from_tensor_slices((X, Y))
print(data.cardinality().numpy())
data = data.batch(batch_size=100, drop_remainder=True)

def API_Model(input_shape, name="test_model"):

    inputs = layers.Input(shape=input_shape)
    x = layers.Dense(1)(inputs)
    outputs = layers.Activation('relu')(x)

    return keras.Model(inputs=inputs, outputs=outputs, name=name)

api_model = API_Model(input_shape=(X.shape[1],))
api_model.compile(loss='mse')
api_model.summary()
api_model.fit(data, epochs=10)
```

Body:
I am constructing a tf keras model using the functional API. This model will train fine on large memory mapped arrays. However, for numerous reasons it can be advantageous to work with tensorflow Dataset objects. Therefore, I use from_tensor_slices() to convert my arrays to Dataset objects.
The problem is that the model will no longer train.

The keras docs: Model training APIs indicate that dataset objects are acceptable.

The guide I'm following on how to train is found here: Using tf.data with tf keras

Guides on how to use the keras functional API are here. However, training a functional API model with a tf Dataset object is not outlined.

A MWE is provided here:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers

print('numpy version: {}'.format(np.__version__))
print('keras version: {}'.format(keras.__version__))
print('tensorflow version: {}'.format(tf.__version__))

numpy version: 1.21.4

keras version: 2.6.0

tensorflow version: 2.6.0

X = np.random.uniform(size=(1000,75))
Y = np.random.uniform(size=(1000))

data = tf.data.Dataset.from_tensor_slices((X, Y))
print(data.cardinality().numpy())

1000

data.batch(batch_size=100, drop_remainder=True)

<BatchDataset shapes: ((100, 75), (100,)), types: (tf.float64, tf.float64)>

def API_Model(input_shape, name="test_model"):

    inputs = layers.Input(shape=input_shape)
    x = layers.Dense(1)(inputs)
    outputs = layers.Activation('relu')(x)

    return keras.Model(inputs=inputs, outputs=outputs, name=name)

api_model = API_Model(input_shape=(X.shape[1],))
api_model.compile()
api_model.summary()

Model: "test_model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_2 (InputLayer)         [(None, 75)]              0
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 76
_________________________________________________________________
activation_1 (Activation)    (None, 1)                 0
=================================================================
Total params: 76
Trainable params: 76
Non-trainable params: 0
_________________________________________________________________

api_model.fit(data, epochs=10)

Epoch 1/10
WARNING:tensorflow:Model was constructed with shape (None, 75) for input
KerasTensor(type_spec=TensorSpec(shape=(None, 75), dtype=tf.float32, name='input_2'),
name='input_2', description="created by layer 'input_2'"), but it was called on an input with
incompatible shape (75, 1).

The error I receive is: ValueError: Input 0 of layer dense_1 is incompatible with the layer: expected axis -1 of input shape to have value 75 but received input with shape (75, 1)

In addition, the error from my actual model I'm trying to train is slightly different but seems to be malfunctioning under the same principle. It is the following:

ValueError: Input 0 is incompatible with layer pfn_base: expected shape=(None, 1086, 5), found shape=(1086, 5)

What is the proper way to train a keras functional API model on a BatchDataset object?


问:
Upload .css file after saving .scss file
I use Visual Studio Code and WinSCP. When I open .scss file via WinSCP the file is opened automatically by VSC – It's ok. There is an extension Live Sass Compiler to I could compile .scss into .css file. The problem is that .css file is created in temporary folder with random number so I always must upload the file manually by drag the file from the folder to FTP client.

Is it there any solution to upload the .css file automatically on save from the temporary folder? Thank you in advance for a help.

答:
Download the files to a local folder.

Have WinSCP monitor the folder and automatically upload any modifications (including new files).

Edit the files locally (and have WinSCP upload the changes, including the generated files).

For your literal question, there's WinSCP feature request.


问:
How can I fix "[Error 6] The handle is invalid." with PySerial
I'm trying to connect to my phone from my Windows 7 PC using PySerial with the following code:

```<code>import wmi
import serial

c = wmi.WMI()
modem = c.query("SELECT * FROM Win32_POTSModem").pop()
ser = serial.Serial(modem.AttachedTo, modem.MaxBaudRateToSerialPort)

try:
    ser.write('at \r\n')
    print ser.readline()
finally:
    ser.close()
</code>```

But get the following error on the write call:

```<code>Traceback (most recent call last):
  File "D:\Alasdair\Documents\Python Scripts\Phone Interface\test.py", line 14, in <module>
    ser.write('at \r\n')
  File "C:\Python26\Lib\site-packages\serial\serialwin32.py", line 255, in write
    raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
SerialException: WriteFile failed ([Error 6] The handle is invalid.)
</code>```

I've tried connecting with TeraTerm and that works fine, so it's not a problem with the connection to the phone itself.

I've been searching around for ages trying to find a solution but haven't come up with anything that works. Any ideas?

答:
I observed this problem with Python 2.7 win7 x64, and PySerial 2.5 installed automatically from easy_install.exe

The problem is not there with PySerial 2.4, so if your code is compatible with 2.4, just use that one instead and the problem is solved. Notice that you have to use pywin32 also, and chose the version that correspond to your python (e.g. pywin32-216.win-amd64-py2.7.exe).

See also https://sourceforge.net/tracker/?func=detail&aid=2921959&group_id=46487&atid=446302%5D2921959

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to connect to my phone from my Windows 7 PC using PySerial with the following code:

import wmi
import serial

c = wmi.WMI()
modem = c.query("SELECT * FROM Win32_POTSModem").pop()
ser = serial.Serial(modem.AttachedTo, modem.MaxBaudRateToSerialPort)

try:
    ser.write('at \r\n')
    print ser.readline()
finally:
    ser.close()

But get the following error on the write call:

Traceback (most recent call last):
  File "D:\Alasdair\Documents\Python Scripts\Phone Interface\test.py", line 14, in <module>
    ser.write('at \r\n')
  File "C:\Python26\Lib\site-packages\serial\serialwin32.py", line 255, in write
    raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
SerialException: WriteFile failed ([Error 6] The handle is invalid.)

I've tried connecting with TeraTerm and that works fine, so it's not a problem with the connection to the phone itself.

I've been searching around for ages trying to find a solution but haven't come up with anything that works. Any ideas?


问:
Error: Page not found The requested URL was not found on this server. google cloud functions
I'm using google cloud's "Hello World" demo for cloud functions but the URL it produces gives me an error:

```<code>Error: Page not found
The requested URL was not found on this server.
</code>```

I follow the tutorial, check allow unauthenticated, etc yet the url trigger leads me to the error.

The curl response requested also returns an error:

```<code>curl -X POST MY_URL  -H "Content-Type:application/json"  -d '{"name":"Jane"}'
</code>```

returns:

```<code><html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404 Page not found</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Page not found</h1>
<h2>The requested URL was not found on this server.</h2>
<h2></h2>
</body></html>
</code>```

Any ideas why?

edit: testing works just fine

Edit2: the url in MY_URL is structured like this:
curl -X POST https://us-west1-PROJECT-NAME.cloudfunctions.net/FUNCTION-NAME  -H "Content-Type:application/json"  -d '{"message":"Jane"}'

答:
According to this GCP doc:

As of January 15, 2020, all HTTP functions by default require most invokers to be authenticated. To allow unauthenticated invocation you must specify this at or after deployment.

After deployment, manually add the Cloud Functions Invoker permission to allUsers users in the Cloud Functions page in the Google Cloud Console.

However, it's always a best practice to set authorization on your cloud functions.

I was able to curl the endpoint successfully using:

```<code>curl -X POST https://us-central1-<project_name>.cloudfunctions.net/<function_name> -H "Authorization:
     bearer $(gcloud auth print-identity-token)" -H "Content-Type:application/json" -d '{"name": "Jane"}'
</code>```

Output:

Body:
I'm using google cloud's "Hello World" demo for cloud functions but the URL it produces gives me an error:

Error: Page not found
The requested URL was not found on this server.

I follow the tutorial, check allow unauthenticated, etc yet the url trigger leads me to the error.

The curl response requested also returns an error:

curl -X POST MY_URL  -H "Content-Type:application/json"  -d '{"name":"Jane"}'

returns:

<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404 Page not found</title>

Error: Page not found

The requested URL was not found on this server.

Any ideas why?

edit: testing works just fine

Edit2: the url in MY_URL is structured like this:
curl -X POST https://us-west1-PROJECT-NAME.cloudfunctions.net/FUNCTION-NAME  -H "Content-Type:application/json"  -d '{"message":"Jane"}'

Body:
According to this GCP doc:

As of January 15, 2020, all HTTP functions by default require most invokers to be authenticated. To allow unauthenticated invocation you must specify this at or after deployment.

After deployment, manually add the Cloud Functions Invoker permission to allUsers users in the Cloud Functions page in the Google Cloud Console.

However, it's always a best practice to set authorization on your cloud functions.

I was able to curl the endpoint successfully using:

curl -X POST https://us-central1-<project_name>.cloudfunctions.net/<function_name> -H "Authorization:
     bearer $(gcloud auth print-identity-token)" -H "Content-Type:application/json" -d '{"name": "Jane"}'

Output:


问:
PHP multidimensional array to variables
Ok I am getting info from poloniex API.

It comes back as an array like so:

```<code>Array ( [0] => Array ( [id] => 357988064 [currency] => DOGE [rate] => 0.00008000 [amount] => 3134.03982846 [duration] => 0.25540000 [interest] => 0.06403308 [fee] => -0.00960496 [earned] => 0.05442812 [open] => 2017-05-30 23:12:09 [close] => 2017-05-31 05:19:55 ) [1] => Array ... and so on
</code>```

Now I am trying to get each element of the array into some sort of variable to use later.

So something like this:

```<code>$id=[id]
$currency=[currency]
$rate=[rate]
$amount=[amount]
$duration=[duration]
$interest=interest]
$fee=fee]
$earned=[earned]
$open=[open]
$close=[close]
</code>```

I want to  put them into a mysqli DB

This is what i am using right now:

```<code>if (!$return) {
    echo "No Data";
    print_r($return);
} else {
    $arrlength=count($return);
    echo "this many results: " .$arrlength. "<br><br>";
    foreach($return as $x=>$x_value)
      {

        echo $return[0][0]. ": Currency: " .$return[0][1]. ". Rate: " .$return[0][2]. " Duration: " .$return[0][3]. " Interest: " .$return[0][4]. " Fee: " .$return[0][5]. " Earned: " .$return[0][6]. " Opened: " .$return[0][7]. " Closed: " .$return[0][8]. "<br>";

        //  insert into Database here
      }

    // print_r($return);
}
</code>```

And all it is returning is

```<code> : Currency: . Rate: Duration: Interest: Fee: Earned: Opened: Closed:
</code>```

I am a newbie with arrays but i have had success with api's with Json this is 1st  with Arrays.

Been tinkering for a few days with this and i just cant get the right combo

EDIT:
for anyone who can use this info i went the answer below and to display it on one line i went like this.

```<code>if (!$return) {
    echo "No Data";
    //print_r($return);
} else {
    $arrlength=count($return);
    echo "this many results: " .$arrlength. "<br><br>";

foreach($return as $x=>$x_value){
    extract($x_value);
    echo $id."   " .$currency."   " .$rate."   " .$duration."   " .$interest."   " .$fee."   " .$earned."   " .strtotime($open)."   " .strtotime($close)."<br>";
    //  insert into Database here
    }
    // print_r($return);
}
</code>```

答:
PHP Multidimensional array to variable

```<code><?php
$array = Array
(
    'success' => '1',
    'result' => array(
        'id' => '12345678ABCDEXXX',
        'userid' => '2950',
        'system_user_id' => '76',
        'coin' => 'TRX',
        'amount' => '11.110000',
        'feePercent' => '0',
        'feeAmount' => '0',
        'memoTag' => '',
        'networkFee' => '0',
        'address' => 'TESTADDRESSHERE',
        'confirmations' => '0',
        'callBackUrl' => 'www.xyz.com/test',
        'transactionStatus' => 'WaitingForTransaction',
        'transactionType' => 'Deposit',
        'createdOn' => '1643692929',
        'modifiedOn' => '1643692929',
        'expiredon' => '1644988929',
        'description' => 'This is description'
    )
);

function extractMultidimentional($array){
    foreach ($array as $key => $value) {
        if(is_array($value)){
            extractMultidimentional($value);
        }else{
            global ${$key};//Set as global
            ${$key} = $value;//Assign with its value
        }
    }
}

extractMultidimentional($array);

// Now you can call each key as a variable
echo $success;//1
echo $system_user_id;//76
echo $expiredon;//1644988929
</code>```

If you have multidimensional array and those have same key then the variable will store last array value

Title: PHP multidimensional array to variables

Body:
Ok I am getting info from poloniex API.

It comes back as an array like so:

Array ( [0] => Array ( [id] => 357988064 [currency] => DOGE [rate] => 0.00008000 [amount] => 3134.03982846 [duration] => 0.25540000 [interest] => 0.06403308 [fee] => -0.00960496 [earned] => 0.05442812 [open] => 2017-05-30 23:12:09 [close] => 2017-05-31 05:19:55 ) [1] => Array ... and so on

Now I am trying to get each element of the array into some sort of variable to use later.

So something like this:

$id=[id]
$currency=[currency]
$rate=[rate]
$amount=[amount]
$duration=[duration]
$interest=interest]
$fee=fee]
$earned=[earned]
$open=[open]
$close=[close]

I want to  put them into a mysqli DB

This is what i am using right now:

if (!$return) {
    echo "No Data";
    print_r($return);
} else {
    $arrlength=count($return);
    echo "this many results: " .$arrlength. "

";
    foreach($return as $x=>$x_value)
      {

        echo $return[0][0]. ": Currency: " .$return[0][1]. ". Rate: " .$return[0][2]. " Duration: " .$return[0][3]. " Interest: " .$return[0][4]. " Fee: " .$return[0][5]. " Earned: " .$return[0][6]. " Opened: " .$return[0][7]. " Closed: " .$return[0][8]. "
";

        //  insert into Database here
      }

    // print_r($return);
}

And all it is returning is

 : Currency: . Rate: Duration: Interest: Fee: Earned: Opened: Closed:

I am a newbie with arrays but i have had success with api's with Json this is 1st  with Arrays.

Been tinkering for a few days with this and i just cant get the right combo

EDIT:
for anyone who can use this info i went the answer below and to display it on one line i went like this.

if (!$return) {
    echo "No Data";
    //print_r($return);
} else {
    $arrlength=count($return);
    echo "this many results: " .$arrlength. "

";

foreach($return as $x=>$x_value){
    extract($x_value);
    echo $id."   " .$currency."   " .$rate."   " .$duration."   " .$interest."   " .$fee."   " .$earned."   " .strtotime($open)."   " .strtotime($close)."
";
    //  insert into Database here
    }
    // print_r($return);
}

Body:
PHP Multidimensional array to variable

<?php
$array = Array
(
    'success' => '1',
    'result' => array(
        'id' => '12345678ABCDEXXX',
        'userid' => '2950',
        'system_user_id' => '76',
        'coin' => 'TRX',
        'amount' => '11.110000',
        'feePercent' => '0',
        'feeAmount' => '0',
        'memoTag' => '',
        'networkFee' => '0',
        'address' => 'TESTADDRESSHERE',
        'confirmations' => '0',
        'callBackUrl' => 'www.xyz.com/test',
        'transactionStatus' => 'WaitingForTransaction',
        'transactionType' => 'Deposit',
        'createdOn' => '1643692929',
        'modifiedOn' => '1643692929',
        'expiredon' => '1644988929',
        'description' => 'This is description'
    )
);

function extractMultidimentional($array){
    foreach ($array as $key => $value) {
        if(is_array($value)){
            extractMultidimentional($value);
        }else{
            global ${$key};//Set as global
            ${$key} = $value;//Assign with its value
        }
    }
}

extractMultidimentional($array);

// Now you can call each key as a variable
echo $success;//1
echo $system_user_id;//76
echo $expiredon;//1644988929

If you have multidimensional array and those have same key then the variable will store last array value


问:
Spring boot rest api, fail on unknown property in the body request
I have a spring-boot rest api service.
Just for one of the rest POST api calls I would like to make sure that no additional properties are send in the request body object. I have realised there is a way to use a custom objectMapper that will fail deserialisation in this kind of case but I have a bit of problem setting up an object mapper just for the particular call. What would be the best approach, pls write/extend my example.

My example:

```<code>PostMapping("/")
public static ResponseEntity apiCallNeedsToFailInCaseOfAdditionalPropertiesInBody(@RequestBody body){
/// some code
}
</code>```

Thanks

答:
As far as I know, if you are trying to hit API via Postman, it will automatically give you a result with error message saying "Additional parameters/properties found" or something similar in error response when you passed additional parameter(s).

Your solution will also work, but no need for the same.

Instead, when you have endpoints growing in your application, you can make use of @Valid and @Validated annotations to take care of that request body parameter validations.

Check if this article throws some light around your query

Difference between @Valid and @Validated in Spring

Body:
I have a spring-boot rest api service.
Just for one of the rest POST api calls I would like to make sure that no additional properties are send in the request body object. I have realised there is a way to use a custom objectMapper that will fail deserialisation in this kind of case but I have a bit of problem setting up an object mapper just for the particular call. What would be the best approach, pls write/extend my example.

My example:

PostMapping("/")
public static ResponseEntity apiCallNeedsToFailInCaseOfAdditionalPropertiesInBody(@RequestBody body){
/// some code
}

Thanks


问:
Navigation and View Controller help in iOS 15 and Xcode 13
HI i have searched everywhere for a solution to my problem and cannot figure it out or found any other posts with the same problem.

I recently updated my Xcode project to Xcode 13 and my iPhone to iOS 15 and Apple made some significant changes to the navigation and tab bar structure which completely destroyed my app.

Need assistance on the correct structure on how to resolve this problem and am sure this will help lots of people who come across this same issue.

I have a ViewControllerA inside of a navigation controller which is nested inside of tab bar controller. User taps a button and segues to another ViewControllerB which is a modal VC that goes over full screen. User can then swipe down with a panGestureRecognizer.
As user swipes down there is a strange flicker effect which looks awful. The only solution I found is in storyboards to completely remove navigation bar and apply constraints to top of the view(I know this is possible but not scalable as I do not want to determine device size). But then view is covered by top bar.

I have attached video showing problem.

Please help as I do not know where to go from here.

THANK YOU

```<code>var initialTouchPoint: CGPoint = CGPoint(x: 0,y: 0)

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    tableView.estimatedRowHeight = 636
    tableView.rowHeight = UITableView.automaticDimension

}

@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) {

    let touchPoint = sender.location(in: self.view?.window)

    if sender.state == UIGestureRecognizer.State.began {
        initialTouchPoint = touchPoint
    } else if sender.state == UIGestureRecognizer.State.changed {
        if touchPoint.y - initialTouchPoint.y > 0 {
            self.view.frame = CGRect(x: 0, y: touchPoint.y - initialTouchPoint.y, width: self.view.frame.size.width, height: self.view.frame.size.height)
        }
    } else if sender.state == UIGestureRecognizer.State.ended || sender.state == UIGestureRecognizer.State.cancelled {
        if touchPoint.y - initialTouchPoint.y > 100 {
            self.dismiss(animated: true)
        } else {
            UIView.animate(withDuration: 0.3, animations: {
                self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
            })
        }
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "SwipeDownCell", for: indexPath) as! SwipeDownTableViewCell
    cell.postImageView.image = UIImage(named: "food")
    cell.postImageView.contentMode = .scaleAspectFill
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
</code>```

https://streamable.com/924xoo

答:
I have the same issue. It is caused by a combination of safeArea and the modalPresentationStyle of the parent view controller. In my case it is UIModalPresentationOverCurrentContext.
If you use other presentation styles, e.g. UIModalPresentationPopover, the flickering disappear.

As this is not appropriate in my case, I found an easy workaround.
You need to set the top constraint of your first item in the child view to refer the superview, not the safe area!

To better support devices without the notch, you can use following helper method implemented in AppDelegate.

```<code>- (UIEdgeInsets)getSafeAreaInsets {
if (@available(iOS 11.0, *)) {
    UIEdgeInsets insets = self.window.safeAreaInsets;
    return insets;
} else {
    return UIEdgeInsetsZero;
}
</code>```

Call this in the viewDidLoad of the child view and check if the bottom edge is 0.

```<code>//classic devices without notch
if ([(AppDelegate*)[[UIApplication sharedApplication] delegate] getSafeAreaInsets].bottom == 0) {
    self.labelHeaderContraint.constant = 32;
}
</code>```

Body:
HI i have searched everywhere for a solution to my problem and cannot figure it out or found any other posts with the same problem.

I recently updated my Xcode project to Xcode 13 and my iPhone to iOS 15 and Apple made some significant changes to the navigation and tab bar structure which completely destroyed my app.

Need assistance on the correct structure on how to resolve this problem and am sure this will help lots of people who come across this same issue.

I have a ViewControllerA inside of a navigation controller which is nested inside of tab bar controller. User taps a button and segues to another ViewControllerB which is a modal VC that goes over full screen. User can then swipe down with a panGestureRecognizer.
As user swipes down there is a strange flicker effect which looks awful. The only solution I found is in storyboards to completely remove navigation bar and apply constraints to top of the view(I know this is possible but not scalable as I do not want to determine device size). But then view is covered by top bar.

I have attached video showing problem.

Please help as I do not know where to go from here.

THANK YOU

var initialTouchPoint: CGPoint = CGPoint(x: 0,y: 0)

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    tableView.estimatedRowHeight = 636
    tableView.rowHeight = UITableView.automaticDimension

}

@IBAction func panGestureRecognizerHandler(_ sender: UIPanGestureRecognizer) {

    let touchPoint = sender.location(in: self.view?.window)

    if sender.state == UIGestureRecognizer.State.began {
        initialTouchPoint = touchPoint
    } else if sender.state == UIGestureRecognizer.State.changed {
        if touchPoint.y - initialTouchPoint.y > 0 {
            self.view.frame = CGRect(x: 0, y: touchPoint.y - initialTouchPoint.y, width: self.view.frame.size.width, height: self.view.frame.size.height)
        }
    } else if sender.state == UIGestureRecognizer.State.ended || sender.state == UIGestureRecognizer.State.cancelled {
        if touchPoint.y - initialTouchPoint.y > 100 {
            self.dismiss(animated: true)
        } else {
            UIView.animate(withDuration: 0.3, animations: {
                self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
            })
        }
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "SwipeDownCell", for: indexPath) as! SwipeDownTableViewCell
    cell.postImageView.image = UIImage(named: "food")
    cell.postImageView.contentMode = .scaleAspectFill
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

https://streamable.com/924xoo

Body:
I have the same issue. It is caused by a combination of safeArea and the modalPresentationStyle of the parent view controller. In my case it is UIModalPresentationOverCurrentContext.
If you use other presentation styles, e.g. UIModalPresentationPopover, the flickering disappear.

As this is not appropriate in my case, I found an easy workaround.
You need to set the top constraint of your first item in the child view to refer the superview, not the safe area!

To better support devices without the notch, you can use following helper method implemented in AppDelegate.

- (UIEdgeInsets)getSafeAreaInsets {
if (@available(iOS 11.0, *)) {
    UIEdgeInsets insets = self.window.safeAreaInsets;
    return insets;
} else {
    return UIEdgeInsetsZero;
}

Call this in the viewDidLoad of the child view and check if the bottom edge is 0.

//classic devices without notch
if ([(AppDelegate*)[[UIApplication sharedApplication] delegate] getSafeAreaInsets].bottom == 0) {
    self.labelHeaderContraint.constant = 32;
}


问:
Turn a function to output a 1 or 0 to be used as a check inside main
I have included a part of the code to demonstrate what I attempt to do.
The idea is to create a function that can be used as a validation of whether a number is valid and that function to be used inside main. Therefore what I have written in the function e.g the message of whether a day is valid or not, should only return instead a 1 if the day is valid and a zero when a day is invalid.

```<code>struct example {
    int day;
    int month;
    int year;
};
</code>```

Above is the struct:

```<code>#include <stdio.h>
int checkday();

int main() {
   if checkday() == 1
       print("%d is valid  date.\n", ex.day)
    return 0;
}
</code>```

I have written the code below to be used as a check for whether a day is valid or not. And I am thinking of returning 1 if it is valid or 0 if it is not. Then, inside main I will use this function for this purpose and then I will print the relevant message (if it is valid or not) from inside main.

The problem is that if I keep only the cases that check if it is valid and then make it reuturn 1, then how it will work for the cases that the date is invalid.

```<code>int checkday(){
    struct example ex;
    if((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3))
        printf("%d is valid  date.\n", ex.day);
    else if((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        printf("%d is valid  date.\n", ex.day);
    else
        printf("%d is invalid date.\n", ex.day);
}
</code>```

答:
You probably need to get the struct as a parameter to the function, it doesn't make sense to use a function otherwise. You should also use the return statement instead of printing.

```<code>int checkday(struct example ex){
    if ((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3)) ||
       ((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        return 1;
    return 0;
}
</code>```

Then use:

```<code>int main() {
    ....
    if checkday(ex)
        print("%d is valid  date.\n", ex.day);
    return 0;
}
</code>```

Body:
I have included a part of the code to demonstrate what I attempt to do.
The idea is to create a function that can be used as a validation of whether a number is valid and that function to be used inside main. Therefore what I have written in the function e.g the message of whether a day is valid or not, should only return instead a 1 if the day is valid and a zero when a day is invalid.

struct example {
    int day;
    int month;
    int year;
};

Above is the struct:

#include <stdio.h>
int checkday();

int main() {
   if checkday() == 1
       print("%d is valid  date.\n", ex.day)
    return 0;
}

I have written the code below to be used as a check for whether a day is valid or not. And I am thinking of returning 1 if it is valid or 0 if it is not. Then, inside main I will use this function for this purpose and then I will print the relevant message (if it is valid or not) from inside main.

The problem is that if I keep only the cases that check if it is valid and then make it reuturn 1, then how it will work for the cases that the date is invalid.

int checkday(){
    struct example ex;
    if((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3))
        printf("%d is valid  date.\n", ex.day);
    else if((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        printf("%d is valid  date.\n", ex.day);
    else
        printf("%d is invalid date.\n", ex.day);
}

Body:
You probably need to get the struct as a parameter to the function, it doesn't make sense to use a function otherwise. You should also use the return statement instead of printing.

int checkday(struct example ex){
    if ((ex.day>=1 && ex.day<=3) && (ex.month==1 || ex.month==3)) ||
       ((ex.day>=1 && ex.day<=12) && (ex.month==4 || ex.month==6))
        return 1;
    return 0;
}

Then use:

int main() {
    ....
    if checkday(ex)
        print("%d is valid  date.\n", ex.day);
    return 0;
}


问:
Java Generics, why is it illegal to use inheritance in generics?
I have this structure:

```<code>///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}
</code>```

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

答:
Polymorphism doesn't work for generics like for arrays for exemple.

The JVM doesn't know at runtime the type of the object, this is called type erasure and was done for retrocompatibility.
Only the compiler knows the type of an instance.

Generics were designed mostly for collections... The matter is that you must know that it IS possible to insert a String to a List, if you pass for exemple an ArrayList of integers to a method taking a List

Give a try to the following code that will surprise you:

```<code>public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i=0 ; i<10 ; i++ ) {
        set.add(i);
    }
    methode(set);
    for ( Integer i : set ) {
        System.out.println(i);
    }
}
public static void methode(Set set) {
    set.add("test");
}
</code>```

It does compile, run and even give some numbers before raising an exception!

Now let's review the following code:

```<code>public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i=0 ; i<10 ; i++ ) {
        set.add(i);
    }
    methode(set); // NOK
    for ( Integer i : set ) {
        System.out.println(i);
    }
}
public static void methode(Set<Number> set) {
    set.add(3f);
}
</code>```

It's almost the same here, if polymorphism was ok with generics, you could pass a set of integers to a method that takes a set of numbers, and then add a float to the set of integers!

Sun designed generics so that if you do not use legacy non typed code, your collections keep being type safe...

Like Bozho said, in my exemple you could use as argument

```<code>Set<? extends Number>
</code>```

and thus it would be possible to pass a set of integers to the method.
I don't remember exactly, but in this case i think java gives you a warning on the danger of inserting a new item to that list...

Body:
I have this structure:

///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

Body:
Polymorphism doesn't work for generics like for arrays for exemple.

The JVM doesn't know at runtime the type of the object, this is called type erasure and was done for retrocompatibility.
Only the compiler knows the type of an instance.

Generics were designed mostly for collections... The matter is that you must know that it IS possible to insert a String to a List, if you pass for exemple an ArrayList of integers to a method taking a List

Give a try to the following code that will surprise you:

public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i=0 ; i<10 ; i++ ) {
        set.add(i);
    }
    methode(set);
    for ( Integer i : set ) {
        System.out.println(i);
    }
}
public static void methode(Set set) {
    set.add("test");
}

It does compile, run and even give some numbers before raising an exception!

Now let's review the following code:

public static void main(String[] args) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i=0 ; i<10 ; i++ ) {
        set.add(i);
    }
    methode(set); // NOK
    for ( Integer i : set ) {
        System.out.println(i);
    }
}
public static void methode(Set<Number> set) {
    set.add(3f);
}

It's almost the same here, if polymorphism was ok with generics, you could pass a set of integers to a method that takes a set of numbers, and then add a float to the set of integers!

Sun designed generics so that if you do not use legacy non typed code, your collections keep being type safe...

Like Bozho said, in my exemple you could use as argument

Set<? extends Number>

and thus it would be possible to pass a set of integers to the method.
I don't remember exactly, but in this case i think java gives you a warning on the danger of inserting a new item to that list...


问:
For loop question in python about printing the columns first then printing the row
I have a programme that can help me to calculate some values.
And the result of this output is like a triangle.

```<code>S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

print(('{:0.4f} ' * n).format(*S))  # print initial line

for i in range(1,n):                # loop over rows
    for j in range(i+1, n+1):       # then over columns
        num = (1 + S[j -1])**j      # Calculating x by a certain formula
        den = (1 + S[i - 1])**i     # Calculating x by a certain formula
        x = (num/den)**(1/(j - i)) -1       # Calculating x by a certain formula and get the value of x
        print('{:0.4f}'.format(x), end=' ') # print all the values followed with a space
    print('')                       # add a newline after a full row
</code>```

If I run the codes above, I will have

```<code>0.0600 0.0645 0.0680 0.0710 0.0736 0.0756 0.0777
0.0690 0.0720 0.0747 0.0770 0.0787 0.0807
0.0750 0.0775 0.0797 0.0812 0.0830
0.0801 0.0821 0.0833 0.0850
0.0841 0.0849 0.0867
0.0857 0.0880
0.0904
</code>```

But what if I only got the first column (of the result after running my programme) as my input, that is

```<code>0.0600
0.0690
0.0750
0.0801
0.0841
0.0857
0.0904
</code>```

How could I restore the whole table (i.e. the whole triangle) by modifying the original codes and INVERSE OPERATION of the formula? Do I need to add a new for loop on the original codes?

In other words,
if I was given a formula x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])i))(1/(j-i))) - 1 , which is inside the programme.
Then, let us assume that I can get a result of

```<code>1 2 3     #the numbers (1 - 6) represents the order of being printed
4 5
6
</code>```

but how could I changing the format of my triangle from a pattern above to a pattern

```<code>1 4 6     #the numbers (1 - 6) represents the order of being printed
2 5
3
</code>```

BY INVERSE OPERATION of the formula?

Body:
I have a programme that can help me to calculate some values.
And the result of this output is like a triangle.

S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

print(('{:0.4f} ' * n).format(*S))  # print initial line

for i in range(1,n):                # loop over rows
    for j in range(i+1, n+1):       # then over columns
        num = (1 + S[j -1])**j      # Calculating x by a certain formula
        den = (1 + S[i - 1])**i     # Calculating x by a certain formula
        x = (num/den)**(1/(j - i)) -1       # Calculating x by a certain formula and get the value of x
        print('{:0.4f}'.format(x), end=' ') # print all the values followed with a space
    print('')                       # add a newline after a full row

If I run the codes above, I will have

0.0600 0.0645 0.0680 0.0710 0.0736 0.0756 0.0777
0.0690 0.0720 0.0747 0.0770 0.0787 0.0807
0.0750 0.0775 0.0797 0.0812 0.0830
0.0801 0.0821 0.0833 0.0850
0.0841 0.0849 0.0867
0.0857 0.0880
0.0904

But what if I only got the first column (of the result after running my programme) as my input, that is

0.0600
0.0690
0.0750
0.0801
0.0841
0.0857
0.0904

How could I restore the whole table (i.e. the whole triangle) by modifying the original codes and INVERSE OPERATION of the formula? Do I need to add a new for loop on the original codes?

In other words,
if I was given a formula x = ((((1 + k[j - 1])**j) / ((1 + k[i - 1])i))(1/(j-i))) - 1 , which is inside the programme.
Then, let us assume that I can get a result of

1 2 3     #the numbers (1 - 6) represents the order of being printed
4 5
6

but how could I changing the format of my triangle from a pattern above to a pattern

1 4 6     #the numbers (1 - 6) represents the order of being printed
2 5
3

BY INVERSE OPERATION of the formula?

Body:
In general terms:

instead of printing each line, save each entry from that line into a list

instead of printing a new line in the outer loop, create a new list and save the previous one within another "results" list.

loop over this two-dimensional list, reverse, sort or whatever, and print it however you like

And in more concrete terms:

from itertools import zip_longest

S = [0.06,0.0645,0.068,0.071,0.0736,0.0756,0.0777]

n = len(S)

results = []
results += [S]

for i in range(1,n):                # loop over rows
    line = []
    for j in range(i+1, n+1):       # then over columns
        num = (1 + S[j -1])**j      # Calculating x by a certain formula
        den = (1 + S[i - 1])**i     # Calculating x by a certain formula
        x = (num/den)**(1/(j - i)) -1       # Calculating x by a certain formula and get the value of x
        line += [x]
    results += [line]

for line in results:
    for entry in line:
        print(entry, end='')
    print('')

print("-" * 10)
for line in zip_longest(*results):
    for entry in line:
        if entry is not None:
            print(entry, end=' ')
    print('')

0.060.06450.0680.0710.07360.07560.0777
0.069019103773584780.072022613109848480.074691975296487630.077027177187337430.07874744277738710.08067860239842739
0.075034561087013340.077539689995302920.079709843727620910.081193329041452820.08302571799174219
0.080050656549259140.082055104262303670.083254082397003830.08503277149878619
0.084063271995895580.084859356567028140.08669857831554517
0.085656025744853540.08801863286709821
0.09038638150035694
----------
0.06 0.06901910377358478 0.07503456108701334 0.08005065654925914 0.08406327199589558 0.08565602574485354 0.09038638150035694
0.0645 0.07202261310984848 0.07753968999530292 0.08205510426230367 0.08485935656702814 0.08801863286709821
0.068 0.07469197529648763 0.07970984372762091 0.08325408239700383 0.08669857831554517
0.071 0.07702717718733743 0.08119332904145282 0.08503277149878619
0.0736 0.0787474427773871 0.08302571799174219
0.0756 0.08067860239842739
0.0777

I will leave the number formatting to you.


问:
How to change font color of select2 control using css
I am using the following HTML code to include a select2 control in my form as below.

```<code><select id="element_id" class="select2" style="width:100%">
<option value="e1" >Element 1</option>
<option value="e2" >Element 2</option>
<option value="e3" >Element 3</option>
</select>
</code>```

I am using the following style to format the font of the list items and selected item.

```<code><style>
    #s2id_element_id .select2-container--default .select2-selection--single .select2-selection__rendered
    {
        color: green ;
    }
</style>
</code>```

This does not color the list items and selected item in green color.
Note: I only need this specific select box to have the style but not others.  So I am using the css id selector for specific select2 control.

Thanks.

Body:
I am using the following HTML code to include a select2 control in my form as below.

<select id="element_id" class="select2" style="width:100%">
<option value="e1" >Element 1</option>
<option value="e2" >Element 2</option>
<option value="e3" >Element 3</option>
</select>

I am using the following style to format the font of the list items and selected item.

This does not color the list items and selected item in green color.
Note: I only need this specific select box to have the style but not others.  So I am using the css id selector for specific select2 control.

Thanks.

Body: $("#select2-**element_id**-container").css('color','green');


问:
Apps Script to clear multiple cells in row if they don't contain a value in another cell
I have a simple sheet that's scraped product details from a website along with their image URLs. Not all URLs are correct for the product and I would like to remove the cells that contain the incorrect ones. Each URL contains the product SKU. The correct product SKU can be found in Column C. All image URLs are in Columns C-X.

Screenshot of sheet

Is there a simple script that can do this for me?

Thanks!

答:
Probably something like this:

```<code>function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var range = sh.getDataRange();
  var [header, ...rows] = range.getValues();
  var new_rows = [];

  for (let row of rows) {
    var sku = row[2];
    var images = row.slice(8).map(x => x.indexOf(sku)>-1 ? x : ''); // '8' is column 'J'
    new_rows.push([...row.slice(0,8), ...images]);
  }

  range.setValues([header, ...new_rows]);
}
</code>```

It cleans all cells in columns J, K, L, etc. if a cell doesn't contain 'SKU' (column C, current row)

Body:
Probably something like this:

function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();
  var range = sh.getDataRange();
  var [header, ...rows] = range.getValues();
  var new_rows = [];

  for (let row of rows) {
    var sku = row[2];
    var images = row.slice(8).map(x => x.indexOf(sku)>-1 ? x : ''); // '8' is column 'J'
    new_rows.push([...row.slice(0,8), ...images]);
  }

  range.setValues([header, ...new_rows]);
}

It cleans all cells in columns J, K, L, etc. if a cell doesn't contain 'SKU' (column C, current row)


问:
How to sort by first few letters of string?
For example, if I have an array of strings {"Bob", "Bom", "Ash", "Ben"}, how do I sort it first by first letter (ASCII value), then by second letter, and so on without losing the previous sorted order? so after sorting it would become {"Ash", "Ben", "Bob", "Bom"}?

答:
Other option:</p>
```<code>String[] names = {"Bob", "Bom", "Ash", "Ben"};
System.out.println(new TreeSet(Arrays.asList(names)));
</code>```

Body:
Other option:

String[] names = {"Bob", "Bom", "Ash", "Ben"};
System.out.println(new TreeSet(Arrays.asList(names)));


问:
index.php and protecting of its content
What are the chances hackers are able to download index.php file from the server (not the result, but the content of index.php file)? Do you recommend to put the content of index.php to modules/index_content.php, where modules folder is .htaccess protected AND index.php contains the only string <?php require_once('modules/index_content.php') ?> ?  Does it make sense?

答:
They can't download php files if you have setup PHP on your webserver.

As a note: protecting with htaccess the folder modules and in index.php you are including a file from that folder when someone is accessing index.php they will have to provide a password and username to access the included file.

Title: index.php and protecting of its content


问:
Is there a way to simplify multiple "greater than to"?
My goal is to simplify this formula. The problem is, I have limited knowledge of Excel. So I rely on the If logical operators. And, as consequence, the if formula is quite long for just 1 column.

The overview:

The current formula:

```<code>=IF(G10<C$3,F10>D$3,  IF(G10<C$4,F10>D$4,  IF(G10<C$5,F10>D$5,  IF(G10<C$6,F10>D$6,  IF(G10>C$7,F10>D$7)))))
</code>```

答:
Just thought of another idea:

```<code>=INDEX(IF(F11:F<>"",LOOKUP(G11:G,C3:C7,D3:D7)<F11:F,""))
</code>```

This will now spill-down results and will update these when you add more data.

Body:
My goal is to simplify this formula. The problem is, I have limited knowledge of Excel. So I rely on the If logical operators. And, as consequence, the if formula is quite long for just 1 column.

The overview:

The current formula:

=IF(G10<C$3,F10>D$3,  IF(G10<C$4,F10>D$4,  IF(G10<C$5,F10>D$5,  IF(G10<C$6,F10>D$6,  IF(G10>C$7,F10>D$7)))))

Body:
Just thought of another idea:

=INDEX(IF(F11:F<>"",LOOKUP(G11:G,C3:C7,D3:D7)<F11:F,""))

This will now spill-down results and will update these when you add more data.


问:
Changing the price text in b2bking plugin
The b2bking plugin has helped me alot with my shop. One of its features in that it can display both a wholesale and a retail price.

My problem is that we are a swedish shop and I would like it to say "ÅF-pris" and "RRP" instead of what is outputs by default.

I've tried modifying the code inside the plugin. It works but I know that it will stop working as soon as I update the plugin. This is why I want to do it with filter hooks provided by the plugin.

What I've tried (I am kinda new to PHP)

```<code>add_filter('b2bking_filter_wholesale_price_final', 'alex_translate_price_text');

function alex_translate_price_text($text_retail_price, $text_final_price){
    $text_retail_price = 'test_RRP: ';
    return $text_retail_price;

    $text_final_price = 'test_åf-pris: ';
    return $text_final_price;
}
</code>```

in the plugin, hook looks like this:

```<code>$price = apply_filters('b2bking_filter_wholesale_price_final', $price, $text_retail_price, $retail_price, $text_final_price, $b2b_price_price, $product_id);
</code>```

My thought process is that I want to change the variables "$text_retail_price" and "$text_final_price" to "ÅF-pris" and "RRP" as right now they contain "Retail price" and "Wholesale price".

答:
We're the developers of the plugin, glad to hear it's been useful to you,

There's now a setting where you can change these directly via B2BKing -> Settings -> Language & Text.

Body:
The b2bking plugin has helped me alot with my shop. One of its features in that it can display both a wholesale and a retail price.

My problem is that we are a swedish shop and I would like it to say "ÅF-pris" and "RRP" instead of what is outputs by default.

I've tried modifying the code inside the plugin. It works but I know that it will stop working as soon as I update the plugin. This is why I want to do it with filter hooks provided by the plugin.

What I've tried (I am kinda new to PHP)

add_filter('b2bking_filter_wholesale_price_final', 'alex_translate_price_text');

function alex_translate_price_text($text_retail_price, $text_final_price){
    $text_retail_price = 'test_RRP: ';
    return $text_retail_price;

    $text_final_price = 'test_åf-pris: ';
    return $text_final_price;
}

in the plugin, hook looks like this:

$price = apply_filters('b2bking_filter_wholesale_price_final', $price, $text_retail_price, $retail_price, $text_final_price, $b2b_price_price, $product_id);

My thought process is that I want to change the variables "$text_retail_price" and "$text_final_price" to "ÅF-pris" and "RRP" as right now they contain "Retail price" and "Wholesale price".


问:
Get back access to the development server
I ran manage.py check --deploy¶ for my django project before I was actually ready to deploy and now I can't seem to run

```<code>python3 manage.py runserver
</code>```

for any of my projects. Is there anyway to reverse my actions?

This is the error I get in my terminal whenever I try to access a project in my browser.

```<code>code 400, message Bad request version ('\x9a\x9a\x13\x01\x13\x02\x13\x03À+À/À,À0Ì©Ì¨À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93êê\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
</code>```

[10/Feb/2022 11:33:40] You're accessing the development server over HTTPS, but it only supports HTTP.

答:
You are trying to access your dev server over https

manage.py check --deploy most likely told you to set SECURE_SSL_REDIRECT = True in your settings.py

Try reverting it back to SECURE_SSL_REDIRECT = False

Body:
I ran manage.py check --deploy¶ for my django project before I was actually ready to deploy and now I can't seem to run

python3 manage.py runserver

for any of my projects. Is there anyway to reverse my actions?

This is the error I get in my terminal whenever I try to access a project in my browser.

code 400, message Bad request version ('\x9a\x9a\x13\x01\x13\x02\x13\x03À+À/À,À0Ì©Ì¨À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93êê\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')

[10/Feb/2022 11:33:40] You're accessing the development server over HTTPS, but it only supports HTTP.


问:
Get `one_of` specific items in SPAQRL
I use Wikidata as example. The following works (test it):

SELECT ?name ?nameLabel
WHERE
{
  wd:Q1339 wdt:P735 ?name.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}
```
<p>Now, suppose I have several items, e.g. <code>wd:Q1339</code>, <code>wd:Q76428</code> and <code>wd:Q57487</code>.</p>
<p>I want to construct a similar query but applied to exactly those items. If there was a magical <code>one_of</code> property (similar to <code>a</code>, which is a shortcut to <code>rdf:type</code> ), something like the following would be a solution (wrong pseudo-syntax):</p>
<pre class="lang-sql prettyprint-override"><code>SELECT ?name ?nameLabel
WHERE
{
  ?person one_of (wd:Q1339, wd:Q76428, wd:Q57487).
  ?person wdt:P735 ?name.

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}
</code>```

Question: How can I construct a query which yields the results?

(It should preferably be applicable not only to Wikidata.)

答:
Turning the comments from @Stanislav Kralin and @UninformedUser into an answer:

The desired keyword to assert identity of items is VALUES, see the example:

```<code>SELECT ?person ?name ?nameLabel
WHERE
{
  VALUES ?person {wd:Q1339 wd:Q76428 wd:Q57487}
  ?person wdt:P735 ?name.

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}
</code>```

Title: Get `one_of` specific items in SPAQRL

Body:
I use Wikidata as example. The following works (test it):

SELECT ?name ?nameLabel
WHERE
{
  wd:Q1339 wdt:P735 ?name.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}

Now, suppose I have several items, e.g. wd:Q1339, wd:Q76428 and wd:Q57487.

I want to construct a similar query but applied to exactly those items. If there was a magical one_of property (similar to a, which is a shortcut to rdf:type ), something like the following would be a solution (wrong pseudo-syntax):

SELECT ?name ?nameLabel
WHERE
{
  ?person one_of (wd:Q1339, wd:Q76428, wd:Q57487).
  ?person wdt:P735 ?name.

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}

Question: How can I construct a query which yields the results?

(It should preferably be applicable not only to Wikidata.)

Body:
Turning the comments from @Stanislav Kralin and @UninformedUser into an answer:

The desired keyword to assert identity of items is VALUES, see the example:

SELECT ?person ?name ?nameLabel
WHERE
{
  VALUES ?person {wd:Q1339 wd:Q76428 wd:Q57487}
  ?person wdt:P735 ?name.

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}


问:
Big O notation - python function
What is the Big O notation of this function (as a function of n = len(lst)):

```<code>def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += i
        jump = jump * 2
    return total
</code>```

I thought it was O(n*log(n)) but it's not, trying to understand why it's actually O(n)...
I'm kinda new in this so if you could also explain how you got to the answer it'll be the best! thanks

答:
The function is O(n).

The function makes about 2*n iterations to got into details (but 2*n is n in big O notation).

For each while loop you're jumping to the next power of 2, so for example for n=1000:

```<code>[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
</code>```

Then for each subloop, you go through all element, thus effectively doing sum(successive_powers) (in the example 1+2+4+…+512 = 1023).

The sum of the n first powers is roughly the power of the n+1, so here: 2**(log2(n)+1) ~ 2*n.

An easy way to check this is to change the code:

```<code>def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += 1 # count instead of summing
        jump = jump * 2
    return total

foo(list(range(1000)))
# 2000
</code>```

Title: Big O notation - python function

Body:
What is the Big O notation of this function (as a function of n = len(lst)):

def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += i
        jump = jump * 2
    return total

I thought it was O(n*log(n)) but it's not, trying to understand why it's actually O(n)...
I'm kinda new in this so if you could also explain how you got to the answer it'll be the best! thanks

Body:
The function is O(n).

The function makes about 2*n iterations to got into details (but 2*n is n in big O notation).

For each while loop you're jumping to the next power of 2, so for example for n=1000:

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Then for each subloop, you go through all element, thus effectively doing sum(successive_powers) (in the example 1+2+4+…+512 = 1023).

The sum of the n first powers is roughly the power of the n+1, so here: 2**(log2(n)+1) ~ 2*n.

An easy way to check this is to change the code:

def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += 1 # count instead of summing
        jump = jump * 2
    return total

foo(list(range(1000)))
# 2000


问:
How can I use one component (page) for multiple route in Next JS
As you all know Next JS doesn't have any route, I am trying to build a web app in next JS in which I have to use the same component for multiple routes without copy pasting in to different directory.

Directroy structure:

```<code>src
    pages
        new (AddListComponent)
        edit-[id] (AddListComponent)
</code>```

AddListComponent

```<code>import React from 'react'
import { withRouter } from 'next/router'

class Listing extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    render () {
        return (
            <div>This is my new component</div>
        )
    }
}
export default withRouter(Listing)
</code>```

答:
You can create a page with optional parameters.

```<code>pages
 ┣ tasks
 ┃ ┣ manage
 ┃ ┃ ┗ [[...id]].jsx
 ┃ ┣ index.jsx
 ┃ ┗ service.js
 ┣ _app.jsx
 ┣ dashboard.jsx
 ┣ index.jsx
 ┗ login.jsx
</code>```

/tasks/manage and tasks/manage/14 will route the same component [[...id]].jsx

Do not forget to use  double brackets and three dots.
[[...foo]].jsx

Catch all routes can be made optional by including the parameter in
double brackets ([[...slug]]).

For example, pages/post/[[...slug]].js will match /post, /post/a,
/post/a/b, and so on.

Please check for more info.

Body:
As you all know Next JS doesn't have any route, I am trying to build a web app in next JS in which I have to use the same component for multiple routes without copy pasting in to different directory.

Directroy structure:

src
    pages
        new (AddListComponent)
        edit-[id] (AddListComponent)

AddListComponent

import React from 'react'
import { withRouter } from 'next/router'

class Listing extends React.Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    render () {
        return (

This is my new component

        )
    }
}
export default withRouter(Listing)

Body:
You can create a page with optional parameters.

pages
 ┣ tasks
 ┃ ┣ manage
 ┃ ┃ ┗ [[...id]].jsx
 ┃ ┣ index.jsx
 ┃ ┗ service.js
 ┣ _app.jsx
 ┣ dashboard.jsx
 ┣ index.jsx
 ┗ login.jsx

/tasks/manage and tasks/manage/14 will route the same component [[...id]].jsx

Do not forget to use  double brackets and three dots.
[[...foo]].jsx

Catch all routes can be made optional by including the parameter in
double brackets ([[...slug]]).

For example, pages/post/[[...slug]].js will match /post, /post/a,
/post/a/b, and so on.

Please check for more info.


问:
Unique ID for interconnected cases
I have the following data frame, that shows which cases are interconnected:

```<code>   DebtorId DupDebtorId
1:        1           2
2:        1           3
3:        1           4
4:        5           1
5:        5           2
6:        5           3
7:        6           7
8:        7           6
</code>```

My goal is to assign a unique group ID to each group of cases. The desired output is:

```<code>   DebtorId group
1:        1     1
2:        2     1
3:        3     1
4:        4     1
5:        5     1
6:        6     2
7:        7     2
</code>```

My train of thought:

```<code>library(data.table)

example <- data.table(
  DebtorId = c(1,1,1,5,5,5,6,7),
  DupDebtorId = c(2,3,4,1,2,3,7,6)
)

unique_pairs <- example[!duplicated(t(apply(example, 1, sort))),] #get unique pairs of DebtorID and DupDebtorID
unique_pairs[, group := .GRP, by=.(DebtorId)] #assign a group ID for each DebtorId
unique_pairs[, num := rowid(group)]
groups <- dcast(unique_pairs, group + DebtorId ~ num, value.var = 'DupDebtorId') #format data to wide for each group ID

#create new data table with unique cases to assign group ID
newdt <- data.table(DebtorId = sort(unique(c(example$DebtorId, example$DupDebtorId))), group = NA)
newdt$group <- as.numeric(newdt$group)

#loop through the mapped groups, selecting the first instance of group ID for the case
for (i in 1:nrow(newdt)) {
  a <- newdt[i]$DebtorId
  b <- min(which(groups[,-1] == a, arr.ind=TRUE)[,1])
  newdt[i]$group <- b
}
</code>```

Output:

```<code>   DebtorId group
1:        1     1
2:        2     1
3:        3     1
4:        4     1
5:        5     2
6:        6     3
7:        7     3
</code>```

There are 2 problems in my approach:

From the output, you can see that it fails to recognize that case 5
belongs to group 1;

The final loop is agonizingly slow, which would
render it useless for my use case of 1M rows in my original data, and going the traditional := way does not work with which()

I'm not sure whether my approach could be optimized, or there is a better way of doing this altogether.

答:
This functionality already exists in igraph, so if you don't need to do it yourself, we can build a graph from your data frame and then extract cluster membership. stack() is just an easy way to convert a named vector to data frame.

library(igraph)

g <- graph.data.frame(df)
df_membership <- clusters(g)$membership
stack(df_membership)
#>   values ind
#> 1      1   1
#> 2      1   5
#> 3      2   6
#> 4      2   7
#> 5      1   2
#> 6      1   3
#> 7      1   4
```

Above, values corresponds to group and ind to DebtorId.

Title: Unique ID for interconnected cases

Body:
I have the following data frame, that shows which cases are interconnected:

   DebtorId DupDebtorId
1:        1           2
2:        1           3
3:        1           4
4:        5           1
5:        5           2
6:        5           3
7:        6           7
8:        7           6

My goal is to assign a unique group ID to each group of cases. The desired output is:

   DebtorId group
1:        1     1
2:        2     1
3:        3     1
4:        4     1
5:        5     1
6:        6     2
7:        7     2

My train of thought:

library(data.table)

example <- data.table(
  DebtorId = c(1,1,1,5,5,5,6,7),
  DupDebtorId = c(2,3,4,1,2,3,7,6)
)

unique_pairs <- example[!duplicated(t(apply(example, 1, sort))),] #get unique pairs of DebtorID and DupDebtorID
unique_pairs[, group := .GRP, by=.(DebtorId)] #assign a group ID for each DebtorId
unique_pairs[, num := rowid(group)]
groups <- dcast(unique_pairs, group + DebtorId ~ num, value.var = 'DupDebtorId') #format data to wide for each group ID

#create new data table with unique cases to assign group ID
newdt <- data.table(DebtorId = sort(unique(c(example$DebtorId, example$DupDebtorId))), group = NA)
newdt$group <- as.numeric(newdt$group)

#loop through the mapped groups, selecting the first instance of group ID for the case
for (i in 1:nrow(newdt)) {
  a <- newdt[i]$DebtorId
  b <- min(which(groups[,-1] == a, arr.ind=TRUE)[,1])
  newdt[i]$group <- b
}

Output:

   DebtorId group
1:        1     1
2:        2     1
3:        3     1
4:        4     1
5:        5     2
6:        6     3
7:        7     3

There are 2 problems in my approach:

From the output, you can see that it fails to recognize that case 5
belongs to group 1;

The final loop is agonizingly slow, which would
render it useless for my use case of 1M rows in my original data, and going the traditional := way does not work with which()

I'm not sure whether my approach could be optimized, or there is a better way of doing this altogether.

Body:
This functionality already exists in igraph, so if you don't need to do it yourself, we can build a graph from your data frame and then extract cluster membership. stack() is just an easy way to convert a named vector to data frame.

library(igraph)

g <- graph.data.frame(df)
df_membership <- clusters(g)$membership
stack(df_membership)
#>   values ind
#> 1      1   1
#> 2      1   5
#> 3      2   6
#> 4      2   7
#> 5      1   2
#> 6      1   3
#> 7      1   4

Above, values corresponds to group and ind to DebtorId.


问:
Docker doesn't start container cleanly after a process monitored by healthcheck crashes
I have a docker-compose with several services. The monitored processs inside one of the containers crashes from time to time and healtcheck detects this and restarts the container. Service is configured:
restart: unless-stopped
But there is an issue because after the restart the pid of rsyslog is not deleted and it cannot start. I can workaround this by deleting the pid in the start script before starting the rsyslog but I don't think it should behave this way. Docker container id is the same after the restart. It behaves like it has committed the container after the process crashed and then it only run the start script again. E.g. the container doesn't start cleanly but the changes made inside stay. The pid location is not a volume. I read the docker documentation on the topic - https://docs.docker.com/config/containers/start-containers-automatically/ but couldn't find anything helpful. Any idea?

答:
A container restart doesn't actually delete and recreate the container or its filesystem; it just restarts the main process within the existing container.

Since a container only runs one process, it's safe to unconditionally delete the pid file.  I'd tend to use an entrypoint wrapper script for this:

#!/bin/sh

# Delete the pid file, if it exists
rm -f /var/run/rsyslog.pid

# Run whatever the image CMD or `docker run` command is
exec "$@"
```
<p>In your Dockerfile, make this script be the <code>ENTRYPOINT</code>, and leave your existing <code>CMD</code> unchanged:</p>
<pre class="lang-sh prettyprint-override"><code>COPY entrypoint.sh .
ENTRYPOINT ["./entrypoint.sh"]
CMD ["rsyslogd", "--no-daemon"]
</code>```

Body:
A container restart doesn't actually delete and recreate the container or its filesystem; it just restarts the main process within the existing container.

Since a container only runs one process, it's safe to unconditionally delete the pid file.  I'd tend to use an entrypoint wrapper script for this:

#!/bin/sh

# Delete the pid file, if it exists
rm -f /var/run/rsyslog.pid

# Run whatever the image CMD or `docker run` command is
exec "$@"

In your Dockerfile, make this script be the ENTRYPOINT, and leave your existing CMD unchanged:

COPY entrypoint.sh .
ENTRYPOINT ["./entrypoint.sh"]
CMD ["rsyslogd", "--no-daemon"]


问:
Google Map not showing only google sign showing in android studio
I made an Activity of GoogleMap type and then as you know that all the codes automatically generated and given to us so and i created an API key and pasted it at required location then i run my app once in emulator and once in my real phone but in the both cases the google map is not showing only the google sign showing.

Google Map not showing only google sign showing

答: Ensure the google map api enabled to your google key.</p>