问:
JS lp-solver. How to use all the products at least once?
I made a linear program code for a diet app that minimizes the cost of products while meeting user's desired calories. It is working, at least somewhat working. The problem is that the result is made by using only the one, best product out of all products to get the lowest cost and meet the user's calories. I want to make it to use all of the products (if possible -> doesn't go over user's calories) at least once. I've tried to add some constraints to the model, but that didn't fix it, still getting the same result. Any suggestions? P.S. the "response" in the code is an array with keys (products) and information of them (see screenshot). "response" is fetched from another file (.php).

Defining model:

```<code>  // Set up the model
  const model = {
    optimize: "price",
    opType: "min",
    constraints: {
      "calories": { "equal": userCalories }
    },
    variables: {}
  };

  console.log(response);

  // Set up the variables and the constraints in the model
  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    //var price = parseFloat(response[i]['price'].replace(',', '.')); // Convert the price to a number
    model.variables[name] = {
      "price": parseFloat(response[i]['price'].replace(',', '.')),
      "calories": response[i]['calories']
    };
  }

  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    model.constraints[name] = {};
    model.constraints[name][name] = 1;
  }

  model.constraints["use_all"] = {};
  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    model.constraints["use_all"][name] = 1;
  }

  // Solve the linear program
  const result = solver.Solve(model);
  console.log(result);
</code>```

Result from this code:

Body:
I made a linear program code for a diet app that minimizes the cost of products while meeting user's desired calories. It is working, at least somewhat working. The problem is that the result is made by using only the one, best product out of all products to get the lowest cost and meet the user's calories. I want to make it to use all of the products (if possible -> doesn't go over user's calories) at least once. I've tried to add some constraints to the model, but that didn't fix it, still getting the same result. Any suggestions? P.S. the "response" in the code is an array with keys (products) and information of them (see screenshot). "response" is fetched from another file (.php).

Defining model:

  // Set up the model
  const model = {
    optimize: "price",
    opType: "min",
    constraints: {
      "calories": { "equal": userCalories }
    },
    variables: {}
  };

  console.log(response);

  // Set up the variables and the constraints in the model
  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    //var price = parseFloat(response[i]['price'].replace(',', '.')); // Convert the price to a number
    model.variables[name] = {
      "price": parseFloat(response[i]['price'].replace(',', '.')),
      "calories": response[i]['calories']
    };
  }

  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    model.constraints[name] = {};
    model.constraints[name][name] = 1;
  }

  model.constraints["use_all"] = {};
  for (var i = 0; i < response.length; i++) {
    var name = response[i]['name'];
    model.constraints["use_all"][name] = 1;
  }

  // Solve the linear program
  const result = solver.Solve(model);
  console.log(result);

Result from this code:


来源: stackexchange

问:
In a GlassFish web application, HTTP to HTTPS redirection works only the first time the http link is accessed in Internet Explorer
We have a GlassFish 4.1 web-application with SSL and port unification configured in domain.xml.

We cannot use built-in authentication mechanisms like BASIC, FORM, CERT-CLIENT. Instead, we use a custom login form (using the Stripes framework - https://github.com/StripesFramework).

We want to redirect all http requests to https, but in IE11 it does not work as expected: the HTTP link is converted into an HTTPS link only on the first access in the browser. Then if the HTTP link is used again in the same browser page, it is no longer replaced with HTTPS.

The issue only appears in Internet Explorer (we're using version 11).

We have tried putting this code in web.xml, as specified in the docs (https://docs.oracle.com/cd/E19226-01/820-7627/bncbk/index.html):

```<code><security-constraint>
    <display-name>Require HTTPS</display-name>
    <web-resource-collection>
        <web-resource-name>EntireApplication</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
</code>```

It works as expected the first time an http link pointing to the app login page is accessed, that is the URL prefix correctly changes from http to https before the page is displayed: http://webapp:8090/ctx_root/ to https://webapp:8090/ctx_root/.

But if afterwards I remove the s from the https prefix in the URL bar (only in IE11), and I press Enter, the http:// prefix is no longer replaced with https:// and the user gets a non-secure version of the login page, with some warnings in the Console: "HTTP security is compromised by http://webapp:8090/ctx_root/js/main.js". However, if the SSL state is cleared in the browser before the second try, the page is again redirected to HTTPS accordingly.

This doesn't happen in Chrome, where each and every time the link changes correctly from http to https.

This is the content of domain.xml:

```<code><network-config>
  <protocols>
    <protocol name="http-listener-1">
      <http encoded-slash-enabled="true" default-virtual-server="server">
        <file-cache></file-cache>
      </http>
    </protocol>
    <protocol name="http-listener-2" security-enabled="true">
      <http encoded-slash-enabled="true" default-virtual-server="server">
        <file-cache></file-cache>
      </http>
      <ssl ssl3-enabled="false" classname="com.sun.enterprise.security.ssl.GlassfishSSLImpl" cert-nickname="mycert"></ssl>
    </protocol>
    ....
    <protocol name="http-redirect">
      <http-redirect secure="true"></http-redirect>
    </protocol>
    <protocol name="pu-protocol-http">
      <port-unification>
        <protocol-finder protocol="http-listener-2" classname="org.glassfish.grizzly.config.portunif.HttpProtocolFinder" name="http-finder"></protocol-finder>
        <protocol-finder protocol="http-redirect" classname="org.glassfish.grizzly.config.portunif.HttpProtocolFinder" name="http-redirect"></protocol-finder>
      </port-unification>
    </protocol>
  </protocols>
  <network-listeners>
    <network-listener protocol="pu-protocol-admin" port="4848" name="admin-listener" thread-pool="admin-thread-pool" transport="tcp"></network-listener>
    <network-listener protocol="pu-protocol-http" port="8090" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp"></network-listener>
  </network-listeners>
  <transports>
    <transport name="tcp"></transport>
  </transports>
</network-config>
</code>```

Any idea why HTTP to HTTPS redirection works only the first time the http link is accessed? Could it be an IE11 or firewall issue?

ContentLicense: CC BY-SA 4.0

Body:
We have a GlassFish 4.1 web-application with SSL and port unification configured in domain.xml.

We cannot use built-in authentication mechanisms like BASIC, FORM, CERT-CLIENT. Instead, we use a custom login form (using the Stripes framework - https://github.com/StripesFramework).

We want to redirect all http requests to https, but in IE11 it does not work as expected: the HTTP link is converted into an HTTPS link only on the first access in the browser. Then if the HTTP link is used again in the same browser page, it is no longer replaced with HTTPS.

The issue only appears in Internet Explorer (we're using version 11).

We have tried putting this code in web.xml, as specified in the docs (https://docs.oracle.com/cd/E19226-01/820-7627/bncbk/index.html):

<security-constraint>
    <display-name>Require HTTPS</display-name>
    <web-resource-collection>
        <web-resource-name>EntireApplication</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

It works as expected the first time an http link pointing to the app login page is accessed, that is the URL prefix correctly changes from http to https before the page is displayed: http://webapp:8090/ctx_root/ to https://webapp:8090/ctx_root/.

But if afterwards I remove the s from the https prefix in the URL bar (only in IE11), and I press Enter, the http:// prefix is no longer replaced with https:// and the user gets a non-secure version of the login page, with some warnings in the Console: "HTTP security is compromised by http://webapp:8090/ctx_root/js/main.js". However, if the SSL state is cleared in the browser before the second try, the page is again redirected to HTTPS accordingly.

This doesn't happen in Chrome, where each and every time the link changes correctly from http to https.

This is the content of domain.xml:

<network-config>
  <protocols>
    <protocol name="http-listener-1">
      <http encoded-slash-enabled="true" default-virtual-server="server">
        <file-cache></file-cache>
      </http>
    </protocol>
    <protocol name="http-listener-2" security-enabled="true">
      <http encoded-slash-enabled="true" default-virtual-server="server">
        <file-cache></file-cache>
      </http>
      <ssl ssl3-enabled="false" classname="com.sun.enterprise.security.ssl.GlassfishSSLImpl" cert-nickname="mycert"></ssl>
    </protocol>
    ....
    <protocol name="http-redirect">
      <http-redirect secure="true"></http-redirect>
    </protocol>
    <protocol name="pu-protocol-http">
      <port-unification>
        <protocol-finder protocol="http-listener-2" classname="org.glassfish.grizzly.config.portunif.HttpProtocolFinder" name="http-finder"></protocol-finder>
        <protocol-finder protocol="http-redirect" classname="org.glassfish.grizzly.config.portunif.HttpProtocolFinder" name="http-redirect"></protocol-finder>
      </port-unification>
    </protocol>
  </protocols>
  <network-listeners>
    <network-listener protocol="pu-protocol-admin" port="4848" name="admin-listener" thread-pool="admin-thread-pool" transport="tcp"></network-listener>
    <network-listener protocol="pu-protocol-http" port="8090" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp"></network-listener>
  </network-listeners>
  <transports>
    <transport name="tcp"></transport>
  </transports>
</network-config>

Any idea why HTTP to HTTPS redirection works only the first time the http link is accessed? Could it be an IE11 or firewall issue?


问:
Different on click action depends on object property
Lets say I have an object that has isValid property. I want to attach on click listener that do the action depends on that property, so if ifValid is true I want to show dialog fragment otherwise just revert it.

What is the most efficent way to do that. I'm using lambda to set the listener when initialize adapter in my activity.

```<code>class ItemListAdapter(..., val listener: (Item, Int) -> Unit): ...
</code>```

ViewHolder:

```<code>fun bind(item: Item){
       binding.validBtn.setOnClickListener{ listener(item, adapterPosition) }
}
</code>```

Then in my activity

```<code>listAdapter = ItemListAdapter() { item, _ ->
            confirm(item)
        }
</code>```

Can I just make if statement in activity and check if item is valid like:

```<code>listAdapter = ItemListAdapter() { item, _ ->
            if(item.isValid!!)
            confirm(item)
            // else another action
        }
</code>```

Body:
Lets say I have an object that has isValid property. I want to attach on click listener that do the action depends on that property, so if ifValid is true I want to show dialog fragment otherwise just revert it.

What is the most efficent way to do that. I'm using lambda to set the listener when initialize adapter in my activity.

class ItemListAdapter(..., val listener: (Item, Int) -> Unit): ...

ViewHolder:

fun bind(item: Item){
       binding.validBtn.setOnClickListener{ listener(item, adapterPosition) }
}

Then in my activity

listAdapter = ItemListAdapter() { item, _ ->
            confirm(item)
        }

Can I just make if statement in activity and check if item is valid like:

listAdapter = ItemListAdapter() { item, _ ->
            if(item.isValid!!)
            confirm(item)
            // else another action
        }


问:
How change dpi in jsPDF html method?
I have figma design 2380х3368.
So, I create pdf with such parameters:

```<code>const doc = new jsPDF({orientation: 'portrait',unit: 'px', userUnit: 300, format: [2780, 3368]});
</code>```

and:

```<code>doc.html(pageTemplate.querySelector('html'), {
                        callback: function(doc) {

                            doc.save('pdf-template.pdf');
                        },
                        margin: [0,0,0,0],
});
</code>```

But this size is too big for printing pdf. I want dpi 300, so it would be ok, but I can't find where to put this in jsPDF

Title: How change dpi in jsPDF html method?

Body:
I have figma design 2380х3368.
So, I create pdf with such parameters:

const doc = new jsPDF({orientation: 'portrait',unit: 'px', userUnit: 300, format: [2780, 3368]});

and:

doc.html(pageTemplate.querySelector('html'), {
                        callback: function(doc) {

                            doc.save('pdf-template.pdf');
                        },
                        margin: [0,0,0,0],
});

But this size is too big for printing pdf. I want dpi 300, so it would be ok, but I can't find where to put this in jsPDF


问:
Find-Package | Install-Package (local feed)
I have setup a local feed and I want to install packages from it, from the command line

```<code>Find-Package -Name "*hukarz*" -Source C:\feed | Install-Package
</code>```

I get this error:

```<code>Install-Package : Unable to resolve package reference ''.
At line:1 char:47
+ Find-Package -Name "*core*" -Source C:\feed | Install-Package
+                                               ~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($UGFja2FnZSBzb3...4x\QzpcZmVlZA==:String) [Install-Package], Exception
    + FullyQualifiedErrorId : UnableToResolvePackage,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
</code>```

Should this command be able to install packages from a local feed?

The feed is also correctly registered

```<code>dotnet nuget list source
..
4.  Package source 1 [Enabled]
      c:\feed
</code>```

Installing from inside of Visual Studio works fine.

Body:
I have setup a local feed and I want to install packages from it, from the command line

Find-Package -Name "*hukarz*" -Source C:\feed | Install-Package

I get this error:

Install-Package : Unable to resolve package reference ''.
At line:1 char:47
+ Find-Package -Name "*core*" -Source C:\feed | Install-Package
+                                               ~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($UGFja2FnZSBzb3...4x\QzpcZmVlZA==:String) [Install-Package], Exception
    + FullyQualifiedErrorId : UnableToResolvePackage,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage

Should this command be able to install packages from a local feed?

The feed is also correctly registered

dotnet nuget list source
..
4.  Package source 1 [Enabled]
      c:\feed

Installing from inside of Visual Studio works fine.


问:
react-select custom single label for multi values?
When selecting an option in react-select multi select, the default behavior is that it adds the option from dropdown to the input and the selected option disappears from the menu.

How do I prevent the selected options from disappearing and how do I replace the default selected option elements in the controller to a single text element saying "n selected".

My react select currently:

```<code><ReactSelect
  isMulti
  options={vSystems}
  getOptionLabel={(option) => option.name}
  getOptionValue={(option) => option.id}
  defaultValue={vSystems}
  onChange={(val) => setSelectedSystems(val)}
  className="my-react-select-container"
  classNamePrefix="my-react-select"
/>
</code>```

Body:
When selecting an option in react-select multi select, the default behavior is that it adds the option from dropdown to the input and the selected option disappears from the menu.

How do I prevent the selected options from disappearing and how do I replace the default selected option elements in the controller to a single text element saying "n selected".

My react select currently:

<ReactSelect
  isMulti
  options={vSystems}
  getOptionLabel={(option) => option.name}
  getOptionValue={(option) => option.id}
  defaultValue={vSystems}
  onChange={(val) => setSelectedSystems(val)}
  className="my-react-select-container"
  classNamePrefix="my-react-select"
/>


问:
why C# UDPClient.client.Available alway equals 0?
Why UDPClient.client.Availabe == 0 while the Wireshark can catch the UDP package ?  I used the UDPClient to receive UDP package from other endpoint like below:

```<code>socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
socket.Bind(new IPEndPoint(IPAddress.Any, 1020));
socket.ReceiveTimeout = 100;
_udpReceiver = new UdpClient
{
    Client = socket
};

while (!_stopReceiveEvent.WaitOne(1))
{`your text`
    if (_udpReceiver.Available <= 0)
    {
        continue;
    }

    byte[] rawBytes = _udpReceiver.Receive(ref endPoint);

    //handle the rawBytes
    //....
}
</code>```

Most of time it worked normally, but occasionally the _udpReceiver.Avaiable equaled 0 while the Wireshark can catch the UDP package on 1020 port.

Any information? Thanks a lot in advance.

Body:
Why UDPClient.client.Availabe == 0 while the Wireshark can catch the UDP package ?  I used the UDPClient to receive UDP package from other endpoint like below:

socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
socket.Bind(new IPEndPoint(IPAddress.Any, 1020));
socket.ReceiveTimeout = 100;
_udpReceiver = new UdpClient
{
    Client = socket
};

while (!_stopReceiveEvent.WaitOne(1))
{`your text`
    if (_udpReceiver.Available <= 0)
    {
        continue;
    }

    byte[] rawBytes = _udpReceiver.Receive(ref endPoint);

    //handle the rawBytes
    //....
}

Most of time it worked normally, but occasionally the _udpReceiver.Avaiable equaled 0 while the Wireshark can catch the UDP package on 1020 port.

Any information? Thanks a lot in advance.


问:
Could not find method Android for arguments build
I've been trying to build my react native app but i keep getting this error:error, i've tried so many things but just can't seem to make it work.

This is my android build gradle:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

`android {
    compileSdkVersion 31
    defaultConfig {
        applicationId "ir.hajitsu.app"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 4
        versionName "1.0.4"
        buildToolsVersion = "31.0.3"
    }
}

buildscript {
    ext {
        buildToolsVersion = "31.0.3"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
    }
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

    buildToolsVersion = "31.0.3"

}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}`

</code>```

And this is my app build gradle:

```<code>`apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
]

apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.primeiroprojeto"
        buildToolsVersion = "31.0.3"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        versionCode 4
        versionName "1.0.4"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    implementation 'com.segment.analytics.android:analytics:latest.release'
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }
    implementation ("com.segment.analytics.android:analytics:latest.release") {
        force = true
    }
    implementation "com.segment.analytics.android:analytics:latest.release"
    DefaultDependencyHandler {
        implementation "com.segment.analytics.android:analytics:latest.release"
    }

    addUnimodulesDependencies()

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)`your text``

</code>```

I'm trying to build an apk, when i used to run expo build android it works fine, but when i try the new eas build it breaks with the following message: Could not find method android() for arguments [build_1sr3r53d9qjssx46r99sxe7o7$_run_closure1@47ede9fd] on root project 'primeiroProjeto' of type org.gradle.api.Project.

Body:
I've been trying to build my react native app but i keep getting this error:error, i've tried so many things but just can't seem to make it work.

This is my android build gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

`android {
    compileSdkVersion 31
    defaultConfig {
        applicationId "ir.hajitsu.app"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 4
        versionName "1.0.4"
        buildToolsVersion = "31.0.3"
    }
}

buildscript {
    ext {
        buildToolsVersion = "31.0.3"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
    }
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

    buildToolsVersion = "31.0.3"

}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}`

And this is my app build gradle:

`apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
]

apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-constants/scripts/get-app-config-android.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.primeiroprojeto"
        buildToolsVersion = "31.0.3"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        versionCode 4
        versionName "1.0.4"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    implementation 'com.segment.analytics.android:analytics:latest.release'
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }
    implementation ("com.segment.analytics.android:analytics:latest.release") {
        force = true
    }
    implementation "com.segment.analytics.android:analytics:latest.release"
    DefaultDependencyHandler {
        implementation "com.segment.analytics.android:analytics:latest.release"
    }

    addUnimodulesDependencies()

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)`your text``

I'm trying to build an apk, when i used to run expo build android it works fine, but when i try the new eas build it breaks with the following message: Could not find method android() for arguments [build_1sr3r53d9qjssx46r99sxe7o7$_run_closure1@47ede9fd] on root project 'primeiroProjeto' of type org.gradle.api.Project.


问:
Sort a DefaultDict by value which is a list and then by key
I'm asking for you help here because i didn't find how to do it on internet and even after trying myself.
Here is my concern:
I want to create an Order Book for a trading strategy, I created then a dictionary like this :

```<code>bids = {Price : (size, submission_time, is_market_maker)}
</code>```

When executing orders, the first priority is price, and, within a given price, the order that was sent prior to another one will have priority (sort by number, the lower being the first).
This is called the price-priority rule for order books.

I already tried this function with the '[1][1]' to sort by the value which is a list but it doesn't work maybe because I'm using a DefaultDict I don't know

```<code>sorted_dict = sorted(bids.items(), key=lambda item: item[1][1])
</code>```

And then I would like to sort it by price without changing the order of the orders.

I would like it to be like this :

```<code>bids = {100: [(5,2,True), (4,1, False)], 101: [(2,3,True), (4,1, False)]}
bids = {101: [(4, 1, False), (2 , 3, True)] , 100: [(4, 1, False), (5, 2, True)]}
</code>```

Thank you for your help !

Body:
I'm asking for you help here because i didn't find how to do it on internet and even after trying myself.
Here is my concern:
I want to create an Order Book for a trading strategy, I created then a dictionary like this :

bids = {Price : (size, submission_time, is_market_maker)}

When executing orders, the first priority is price, and, within a given price, the order that was sent prior to another one will have priority (sort by number, the lower being the first).
This is called the price-priority rule for order books.

I already tried this function with the '[1][1]' to sort by the value which is a list but it doesn't work maybe because I'm using a DefaultDict I don't know

sorted_dict = sorted(bids.items(), key=lambda item: item[1][1])

And then I would like to sort it by price without changing the order of the orders.

I would like it to be like this :

bids = {100: [(5,2,True), (4,1, False)], 101: [(2,3,True), (4,1, False)]}
bids = {101: [(4, 1, False), (2 , 3, True)] , 100: [(4, 1, False), (5, 2, True)]}

Thank you for your help !


问:
Is there any way to bind trait to class dinamically?
I have an array that has my traits:

```<code>$traits = [
  'app\traits\TraitNumOne',
  'app\traits\TraitNumTwo',
];
</code>```

is there any way to use that traits in my class dinamically?

```<code>class MyClass {
use $traits[0],$traits[1]; // something like this :)
}
</code>```

I haven't any idea to solve this, please help

Body:
I have an array that has my traits:

$traits = [
  'app\traits\TraitNumOne',
  'app\traits\TraitNumTwo',
];

is there any way to use that traits in my class dinamically?

class MyClass {
use $traits[0],$traits[1]; // something like this :)
}

I haven't any idea to solve this, please help


问:
Automatic role change for read/writes using ActiveRecord
The addition of multiple databases on Rails 6.1 is great and provides a way to have a fairly simple read from follower write on replica setup if you use the included resolver.

That works if your app is fully RESTful and there's no mutations on the database during GETs and HEADs. On paper that's great but there are some situations where alterations of the data can happen (see consuming tokens, lazy cleaning data, set flags, etc).

ActiveRecord knows when the query is a write one and raises an error if the target connection is a replica one.

I want to automatically switch between leader and follower based on that condition. PGPool2 does that but I'd like to avoid setting up another service if it were possible.

A simple solution I tried was to create a custom resolver and wrap the execution but since ActiveRecord can detect a query that modifies the data I was wondering if there's any way to switch the connection before execution.

# frozen_string_literal: true

module Middleware
  module DatabaseSelector
    class AutoSwitchResolver < ActiveRecord::Middleware::DatabaseSelector::Resolver
      def read(&block)
        super(&block)
      rescue ActiveRecord::ReadOnlyError
        write(&block)
      end
    end
  end
end

```
<p>I also tried to hook up to <code>ActiveRecord::ConnectionAdapters::PostgreSQLAdapter</code> <code>execute</code> methods as Marginalia does to try to overwrite the target without much luck.</p>
<p>EDIT:</p>
<p>I also tried and it seemed to work but it ends up failing alongside the stock Rails resolver:</p>
<pre class="lang-rb prettyprint-override"><code>class ApplicationRecord < ActiveRecord::Base
  # ...
  around_save :ensure_write_database
  around_destroy :ensure_write_database

  def touch(*args)
    ensure_write_database { super(*args) }
  end

  def ensure_write_database
    ApplicationRecord.connected_to(role: :writing) { yield }
  end

</code>```

Body:
The addition of multiple databases on Rails 6.1 is great and provides a way to have a fairly simple read from follower write on replica setup if you use the included resolver.

That works if your app is fully RESTful and there's no mutations on the database during GETs and HEADs. On paper that's great but there are some situations where alterations of the data can happen (see consuming tokens, lazy cleaning data, set flags, etc).

ActiveRecord knows when the query is a write one and raises an error if the target connection is a replica one.

I want to automatically switch between leader and follower based on that condition. PGPool2 does that but I'd like to avoid setting up another service if it were possible.

A simple solution I tried was to create a custom resolver and wrap the execution but since ActiveRecord can detect a query that modifies the data I was wondering if there's any way to switch the connection before execution.

# frozen_string_literal: true

module Middleware
  module DatabaseSelector
    class AutoSwitchResolver < ActiveRecord::Middleware::DatabaseSelector::Resolver
      def read(&block)
        super(&block)
      rescue ActiveRecord::ReadOnlyError
        write(&block)
      end
    end
  end
end

I also tried to hook up to ActiveRecord::ConnectionAdapters::PostgreSQLAdapter execute methods as Marginalia does to try to overwrite the target without much luck.

EDIT:

I also tried and it seemed to work but it ends up failing alongside the stock Rails resolver:

class ApplicationRecord < ActiveRecord::Base
  # ...
  around_save :ensure_write_database
  around_destroy :ensure_write_database

  def touch(*args)
    ensure_write_database { super(*args) }
  end

  def ensure_write_database
    ApplicationRecord.connected_to(role: :writing) { yield }
  end


问:
How to disable cron service delay on startup
I'm trying to add the execution of a shell script on server startup. I do it using cron, so I configured it with 'crontab -e' command. It looks so:

```<code>@reboot /home/user/run.sh
</code>```

Then I enabled service with

```<code>sudo systemctl enable cron.service
</code>```

But when I reboot my server, jobs are not started. I check service status with:

```<code>sudo systemctl status cron.service
</code>```

screenshot with an example

And there is a message that it's 2h 55min left to start executing all jobs. So, as I understood service is running but with 3 hours delay. It's happening after every server startup.

Using sudo systemctl restart cron.service command helps to make service working, but the server skips @reboot jobs because "it's not system startup".

Body:
I'm trying to add the execution of a shell script on server startup. I do it using cron, so I configured it with 'crontab -e' command. It looks so:

@reboot /home/user/run.sh

Then I enabled service with

sudo systemctl enable cron.service

But when I reboot my server, jobs are not started. I check service status with:

sudo systemctl status cron.service

screenshot with an example

And there is a message that it's 2h 55min left to start executing all jobs. So, as I understood service is running but with 3 hours delay. It's happening after every server startup.

Using sudo systemctl restart cron.service command helps to make service working, but the server skips @reboot jobs because "it's not system startup".


问:
measure / Track commit metrices from intial PR to artifact build
I need to measure metrics for a single commit throughout its lifecycle from commit to artifact build process and need to calculate time diffrence after commiting the code into master,raising pull request against master to successful artifact build via CI pipeline.

This will include few points as below.

Overall time taken by commit from PR to first successful build.

avg. time taken by each commit to build on CI server.

waiting/queuing time of each commit on the CI system.

How many times a commit failed before a successful merge in PR request?

How many times does the master branch run in a day ?

Total number of build in days from master as well as PR branch for each commit.

Total successful or failed build for single commit.

I am thinking of using Jenkins metrics plugin for build related metrics. But while measuring commit metrics on bitbucket I am not able to figure out what things actually we need to do. whether I need to write a custom script or any other options/ plugins/ tools/utilities to get time difference between commit I made and the same commit able to build a successful artifact


问:
How to use custom arbitrary values in HTML tags?
I saw Tailwind CSS framework use one technique. Adding Custom "Styles using-arbitrary-values" This features helps one to add any custom style with value without the hustle of inline CSS. It's really helpful. So I want to know, how do they do it ? Can I do it with just Javascript and jQuery?

This is an example of their technique:

```<code><div class="bg-[#bada55] text-[22px] before:content-['Festivus']">
  <!-- ... -->
</div>
</code>```

Here's another example of Tailwind css arbitary values thst I've copied from their documentation.

Using arbitrary values

While you can usually build the bulk of a well-crafted design using a
constrained set of design tokens, once in a while you need to break
out of those constraints to get things pixel-perfect.

When you find yourself really needing something like top: 117px to get
a background image in just the right spot, use Tailwind’s square
bracket notation to generate a class on the fly with any arbitrary
value.

For Example;

```<code><div class="top-[117px]">
  <!-- ... -->
</div>
</code>```

Body:
I saw Tailwind CSS framework use one technique. Adding Custom "Styles using-arbitrary-values" This features helps one to add any custom style with value without the hustle of inline CSS. It's really helpful. So I want to know, how do they do it ? Can I do it with just Javascript and jQuery?

This is an example of their technique:

Here's another example of Tailwind css arbitary values thst I've copied from their documentation.

Using arbitrary values

While you can usually build the bulk of a well-crafted design using a
constrained set of design tokens, once in a while you need to break
out of those constraints to get things pixel-perfect.

When you find yourself really needing something like top: 117px to get
a background image in just the right spot, use Tailwind’s square
bracket notation to generate a class on the fly with any arbitrary
value.

For Example;


问:
Make a post request to a remote PHP server containing base64 encoded data from a Fingerprint scanner capture using a Web Brouser
I currently need an assistance on how to read data from a client fingerprint scanner using the Web Browser thereafter, make a POST request to a remote PHP server where verification can be conduct.

I am thinking if this can be achieved with JavaScript or probably any API services available for this purpose does exist? Please help out with possible solutions. Thanks in anticipation.

I have tried making a POST request to m2sys API using POSTMAN to register and verify base_encode64(fingerprint image) which is actually successful, I need a way to get the fingerprint image from the client browser directly from the scanner and make a POST request to a remote server.

Any possible solution will be greatly appreciated.


问:
Highcharts offline export does not work after upgrading to highcharts 9.0.1 and highcharts-angular 3.0.0
I am using highcharts and highcharts-angular in order to create a pdf with multiple graphs, using the offline exporting.
Previous to the upgrade to highcharts 9.0.1 I have been using highcharts 8.2 and highcharts-angular 2.4 and everything worked fine. After upgrade I keep encountering this error
[]

My code looks like:

```<code>import * as Highcharts from 'highcharts';
import HC_exporting from "highcharts/modules/exporting";
import offlineExporting from "highcharts/modules/offline-exporting";
HC_exporting(Highcharts);
offlineExporting(Highcharts);
import { defaultSeriesColorsArray, defaultSpecialColorsArray, defaultSpecialColorsEnum } from '../../constants/colors.constants';
import { ChartModel, PieChartModel } from '../../models/chart.model';

export class ChartOptionsHelper {

    constructor() {
    }

    public static buildChart(options: Highcharts.Options): any {
        const chartDiv = document.createElement('div');
        const charAsSVG = Highcharts.chart(chartDiv, options).getSVG();
        return charAsSVG;
    }
}

</code>```

So far I have tried moving the calls to HC_exporting and offlineExporting before the getSVG is being called, but the error persisted. The only way I managed to get rid of the error is by removing those 2 calls.

Is there a workaround or a fix for this issue? I have not seen any information about these methods being deprecated

Body:
I am using highcharts and highcharts-angular in order to create a pdf with multiple graphs, using the offline exporting.
Previous to the upgrade to highcharts 9.0.1 I have been using highcharts 8.2 and highcharts-angular 2.4 and everything worked fine. After upgrade I keep encountering this error
[]

My code looks like:

import * as Highcharts from 'highcharts';
import HC_exporting from "highcharts/modules/exporting";
import offlineExporting from "highcharts/modules/offline-exporting";
HC_exporting(Highcharts);
offlineExporting(Highcharts);
import { defaultSeriesColorsArray, defaultSpecialColorsArray, defaultSpecialColorsEnum } from '../../constants/colors.constants';
import { ChartModel, PieChartModel } from '../../models/chart.model';

export class ChartOptionsHelper {

    constructor() {
    }

    public static buildChart(options: Highcharts.Options): any {
        const chartDiv = document.createElement('div');
        const charAsSVG = Highcharts.chart(chartDiv, options).getSVG();
        return charAsSVG;
    }
}

So far I have tried moving the calls to HC_exporting and offlineExporting before the getSVG is being called, but the error persisted. The only way I managed to get rid of the error is by removing those 2 calls.

Is there a workaround or a fix for this issue? I have not seen any information about these methods being deprecated


问:
PowerBI, DAX - multiply DISTINCTCOUNT of repaired products over value of those products from another related table
I have two separate tables that are used to calculate total savings of repaired products.

Table_A is a result of my SQL Server query and contains information about all repairs performed on specific products:

Timestamp
Product_serialnumber
Product_name
Repair_reference
Repair_description

2022-10-02 11:52:36.330
Serial_A
Product_A
J1
Damaged

2022-10-02 11:52:37.343
Serial_A
Product_A
J3
Damaged

2022-10-02 11:52:37.720
Serial_A
Product_A
P5
Bent

2022-10-20 03:02:11.713
Serial_B
Product_A
J8
Dirty

2022-10-20 03:03:45.570
Serial_C
Product_B
P40
Damaged

2022-10-20 23:49:54.837
Serial_D
Product_C
P8
Dirty

2022-11-12 08:26:11.270
Serial_E
Product_A
J50
Bent

One Product_serialnumber can be repaired many times.

Table_B is very simple and created manually - it contains information how much each unit of specific product is worth.

Product_name
Value

Product_A
250

Product_B
250

Product_C
175

Both tables are joined with many to one cardinality with single cross filter direction running from Table_B to Table_A.

My task was to create visual to show how many Product_serialnumber s were repaired and how much we saved by repairing them. It is very important to perform DISTINCTCOUNT of Product_serialnumber , not COUNT of all repairs performed on them as 3 repairs on 1 Product_serialnumber worth 250 is still 250 saved, not 750.

In PowerBI I have one table with summary. To calculate savings I created following DAX measure in Table_A:

```<code>Measure = DISTINCTCOUNT('Table_A'[Product_serialnumber]) * MAX(Table_B[Value])
</code>```

It gave me results below:

Product_name
Distinct count of Product_serialnumber
Value
Savings

Product_A
3
250
750

Product_B
10
250
2500

Product_C
25
175
4375

Total
38

9500

Each row has correct Savings value but Total is wrong. Instead of 9500, there should be 7625.

I figured out that MAX(Table_B[Value]) in my DAX Measure simulates 38*250. When I changed that to MIN, it was 38*175. So still wrong

To correct that, what I eventually did was I created New Column in Table_A:

```<code>RELATED_Value_from_table_b = RELATED(Table_B[Value])
</code>```

Now each row in Table_A has correct Value based on Product_name.

Only then I created this measure in Table_A:

```<code>Saved = SUMX(
    DISTINCT('Table_A'[Product_serialnumber]),
        CALCULATE(MAX('Table_A'[RELATED_Value_from_table_b])))
</code>```

So I got following result:

Product_name
Distinct count of Product_serialnumber
Value
Savings

Product_A
3
250
750

Product_B
10
250
2500

Product_C
25
175
4375

Total
38

7625

Total is finally correct.

Of course I found the solution to the task but I am not happy of how I did it and I believe there is more optimized way of doing it. I want to know it to be better in the future.

Body:
I have two separate tables that are used to calculate total savings of repaired products.

Table_A is a result of my SQL Server query and contains information about all repairs performed on specific products:

Timestamp
Product_serialnumber
Product_name
Repair_reference
Repair_description

2022-10-02 11:52:36.330
Serial_A
Product_A
J1
Damaged

2022-10-02 11:52:37.343
Serial_A
Product_A
J3
Damaged

2022-10-02 11:52:37.720
Serial_A
Product_A
P5
Bent

2022-10-20 03:02:11.713
Serial_B
Product_A
J8
Dirty

2022-10-20 03:03:45.570
Serial_C
Product_B
P40
Damaged

2022-10-20 23:49:54.837
Serial_D
Product_C
P8
Dirty

2022-11-12 08:26:11.270
Serial_E
Product_A
J50
Bent

One Product_serialnumber can be repaired many times.

Table_B is very simple and created manually - it contains information how much each unit of specific product is worth.

Product_name
Value

Product_A
250

Product_B
250

Product_C
175

Both tables are joined with many to one cardinality with single cross filter direction running from Table_B to Table_A.

My task was to create visual to show how many Product_serialnumber s were repaired and how much we saved by repairing them. It is very important to perform DISTINCTCOUNT of Product_serialnumber , not COUNT of all repairs performed on them as 3 repairs on 1 Product_serialnumber worth 250 is still 250 saved, not 750.

In PowerBI I have one table with summary. To calculate savings I created following DAX measure in Table_A:

Measure = DISTINCTCOUNT('Table_A'[Product_serialnumber]) * MAX(Table_B[Value])

It gave me results below:

Product_name
Distinct count of Product_serialnumber
Value
Savings

Product_A
3
250
750

Product_B
10
250
2500

Product_C
25
175
4375

Total
38

9500

Each row has correct Savings value but Total is wrong. Instead of 9500, there should be 7625.

I figured out that MAX(Table_B[Value]) in my DAX Measure simulates 38*250. When I changed that to MIN, it was 38*175. So still wrong

To correct that, what I eventually did was I created New Column in Table_A:

RELATED_Value_from_table_b = RELATED(Table_B[Value])

Now each row in Table_A has correct Value based on Product_name.

Only then I created this measure in Table_A:

Saved = SUMX(
    DISTINCT('Table_A'[Product_serialnumber]),
        CALCULATE(MAX('Table_A'[RELATED_Value_from_table_b])))

So I got following result:

Product_name
Distinct count of Product_serialnumber
Value
Savings

Product_A
3
250
750

Product_B
10
250
2500

Product_C
25
175
4375

Total
38

7625

Total is finally correct.

Of course I found the solution to the task but I am not happy of how I did it and I believe there is more optimized way of doing it. I want to know it to be better in the future.


问:
Is there a way, I can get all groups from Meetup API without specifying query value in keywordSearch ? or using a regex
Can I get all groups without specifying keyword or giving some regex to the Meetup Graph QL API ?
My objective is to get all groups for a particular lat, lon and radius. Here is my query:

{
    keywordSearch(
        filter: {
            query: "/[a-zA-Z]/",
            lat: -35.2809368,
            lon: 149.1300092,
            radius: 62,
            source: GROUPS
        }
        input: {
            first: 200
        }
    ) {
    count
    pageInfo {
        endCursor
        hasNextPage
    }
    edges {
        node {
            id
            result {
                ... on Group {
                    id
                    name
                    urlname
                    country
                    description
                    topicCategory {
                        id
                        name
                    }
                }
            }
        }
    }
}
```

I tried regex but it did not work.

Body:
Can I get all groups without specifying keyword or giving some regex to the Meetup Graph QL API ?
My objective is to get all groups for a particular lat, lon and radius. Here is my query:

{
    keywordSearch(
        filter: {
            query: "/[a-zA-Z]/",
            lat: -35.2809368,
            lon: 149.1300092,
            radius: 62,
            source: GROUPS
        }
        input: {
            first: 200
        }
    ) {
    count
    pageInfo {
        endCursor
        hasNextPage
    }
    edges {
        node {
            id
            result {
                ... on Group {
                    id
                    name
                    urlname
                    country
                    description
                    topicCategory {
                        id
                        name
                    }
                }
            }
        }
    }
}

I tried regex but it did not work.


问:
Adding new fields conditioned and calculate the length using Python QGIS
I am developing a new plugin using python in qgis. I want to get an output with the result of a specific attribute table from another layer already existing in my project => layer "SUPPORT".

That's what I've done so far

my code :

`

```<code>tableSUPPORT = QgsVectorLayer('None', 'table_SUPPORT', 'memory')
tableSUPPORT.dataProvider().addAttributes(
    [QgsField("Propriétaire", QVariant.String), QgsField("Nb. tronçons", QVariant.Int),
     QgsField("Long. (m)", QVariant.Int)])
tableSUPPORT.updateFields()

dicoSUPPORT = {'FT': (0, 0), 'FREE MOBILE': (0, 0), 'PRIVE': (0, 0)}

for sup in coucheSUPPORT.getFeatures():
    proprietaire = sup['PROPRIETAI']
    if proprietaire in ['FT', 'FREE MOBILE', 'PRIVE']:
        dicoSUPPORT[proprietaire] = tuple(map(operator.add, (1, sup['LGR_REEL']), dicoSUPPORT[proprietaire]))
    else:
        QMessageBox.critical(None, "Problème de support",
                             "Le support %s possède un propriétaire qui ne fait pas partie de la liste." % str(sup['LIBELLE']))
        return None
ligneFT = QgsFeature()
ligneFT.setAttributes(['FT', int(dicoSUPPORT['FT'][0]), int(dicoSUPPORT['FT'][1])])
ligneFREE = QgsFeature()
ligneFREE.setAttributes(['FREE MOBILE', int(dicoSUPPORT['FREE MOBILE'][0]), int(dicoSUPPORT['FREE MOBILE'][1])])
lignePRIVE = QgsFeature()
lignePRIVE.setAttributes(['PRIVE', int(dicoSUPPORT['PRIVE'][0]), int(dicoSUPPORT['PRIVE'][1])])

tableSUPPORT.dataProvider().addFeatures([ligneFT])
tableSUPPORT.dataProvider().addFeatures([ligneFREE])
tableSUPPORT.dataProvider().addFeatures([lignePRIVE])

QgsProject.instance().addMapLayer(tableSUPPORT)
</code>```

`

and here is the result obtained with this code :
result

but in fact I want this table with these specific rows and columns:
table

This is my support attribute table :
support attribute table

description of each row I want in the result:
`

```<code>> row 1 =>FT_SOUT:sum of the length ('LGR_REEL') and count the number if ('PROPRIETAI'='FT' and
> 'TYPE_STRUC'='TRANCHEE')
>
> row 2 =>FT_AERIEN:sum of the length('LGR_REEL') if ('PROPRIETAI'='FT' and
> 'TYPE_STRUC'='AERIEN')
>
> row 3 =>CREATION GC FREE RESEAU:sum of length('LGR_REEL') If
> ('PROPRIETAI'='FREE MOBILE' and 'TYPE_STRUC'='TRANCHEE')
>
> row 4 =>CREATION AERIEN FREE RESEAU:sum of the length ('LGR_REEL') If
> ('PROPRIETAI'='FREE MOBILE' and 'TYPE_STRUC'='AERIEN')
>
> row 5 =>PRIVE :sum of the length ('LGR_REEL') If
> ('PROPRIETAI'='PRIVE')
</code>```

`
i have been asking this at stackexchang but no one answers me
this is my question
https://gis.stackexchange.com/questions/448698/adding-new-fields-conditioned-and-calculate-the-length-using-python-qgis

Body:
I am developing a new plugin using python in qgis. I want to get an output with the result of a specific attribute table from another layer already existing in my project => layer "SUPPORT".

That's what I've done so far

my code :

`

tableSUPPORT = QgsVectorLayer('None', 'table_SUPPORT', 'memory')
tableSUPPORT.dataProvider().addAttributes(
    [QgsField("Propriétaire", QVariant.String), QgsField("Nb. tronçons", QVariant.Int),
     QgsField("Long. (m)", QVariant.Int)])
tableSUPPORT.updateFields()

dicoSUPPORT = {'FT': (0, 0), 'FREE MOBILE': (0, 0), 'PRIVE': (0, 0)}

for sup in coucheSUPPORT.getFeatures():
    proprietaire = sup['PROPRIETAI']
    if proprietaire in ['FT', 'FREE MOBILE', 'PRIVE']:
        dicoSUPPORT[proprietaire] = tuple(map(operator.add, (1, sup['LGR_REEL']), dicoSUPPORT[proprietaire]))
    else:
        QMessageBox.critical(None, "Problème de support",
                             "Le support %s possède un propriétaire qui ne fait pas partie de la liste." % str(sup['LIBELLE']))
        return None
ligneFT = QgsFeature()
ligneFT.setAttributes(['FT', int(dicoSUPPORT['FT'][0]), int(dicoSUPPORT['FT'][1])])
ligneFREE = QgsFeature()
ligneFREE.setAttributes(['FREE MOBILE', int(dicoSUPPORT['FREE MOBILE'][0]), int(dicoSUPPORT['FREE MOBILE'][1])])
lignePRIVE = QgsFeature()
lignePRIVE.setAttributes(['PRIVE', int(dicoSUPPORT['PRIVE'][0]), int(dicoSUPPORT['PRIVE'][1])])

tableSUPPORT.dataProvider().addFeatures([ligneFT])
tableSUPPORT.dataProvider().addFeatures([ligneFREE])
tableSUPPORT.dataProvider().addFeatures([lignePRIVE])

QgsProject.instance().addMapLayer(tableSUPPORT)

`

and here is the result obtained with this code :
result

but in fact I want this table with these specific rows and columns:
table

This is my support attribute table :
support attribute table

description of each row I want in the result:
`

> row 1 =>FT_SOUT:sum of the length ('LGR_REEL') and count the number if ('PROPRIETAI'='FT' and
> 'TYPE_STRUC'='TRANCHEE')
>
> row 2 =>FT_AERIEN:sum of the length('LGR_REEL') if ('PROPRIETAI'='FT' and
> 'TYPE_STRUC'='AERIEN')
>
> row 3 =>CREATION GC FREE RESEAU:sum of length('LGR_REEL') If
> ('PROPRIETAI'='FREE MOBILE' and 'TYPE_STRUC'='TRANCHEE')
>
> row 4 =>CREATION AERIEN FREE RESEAU:sum of the length ('LGR_REEL') If
> ('PROPRIETAI'='FREE MOBILE' and 'TYPE_STRUC'='AERIEN')
>
> row 5 =>PRIVE :sum of the length ('LGR_REEL') If
> ('PROPRIETAI'='PRIVE')

`
i have been asking this at stackexchang but no one answers me
this is my question
https://gis.stackexchange.com/questions/448698/adding-new-fields-conditioned-and-calculate-the-length-using-python-qgis


问:
Decrypted string not equivalent to another string with the same value?
I'm working on Login project in flutter encryption and decryption works just like how I expected to be, this is how I decrypted the user password:

```<code>      final key = encrypterQERT.Key.fromUtf8('key');
      final iv = encrypterQERT.IV.fromUtf8('key');

      final encrypter = encrypterQERT.Encrypter(encrypterQERT.AES(key, mode: encrypterQERT.AESMode.cbc, padding: null));
      final decrypted = encrypter.decrypt64(_passValues.elementAt(0), iv: iv);
</code>```

How it was encrypted:

```<code>    final _getKey = encrypter.Key.fromUtf8(key);
    final encryptServ = encrypter.Encrypter(encrypter.AES(_getKey, mode: encrypter.AESMode.cbc));
    final InitVect = encrypter.IV.fromUtf8(key.substring(0,16));

    encrypter.Encrypted _encryptDat = encryptServ.encrypt(Value,iv: InitVect);
   return _encryptDat;
</code>```

Now I tried to determine if the user input is equivalent to the decrypted password:

```<code>     List<dynamic> _passValues = <dynamic>[];
      for(final _userPass in _getPass.rows) {
        dynamic _getFirst = _userPass.assoc().values.elementAt(0);
        print(_getFirst);
        _passValues.add(_getFirst);
      }

      final key = encrypterQERT.Key.fromUtf8('key');
      final iv = encrypterQERT.IV.fromUtf8('key');

      final encrypter = encrypterQERT.Encrypter(encrypterQERT.AES(key, mode: encrypterQERT.AESMode.cbc, padding: null));
      final decrypted = encrypter.decrypt64(_passValues.elementAt(0), iv: iv);
      print(_userPasswordInput);
      print(decrypted);

      if(decrypted == _userPasswordinput) {
        print("Passed");
      } else {
        print("Failed");
      }
</code>```

And the output were:

mypass mypass Failed

Why does this happens?

What I were expecting:

mypass mypass Passed

Body:
I'm working on Login project in flutter encryption and decryption works just like how I expected to be, this is how I decrypted the user password:

      final key = encrypterQERT.Key.fromUtf8('key');
      final iv = encrypterQERT.IV.fromUtf8('key');

      final encrypter = encrypterQERT.Encrypter(encrypterQERT.AES(key, mode: encrypterQERT.AESMode.cbc, padding: null));
      final decrypted = encrypter.decrypt64(_passValues.elementAt(0), iv: iv);

How it was encrypted:

    final _getKey = encrypter.Key.fromUtf8(key);
    final encryptServ = encrypter.Encrypter(encrypter.AES(_getKey, mode: encrypter.AESMode.cbc));
    final InitVect = encrypter.IV.fromUtf8(key.substring(0,16));

    encrypter.Encrypted _encryptDat = encryptServ.encrypt(Value,iv: InitVect);
   return _encryptDat;

Now I tried to determine if the user input is equivalent to the decrypted password:

     List<dynamic> _passValues = <dynamic>[];
      for(final _userPass in _getPass.rows) {
        dynamic _getFirst = _userPass.assoc().values.elementAt(0);
        print(_getFirst);
        _passValues.add(_getFirst);
      }

      final key = encrypterQERT.Key.fromUtf8('key');
      final iv = encrypterQERT.IV.fromUtf8('key');

      final encrypter = encrypterQERT.Encrypter(encrypterQERT.AES(key, mode: encrypterQERT.AESMode.cbc, padding: null));
      final decrypted = encrypter.decrypt64(_passValues.elementAt(0), iv: iv);
      print(_userPasswordInput);
      print(decrypted);

      if(decrypted == _userPasswordinput) {
        print("Passed");
      } else {
        print("Failed");
      }

And the output were:

mypass mypass Failed

Why does this happens?

What I were expecting:

mypass mypass Passed


问:
react-intl - Custom date formatter
I would like to specify the date format based on what the user has selected.

When defining the Intl object I can specify the values I would like to include for a date but I can't specify the ordering or exactly how I would like the date formatted.

E.g.

```<code>const intl = createIntl({
    locale: 'en',
    messages: messages,
    timeZone: "MST",
    formats: {
        date: {
            custom: {
                day: "2-digit",
                month: "2-digit",
                year: "2-digit",
            }
        }
    }
}, cache)
</code>```

This formats a date as 01/03/23 (mm/dd/yy).

I would like to format the date based on what the user has selected. Possibly using a library like date-fns.

E.g.

```<code>dd/mm/yyyy
mm/dd/yyyy
yyyy/dd/mm
...
</code>```

How can I format dates based on a date format?

Title: react-intl - Custom date formatter

Body:
I would like to specify the date format based on what the user has selected.

When defining the Intl object I can specify the values I would like to include for a date but I can't specify the ordering or exactly how I would like the date formatted.

E.g.

const intl = createIntl({
    locale: 'en',
    messages: messages,
    timeZone: "MST",
    formats: {
        date: {
            custom: {
                day: "2-digit",
                month: "2-digit",
                year: "2-digit",
            }
        }
    }
}, cache)

This formats a date as 01/03/23 (mm/dd/yy).

I would like to format the date based on what the user has selected. Possibly using a library like date-fns.

E.g.

dd/mm/yyyy
mm/dd/yyyy
yyyy/dd/mm
...

How can I format dates based on a date format?


问:
How to see details about errors after running DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS
I'm adding partitions to an existing table in an Oracle database by creating an intermediary table and then using DBMS_REDEFINITION api to copy dependents from the original table.

```<code>CREATE TABLE my_schema.interm_tb AS SELECT * FROM my_schema.original_tb WHERE 1 = 0;

-- add partitions on my_schema.interm_tb
</code>```

When running the script bellow I am getting num_errors > 0. However, select object_name, base_table_name, ddl_txt from DBA_REDEFINITION_ERRORS; doesn't find any error details. How can I see the error details? I am running as SYS user if it matters.

```<code>DECLARE
         num_errors PLS_INTEGER;
BEGIN
  DBMS_REDEFINITION.start_redef_table('my_schema', 'original_tb', 'interm_tb');
  DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS('my_schema', 'original_tb', 'interm_tb',
                                                        DBMS_REDEFINITION.CONS_ORIG_PARAMS, TRUE, TRUE, TRUE, TRUE,
                                                        num_errors);
  DBMS_OUTPUT.put_line('num_errors=' || num_errors);
END;
</code>```

Edit 1:
With ignore_errors set to false I get:

```<code>DECLARE
*
ERROR at line 1:
ORA-01442: column to be modified to NOT NULL is already NOT NULL
ORA-06512: at "SYS.DBMS_REDEFINITION", line 2304
</code>```

So I tried to get all not null constraints on the intermediary table and drop them by adding this block before calling DBMS_REDEFINITION.start_redef_table - this fixed the errors:

```<code>FOR q IN (
                    select 'alter table "' || owner || '"."' || table_name || '" DROP CONSTRAINT "' || CONSTRAINT_NAME || '"' as sql_text
                    from dba_constraints where table_name='interm_tb'
                    )
                    LOOP
                        DBMS_OUTPUT.put_line(q.sql_text);
                        EXECUTE IMMEDIATE q.sql_text;
                END LOOP;
</code>```

Body:
I'm adding partitions to an existing table in an Oracle database by creating an intermediary table and then using DBMS_REDEFINITION api to copy dependents from the original table.

CREATE TABLE my_schema.interm_tb AS SELECT * FROM my_schema.original_tb WHERE 1 = 0;

-- add partitions on my_schema.interm_tb

When running the script bellow I am getting num_errors > 0. However, select object_name, base_table_name, ddl_txt from DBA_REDEFINITION_ERRORS; doesn't find any error details. How can I see the error details? I am running as SYS user if it matters.

DECLARE
         num_errors PLS_INTEGER;
BEGIN
  DBMS_REDEFINITION.start_redef_table('my_schema', 'original_tb', 'interm_tb');
  DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS('my_schema', 'original_tb', 'interm_tb',
                                                        DBMS_REDEFINITION.CONS_ORIG_PARAMS, TRUE, TRUE, TRUE, TRUE,
                                                        num_errors);
  DBMS_OUTPUT.put_line('num_errors=' || num_errors);
END;

Edit 1:
With ignore_errors set to false I get:

DECLARE
*
ERROR at line 1:
ORA-01442: column to be modified to NOT NULL is already NOT NULL
ORA-06512: at "SYS.DBMS_REDEFINITION", line 2304

So I tried to get all not null constraints on the intermediary table and drop them by adding this block before calling DBMS_REDEFINITION.start_redef_table - this fixed the errors:

FOR q IN (
                    select 'alter table "' || owner || '"."' || table_name || '" DROP CONSTRAINT "' || CONSTRAINT_NAME || '"' as sql_text
                    from dba_constraints where table_name='interm_tb'
                    )
                    LOOP
                        DBMS_OUTPUT.put_line(q.sql_text);
                        EXECUTE IMMEDIATE q.sql_text;
                END LOOP;


问:
TypeError: memoryview: a bytes-like object is required, not 'str'
Device: Macbook M1 Pro(arm64)
Note:I am using zsh. I looked through previously provided solution to the related problem but still got the same error.
I tried to use installer from miniconda pkg installer for apple silicion M1 64 bit and still got the same error.

I first installed miniforge with

homebrew install --cask miniforge
I then tired to initialize it.
I first tiried,
conda init -dvv zsh
and,
conda init -vv zsh
and got the same old error.

```<code>lucifer@Manojs-MacBook-Pro ~ % conda init -vv zsh
DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2
DEBUG conda.gateways.subprocess:subprocess_call(78): executing>> /opt/homebrew/Caskroom/miniforge/base/bin/python --version

/Users/lucifer/.zshrc
---

+++

@@ -1,2 +1,18 @@

 echo "alias blender=/Applications/Blender.app/Contents/MacOS/blender"
+
+# >>> conda initialize >>>
+# !! Contents within this block are managed by 'conda init' !!
+__conda_setup="$('/opt/homebrew/Caskroom/miniforge/base/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
+if [ $? -eq 0 ]; then
+    eval "$__conda_setup"
+else
+    if [ -f "/opt/homebrew/Caskroom/miniforge/base/etc/profile.d/conda.sh" ]; then
+        . "/opt/homebrew/Caskroom/miniforge/base/etc/profile.d/conda.sh"
+    else
+        export PATH="/opt/homebrew/Caskroom/miniforge/base/bin:$PATH"
+    fi
+fi
+unset __conda_setup
+# <<< conda initialize <<<
+
INFO conda.core.initialize:run_plan(640): init_sh_user: PermissionError(13, 'Permission denied')
Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 638, in run_plan
    result = globals()[step['function']](*step.get('args', ()), **step.get('kwargs', {}))
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 1331, in init_sh_user
    with open(user_rc_path, 'w') as fh:
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/common/compat.py", line 69, in open
    return io_open(file, str(mode), buffering=buffering,
PermissionError: [Errno 13] Permission denied: '/Users/lucifer/.zshrc'
DEBUG conda.gateways.subprocess:subprocess_call(78): executing>> sudo /opt/homebrew/Caskroom/miniforge/base/bin/python -m conda.core.initialize
Password:DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

    Traceback (most recent call last):
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/exceptions.py", line 1129, in __call__
        return func(*args, **kwargs)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/main.py", line 86, in main_subshell
        exit_code = do_call(args, p)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/conda_argparse.py", line 93, in do_call
        return getattr(module, func_name)(args, parser)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/main_init.py", line 50, in execute
        return initialize(context.conda_prefix, selected_shells, for_user, args.system,
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 119, in initialize
        run_plan_elevated(plan2)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 688, in run_plan_elevated
        result = subprocess_call(
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/gateways/subprocess.py", line 100, in subprocess_call
        stdout, stderr = process.communicate(input=stdin)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/subprocess.py", line 1152, in communicate
        stdout, stderr = self._communicate(input, endtime, timeout)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/subprocess.py", line 1983, in _communicate
        input_view = memoryview(self._input)
    TypeError: memoryview: a bytes-like object is required, not 'str'

`$ /opt/homebrew/bin/conda init -vv zsh`

  environment variables:
                 CIO_TEST=<not set>
               CONDA_ROOT=/opt/homebrew/Caskroom/miniforge/base
           CURL_CA_BUNDLE=<not set>
                 INFOPATH=/opt/homebrew/share/info:
                  MANPATH=/opt/homebrew/share/man::
                     PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr
                          /sbin:/sbin:/Library/Apple/usr/bin
       REQUESTS_CA_BUNDLE=<not set>
            SSL_CERT_FILE=<not set>

     active environment : None
       user config file : /Users/lucifer/.condarc
 populated config files : /opt/homebrew/Caskroom/miniforge/base/.condarc
          conda version : 22.9.0
    conda-build version : not installed
         python version : 3.10.6.final.0
       virtual packages : __osx=11.6=0
                          __unix=0=0
                          __archspec=1=arm64
       base environment : /opt/homebrew/Caskroom/miniforge/base  (writable)
      conda av data dir : /opt/homebrew/Caskroom/miniforge/base/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
                          https://conda.anaconda.org/conda-forge/noarch
          package cache : /opt/homebrew/Caskroom/miniforge/base/pkgs
                          /Users/lucifer/.conda/pkgs
       envs directories : /opt/homebrew/Caskroom/miniforge/base/envs
                          /Users/lucifer/.conda/envs
               platform : osx-arm64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.10.6 Darwin/20.6.0 OSX/11.6
                UID:GID : 501:20
             netrc file : None
           offline mode : False

An unexpected error has occurred. Conda has prepared the above report.

If submitted, this report will be used by core maintainers to improve
future releases of conda.
Would you like conda to send this report to the core maintainers? [y/N]: DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2

No report sent. To permanently opt-out, use

    $ conda config --set report_errors false
</code>```

Body:
Device: Macbook M1 Pro(arm64)
Note:I am using zsh. I looked through previously provided solution to the related problem but still got the same error.
I tried to use installer from miniconda pkg installer for apple silicion M1 64 bit and still got the same error.

I first installed miniforge with

homebrew install --cask miniforge
I then tired to initialize it.
I first tiried,
conda init -dvv zsh
and,
conda init -vv zsh
and got the same old error.

lucifer@Manojs-MacBook-Pro ~ % conda init -vv zsh
DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2
DEBUG conda.gateways.subprocess:subprocess_call(78): executing>> /opt/homebrew/Caskroom/miniforge/base/bin/python --version

/Users/lucifer/.zshrc
---

+++

@@ -1,2 +1,18 @@

 echo "alias blender=/Applications/Blender.app/Contents/MacOS/blender"
+
+# >>> conda initialize >>>
+# !! Contents within this block are managed by 'conda init' !!
+__conda_setup="$('/opt/homebrew/Caskroom/miniforge/base/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
+if [ $? -eq 0 ]; then
+    eval "$__conda_setup"
+else
+    if [ -f "/opt/homebrew/Caskroom/miniforge/base/etc/profile.d/conda.sh" ]; then
+        . "/opt/homebrew/Caskroom/miniforge/base/etc/profile.d/conda.sh"
+    else
+        export PATH="/opt/homebrew/Caskroom/miniforge/base/bin:$PATH"
+    fi
+fi
+unset __conda_setup
+# <<< conda initialize <<<
+
INFO conda.core.initialize:run_plan(640): init_sh_user: PermissionError(13, 'Permission denied')
Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 638, in run_plan
    result = globals()[step['function']](*step.get('args', ()), **step.get('kwargs', {}))
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 1331, in init_sh_user
    with open(user_rc_path, 'w') as fh:
  File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/common/compat.py", line 69, in open
    return io_open(file, str(mode), buffering=buffering,
PermissionError: [Errno 13] Permission denied: '/Users/lucifer/.zshrc'
DEBUG conda.gateways.subprocess:subprocess_call(78): executing>> sudo /opt/homebrew/Caskroom/miniforge/base/bin/python -m conda.core.initialize
Password:DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

    Traceback (most recent call last):
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/exceptions.py", line 1129, in __call__
        return func(*args, **kwargs)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/main.py", line 86, in main_subshell
        exit_code = do_call(args, p)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/conda_argparse.py", line 93, in do_call
        return getattr(module, func_name)(args, parser)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/cli/main_init.py", line 50, in execute
        return initialize(context.conda_prefix, selected_shells, for_user, args.system,
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 119, in initialize
        run_plan_elevated(plan2)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/core/initialize.py", line 688, in run_plan_elevated
        result = subprocess_call(
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/site-packages/conda/gateways/subprocess.py", line 100, in subprocess_call
        stdout, stderr = process.communicate(input=stdin)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/subprocess.py", line 1152, in communicate
        stdout, stderr = self._communicate(input, endtime, timeout)
      File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.10/subprocess.py", line 1983, in _communicate
        input_view = memoryview(self._input)
    TypeError: memoryview: a bytes-like object is required, not 'str'

`$ /opt/homebrew/bin/conda init -vv zsh`

  environment variables:
                 CIO_TEST=<not set>
               CONDA_ROOT=/opt/homebrew/Caskroom/miniforge/base
           CURL_CA_BUNDLE=<not set>
                 INFOPATH=/opt/homebrew/share/info:
                  MANPATH=/opt/homebrew/share/man::
                     PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr
                          /sbin:/sbin:/Library/Apple/usr/bin
       REQUESTS_CA_BUNDLE=<not set>
            SSL_CERT_FILE=<not set>

     active environment : None
       user config file : /Users/lucifer/.condarc
 populated config files : /opt/homebrew/Caskroom/miniforge/base/.condarc
          conda version : 22.9.0
    conda-build version : not installed
         python version : 3.10.6.final.0
       virtual packages : __osx=11.6=0
                          __unix=0=0
                          __archspec=1=arm64
       base environment : /opt/homebrew/Caskroom/miniforge/base  (writable)
      conda av data dir : /opt/homebrew/Caskroom/miniforge/base/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
                          https://conda.anaconda.org/conda-forge/noarch
          package cache : /opt/homebrew/Caskroom/miniforge/base/pkgs
                          /Users/lucifer/.conda/pkgs
       envs directories : /opt/homebrew/Caskroom/miniforge/base/envs
                          /Users/lucifer/.conda/envs
               platform : osx-arm64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.10.6 Darwin/20.6.0 OSX/11.6
                UID:GID : 501:20
             netrc file : None
           offline mode : False

An unexpected error has occurred. Conda has prepared the above report.

If submitted, this report will be used by core maintainers to improve
future releases of conda.
Would you like conda to send this report to the core maintainers? [y/N]: DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 2

No report sent. To permanently opt-out, use

    $ conda config --set report_errors false


问:
How to resolve Security code scan SCS0016 in API controller
We have implemented weather API controller to update weather data and inherited ControllerBase in API controller with APIController action filter like below and enabled security code scan.

```<code>using Microsoft.AspNetCore.Mvc;

namespace SampleApiApplication.Controllers
{
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {

        [HttpPost]
        [Route("UpdateWeatherDetails")]
        public IEnumerable<WeatherForecast> PostWeatherDetails(WeatherForecast weatherForecast)
        {
            // Some lines of code to implement
        }
    }
}
</code>```

I can be able to post Json content data, but I Could not able to post data with content type as application/x-www-form-urlencoded in UpdateWeatherDetails API.

To resolve the above issue, I have used [FromForm] attribute to post form data like below, now I am able to post form data and Json data. But I have faced security warning SCS0016.

```<code>using Microsoft.AspNetCore.Mvc;

namespace SampleApiApplication.Controllers
{
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpPost]
        [Route("UpdateWeatherDetails")]
        [Consumes("application/json")]
        public IEnumerable<WeatherForecast> PostWeather([FromBody] WeatherForecast weatherForecast)
        {
            return PostMethod(weatherForecast);
        }

        [HttpPost]
        [Route("UpdateWeatherDetails")]
        public IEnumerable<WeatherForecast> PostWeatherDetails([FromForm] WeatherForecast weatherForecast)
        {
            // Some lines of code to implement
        }
    }
}
</code>```

I thought after adding FromForm attribute only facing security warning and removed it, now no security warning, but I am unable get data binding to parameter. Now,  I have removed [ApiController] attribute and tried to post form data, Now I am able to post form data.

But I am again getting Security warning** SCS0016 **for that method.

How to resolve the above Security issue and get data send with application/x-www-form-urlencoded working?

Body:
We have implemented weather API controller to update weather data and inherited ControllerBase in API controller with APIController action filter like below and enabled security code scan.

using Microsoft.AspNetCore.Mvc;

namespace SampleApiApplication.Controllers
{
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {

        [HttpPost]
        [Route("UpdateWeatherDetails")]
        public IEnumerable<WeatherForecast> PostWeatherDetails(WeatherForecast weatherForecast)
        {
            // Some lines of code to implement
        }
    }
}

I can be able to post Json content data, but I Could not able to post data with content type as application/x-www-form-urlencoded in UpdateWeatherDetails API.

To resolve the above issue, I have used [FromForm] attribute to post form data like below, now I am able to post form data and Json data. But I have faced security warning SCS0016.

using Microsoft.AspNetCore.Mvc;

namespace SampleApiApplication.Controllers
{
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpPost]
        [Route("UpdateWeatherDetails")]
        [Consumes("application/json")]
        public IEnumerable<WeatherForecast> PostWeather([FromBody] WeatherForecast weatherForecast)
        {
            return PostMethod(weatherForecast);
        }

        [HttpPost]
        [Route("UpdateWeatherDetails")]
        public IEnumerable<WeatherForecast> PostWeatherDetails([FromForm] WeatherForecast weatherForecast)
        {
            // Some lines of code to implement
        }
    }
}

I thought after adding FromForm attribute only facing security warning and removed it, now no security warning, but I am unable get data binding to parameter. Now,  I have removed [ApiController] attribute and tried to post form data, Now I am able to post form data.

But I am again getting Security warning** SCS0016 **for that method.

How to resolve the above Security issue and get data send with application/x-www-form-urlencoded working?