问:
How to import a package when composite flag is enabled?
I'm trying to setup a pnpm monorepository that contains multiple typescript packages.

I reference packages using the pnpm's workspace alias and import then using its name.

Packages can be either reusable code (pure typescript or react library) or react application.

Because the shared packages does not need to be published (only goal is to reuse code across applicaiton), I have no bundler or similar. Build is performed by tsc.

Everything work as expected unless I enable the composite flag.

To illustrate, I've created a reproductible repository

Basically, I've a @tsmonorepo/common package that export a simple module:

const add = (a: number, b: number) => a + b;
const subtract = (a: number, b: number) => a - b;
const multiply = (a: number, b: number) => a * b;
const divide = (a: number, b: number) => a / b;

export { add, subtract, multiply, divide };

```
<p>And I consume it from another package <code>@tsmonorepo/react-common</code></p>
<pre class="lang-js prettyprint-override"><code>import { add } from '@tsmonorepo/common';
import * as React from 'react';

const Calc: React.FC = () => {
    const [first, setFirst] = React.useState(0);
    const [second, setSecond] = React.useState(0);

    const [result, setResult] = React.useState(0);

    return (
        <div>
            <input type="number" value={first} onChange={(e) => setFirst(Number(e.target.value))} />
            <input type="number" value={second} onChange={(e) => setSecond(Number(e.target.value))} />
            <button onClick={() => add(first, second)}>+</button>
            <p>{result}</p>
        </div>
    );

}
</code>```

If I don't use composite flag, it works as expected. Base tsconfig.json for packages is:

```<code>{
    "extends": "./tsconfig.base.json", // non relevant parameters
    "compilerOptions": {
        "composite": false,
        "noEmit": false
    }
}
</code>```

and consumer package's tsconfig is :

```<code>{
    "extends": "../../tsconfig.lib.json",
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx"
    ],
    "compilerOptions": {
        "outDir": "./lib",
        "baseUrl": "./src"
    }
}
</code>```

But If enable the composite flag, it stop compiling, telling me the '@tsmonorepo/common' cannot be found.

In this case, lib's common config is

```<code>{
    "extends": "./tsconfig.base.json", // non relevant parameters
    "compilerOptions": {
        "composite": true,
        "noEmit": false
    }
}
</code>```

and consumer package's tsconfig is :

```<code>{
    "extends": "../../tsconfig.lib.json",
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx"
    ],
    "compilerOptions": {
        "outDir": "./lib",
        "baseUrl": "./src"
    },
    "references": [
        {
            "path": "..\\common"
        }
    ]
}
</code>```

The exact error message is :

```<code>src/Calc/Calc.tsx:1:21 - error TS2307: Cannot find module '@tsmonorepo/common' or its corresponding type declar
│ 1 import { add } from '@tsmonorepo/common';
│                       ~~~~~~~~~~~~~~~~~~~~
│ Found 1 error.
</code>```

What I try to achieve is to have a smooth dev experience. I expect to have a single "watch" mode for the leaf project and let TS recompile what's required whatever the modified package is.

How to fix that ?

Body:
I'm trying to setup a pnpm monorepository that contains multiple typescript packages.

I reference packages using the pnpm's workspace alias and import then using its name.

Packages can be either reusable code (pure typescript or react library) or react application.

Because the shared packages does not need to be published (only goal is to reuse code across applicaiton), I have no bundler or similar. Build is performed by tsc.

Everything work as expected unless I enable the composite flag.

To illustrate, I've created a reproductible repository

Basically, I've a @tsmonorepo/common package that export a simple module:

const add = (a: number, b: number) => a + b;
const subtract = (a: number, b: number) => a - b;
const multiply = (a: number, b: number) => a * b;
const divide = (a: number, b: number) => a / b;

export { add, subtract, multiply, divide };

And I consume it from another package @tsmonorepo/react-common

import { add } from '@tsmonorepo/common';
import * as React from 'react';

const Calc: React.FC = () => {
    const [first, setFirst] = React.useState(0);
    const [second, setSecond] = React.useState(0);

    const [result, setResult] = React.useState(0);

    return (

            <input type="number" value={first} onChange={(e) => setFirst(Number(e.target.value))} />
            <input type="number" value={second} onChange={(e) => setSecond(Number(e.target.value))} />
            <button onClick={() => add(first, second)}>+</button>

{result}

    );

}

If I don't use composite flag, it works as expected. Base tsconfig.json for packages is:

{
    "extends": "./tsconfig.base.json", // non relevant parameters
    "compilerOptions": {
        "composite": false,
        "noEmit": false
    }
}

and consumer package's tsconfig is :

{
    "extends": "../../tsconfig.lib.json",
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx"
    ],
    "compilerOptions": {
        "outDir": "./lib",
        "baseUrl": "./src"
    }
}

But If enable the composite flag, it stop compiling, telling me the '@tsmonorepo/common' cannot be found.

In this case, lib's common config is

{
    "extends": "./tsconfig.base.json", // non relevant parameters
    "compilerOptions": {
        "composite": true,
        "noEmit": false
    }
}

and consumer package's tsconfig is :

{
    "extends": "../../tsconfig.lib.json",
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx"
    ],
    "compilerOptions": {
        "outDir": "./lib",
        "baseUrl": "./src"
    },
    "references": [
        {
            "path": "..\\common"
        }
    ]
}

The exact error message is :

src/Calc/Calc.tsx:1:21 - error TS2307: Cannot find module '@tsmonorepo/common' or its corresponding type declar
│ 1 import { add } from '@tsmonorepo/common';
│                       ~~~~~~~~~~~~~~~~~~~~
│ Found 1 error.

What I try to achieve is to have a smooth dev experience. I expect to have a single "watch" mode for the leaf project and let TS recompile what's required whatever the modified package is.

How to fix that ?


来源: stackexchange

问:
Jenkins JobDSL generation failure after plugin updates
We have been using same JobDSL generation scripts for ages and after we did have some plugin updates to latest ones, JobDSL generation started to fail and not finding how to get it fixed.

Here is example what we are doing

```<code>package foobar.qvantel.dsl.builders;

import javaposse.jobdsl.dsl.Context:
import javaposse.jobdsl.dsl.Item;

import groovy.json.JsonSlurper;

import com.foobar.dsl.builders.PipelineJobBuilder;
import com.foobar.dsl.common.CommonConstants;

class StackstormJobBuilder {
  Map mapping = [:];
  String resourcePath = 'default'

  Item build(Context context) {
    def mappingFile = context.readFileFromWorkspace(CommonConstants.RESOURCES_PATH +'stackstorm/' + this.resourcePath + '/mapping.json');
    def mappingData = new JsonSlurper().parseText(mappingFile);
    def combinedMapping = mappingData + this.mapping
    def eventMapping = '  def mapping = [\n'
    eventMapping += combinedMapping.collect { key, value ->
      def content = "    '${key}': [\n"
      content += value.collect { source, target ->
        def line = "      '${source}': ["
        if (target instanceof List) {
          line += target.collect { "'${it}'" }.join(', ')
        } else {
          line += "'${target}'"
        }
        line += ']'
        return line
      }.join(',\n')
      content += '\n    ]'
      return content
    }.join(',\n')
    eventMapping += '\n  ]'
    def pipelineScript = """
try {
  ${eventMapping}
    if (mapping[INSTANCE] && mapping[INSTANCE][JOB]) {
      for (job in mapping[INSTANCE][JOB]) {
        build job: job, wait: false
      }
    } else {
      unstable "No matching event mapping found."
    }
 } catch (all) {
     echo 'ERROR: ' + all.toString();
     currentBuild.result = 'FAILURE';
 }
"""
</code>```

Here is example mapping.json content processed by above snippet:

```<code>{
  "auto-jenkins": {
    "devops_jenkins-config-as-code_pipeline/master": "deploy_jenkins-config-as-code"
  }
}
</code>```

Previously / expected output in generated job config would be something like this:

```<code>try {
  def mapping = [
    'auto-jenkins': [
      'devops_jenkins-config-as-code_pipeline/master': ['deploy_jenkins-config-as-code']
    ]
  ]
  if (mapping[INSTANCE] && mapping[INSTANCE][JOB]) {
    for (job in mapping[INSTANCE][JOB]) {
      build job: job, wait: false
    }
  } else {
    unstable "No matching event mapping found."
  }
} catch (all) {
  echo 'ERROR: ' + all.toString();
  currentBuild.result = 'FAILURE';
}
</code>```

But actual failure in JobDSL generation is like this:

```<code> org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '      'devops_jenkins-config-as-code_pipeline/master': ['deploy_jenkins-config-as-code']' with class 'org.codehaus.groovy.runtime.GStringImpl' to class 'javaposse.jobdsl.dsl.Item'
</code>```

And it is coming exactly from this line above:

```<code>return line
</code>```

And unfortunately these JobDSL stuff are not my core knowledge area (guy who has implemented this stuff not available anymore), so any help is highly appreciated!

ContentLicense: CC BY-SA 4.0

Body:
We have been using same JobDSL generation scripts for ages and after we did have some plugin updates to latest ones, JobDSL generation started to fail and not finding how to get it fixed.

Here is example what we are doing

package foobar.qvantel.dsl.builders;

import javaposse.jobdsl.dsl.Context:
import javaposse.jobdsl.dsl.Item;

import groovy.json.JsonSlurper;

import com.foobar.dsl.builders.PipelineJobBuilder;
import com.foobar.dsl.common.CommonConstants;

class StackstormJobBuilder {
  Map mapping = [:];
  String resourcePath = 'default'

  Item build(Context context) {
    def mappingFile = context.readFileFromWorkspace(CommonConstants.RESOURCES_PATH +'stackstorm/' + this.resourcePath + '/mapping.json');
    def mappingData = new JsonSlurper().parseText(mappingFile);
    def combinedMapping = mappingData + this.mapping
    def eventMapping = '  def mapping = [\n'
    eventMapping += combinedMapping.collect { key, value ->
      def content = "    '${key}': [\n"
      content += value.collect { source, target ->
        def line = "      '${source}': ["
        if (target instanceof List) {
          line += target.collect { "'${it}'" }.join(', ')
        } else {
          line += "'${target}'"
        }
        line += ']'
        return line
      }.join(',\n')
      content += '\n    ]'
      return content
    }.join(',\n')
    eventMapping += '\n  ]'
    def pipelineScript = """
try {
  ${eventMapping}
    if (mapping[INSTANCE] && mapping[INSTANCE][JOB]) {
      for (job in mapping[INSTANCE][JOB]) {
        build job: job, wait: false
      }
    } else {
      unstable "No matching event mapping found."
    }
 } catch (all) {
     echo 'ERROR: ' + all.toString();
     currentBuild.result = 'FAILURE';
 }
"""

Here is example mapping.json content processed by above snippet:

{
  "auto-jenkins": {
    "devops_jenkins-config-as-code_pipeline/master": "deploy_jenkins-config-as-code"
  }
}

Previously / expected output in generated job config would be something like this:

try {
  def mapping = [
    'auto-jenkins': [
      'devops_jenkins-config-as-code_pipeline/master': ['deploy_jenkins-config-as-code']
    ]
  ]
  if (mapping[INSTANCE] && mapping[INSTANCE][JOB]) {
    for (job in mapping[INSTANCE][JOB]) {
      build job: job, wait: false
    }
  } else {
    unstable "No matching event mapping found."
  }
} catch (all) {
  echo 'ERROR: ' + all.toString();
  currentBuild.result = 'FAILURE';
}

But actual failure in JobDSL generation is like this:

 org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '      'devops_jenkins-config-as-code_pipeline/master': ['deploy_jenkins-config-as-code']' with class 'org.codehaus.groovy.runtime.GStringImpl' to class 'javaposse.jobdsl.dsl.Item'

And it is coming exactly from this line above:

return line

And unfortunately these JobDSL stuff are not my core knowledge area (guy who has implemented this stuff not available anymore), so any help is highly appreciated!


问:
Not able to install project dependencies NodeJS
I am trying to install dependency in a project but getting this error. I already upgraded all dependencies and versions of npm but that's not working for me.

Package.json:

```<code>{
  "name": "task",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.0",
    "body-parser": "^1.19.0",
    "connect-mongo": "^3.2.0",
    "ejs": "^3.1.6",
    "express": "^4.18.1",
    "express-fileupload": "^1.4.0",
    "express-flash": "^0.0.2",
    "express-session": "^1.17.3",
    "lodash": "^4.17.21",
    "mongodb": "^4.9.1",
    "mongoose": "^6.0.5",
    "multer": "^1.4.3",
    "node": "^16.6.1",
    "nodemailer": "^6.7.0",
    "nodemon": "^2.0.13",
    "open": "^8.4.0",
    "passport": "^0.6.0",
    "passport-local": "^1.0.0",
    "simplebar": "^5.3.5"
  }
}
</code>```

Body:
I am trying to install dependency in a project but getting this error. I already upgraded all dependencies and versions of npm but that's not working for me.

Package.json:

{
  "name": "task",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.0",
    "body-parser": "^1.19.0",
    "connect-mongo": "^3.2.0",
    "ejs": "^3.1.6",
    "express": "^4.18.1",
    "express-fileupload": "^1.4.0",
    "express-flash": "^0.0.2",
    "express-session": "^1.17.3",
    "lodash": "^4.17.21",
    "mongodb": "^4.9.1",
    "mongoose": "^6.0.5",
    "multer": "^1.4.3",
    "node": "^16.6.1",
    "nodemailer": "^6.7.0",
    "nodemon": "^2.0.13",
    "open": "^8.4.0",
    "passport": "^0.6.0",
    "passport-local": "^1.0.0",
    "simplebar": "^5.3.5"
  }
}


问:
When exactly does Java implicitly allocate heap memory?
I distantly recall that one design decision of Java was to make heap allocations explicit, with new keyword (don't quote me on that, please).

It does deviate from this decision, at the very least, in two cases:

Passing varargs to a function (Array is implicitly allocated),

Assigning a primitive type to a boxed value/argument (autoboxing).

Are there other cases, and what are they? Exhaustive list is preferred.

My googling only revealed a basic articles about Java memory management.


问:
How to send request using ESQL to a REST Request Node in ACE flow
I have to call a REST API in my flow, that uses SSL authentication. I used a Compute Node to generate the input message and set the required header parameters in HTTPRequestHeaders. I set my Keydb file for the Integration Server that has the cert and key files.

```<code></code>```
```<code>SET OutputRoot.HTTPRequestHeader."Authorization" = InputRoot.HTTPRequestHeader.Authorization;
     SET OutputRoot.HTTPRequestHeader."X-WCM-TENANT-ID" = '8223028';
     SET OutputRoot.HTTPRequestHeader."X-WCM-TENANT-INSTANCE"='02';
     SET OutputRoot.HTTPRequestHeader."accept"='application/json';
     SET OutputRoot.HTTPRequestHeader."Referer" = 'curam://foundational.app';
     SET OutputRoot.HTTPRequestHeader."Content-Type"='application/json';

     SET OutputRoot.HTTPRequestHeader."X-GRANT-TYPE"='client_credentials';
</code>```
```<code>    SET OutputRoot.JSON.Data.messageID = '123';
        SET OutputRoot.JSON.Data.id = 'extProviderESR5';
        SET OutputRoot.JSON.Data.name = 'ext provder1 name';
        SET OutputRoot.JSON.Data.description = 'ext provder1 desc';
        SET OutputRoot.JSON.Data.email = 'extprovider1@example.com';
        SET OutputRoot.JSON.Data.url = 'http://www.extprovider1.com';
</code>```
```<code>I get 400 Bad request error. The same headers and data, if used in Postman, it creates the object.

Can some one help me to identify , what am I missing..
</code>```

I should be create the object using the API call

```<code>type here
</code>```

Body:
I have to call a REST API in my flow, that uses SSL authentication. I used a Compute Node to generate the input message and set the required header parameters in HTTPRequestHeaders. I set my Keydb file for the Integration Server that has the cert and key files.

SET OutputRoot.HTTPRequestHeader."Authorization" = InputRoot.HTTPRequestHeader.Authorization;
     SET OutputRoot.HTTPRequestHeader."X-WCM-TENANT-ID" = '8223028';
     SET OutputRoot.HTTPRequestHeader."X-WCM-TENANT-INSTANCE"='02';
     SET OutputRoot.HTTPRequestHeader."accept"='application/json';
     SET OutputRoot.HTTPRequestHeader."Referer" = 'curam://foundational.app';
     SET OutputRoot.HTTPRequestHeader."Content-Type"='application/json';

     SET OutputRoot.HTTPRequestHeader."X-GRANT-TYPE"='client_credentials';

    SET OutputRoot.JSON.Data.messageID = '123';
        SET OutputRoot.JSON.Data.id = 'extProviderESR5';
        SET OutputRoot.JSON.Data.name = 'ext provder1 name';
        SET OutputRoot.JSON.Data.description = 'ext provder1 desc';
        SET OutputRoot.JSON.Data.email = 'extprovider1@example.com';
        SET OutputRoot.JSON.Data.url = 'http://www.extprovider1.com';

I get 400 Bad request error. The same headers and data, if used in Postman, it creates the object.

Can some one help me to identify , what am I missing..

I should be create the object using the API call

type here


问:
Need To See When Record Was Added To Database but Don't Track That - SQLITE
I have an immediate need to identify users added to my SQLite database after a specific date, however I don't currently have a field in my table that tracks the date a record is added. Is there any built in functionality for tracking when a record is added to a SQLite database? If so, how would I go about grabbing this data?</p>


问:
configuration of yml file for cloud workflow
i want to write on yml file for create a workflow for scheduler et progrmmer my dataflow et dataproc serveless job, can you help me?

i try

```<code># This is a sample cloud workflow YAML file for scheduling Dataflow jobs.

name: Scheduled Dataflow Job

# Replace [PROJECT_ID] with your Google Cloud project ID.
project: [PROJECT_ID]

# This workflow will run daily at 9:00 AM.
schedule: every 24 hours at 9:00

# The `dataflow` template will be used to run the Dataflow job.
# Replace [TEMPLATE_NAME] with the name of your Dataflow template.
# Replace [TEMPLATE_PROJECT] with the Google Cloud project where the
# Dataflow template is stored.
entrypoint: dataflow

parameters:
  jobName: [TEMPLATE_NAME]
  tempLocation: gs://[TEMPLATE_PROJECT]/temp
  region: us-central1
  zones: us-central1-*
  inputFile: gs://[TEMPLATE_PROJECT]/input/data.txt
  outputFile: gs://[TEMPLATE_PROJECT]/output/data.txt

</code>```

but it's not ok

Body:
i want to write on yml file for create a workflow for scheduler et progrmmer my dataflow et dataproc serveless job, can you help me?

i try

# This is a sample cloud workflow YAML file for scheduling Dataflow jobs.

name: Scheduled Dataflow Job

# Replace [PROJECT_ID] with your Google Cloud project ID.
project: [PROJECT_ID]

# This workflow will run daily at 9:00 AM.
schedule: every 24 hours at 9:00

# The `dataflow` template will be used to run the Dataflow job.
# Replace [TEMPLATE_NAME] with the name of your Dataflow template.
# Replace [TEMPLATE_PROJECT] with the Google Cloud project where the
# Dataflow template is stored.
entrypoint: dataflow

parameters:
  jobName: [TEMPLATE_NAME]
  tempLocation: gs://[TEMPLATE_PROJECT]/temp
  region: us-central1
  zones: us-central1-*
  inputFile: gs://[TEMPLATE_PROJECT]/input/data.txt
  outputFile: gs://[TEMPLATE_PROJECT]/output/data.txt

but it's not ok


问:
Both child components are firing the same event when only clicking on of them only
I have 2 identical child components on the page. The child component contains a table and a series of functionality.

```<code><app-child [model]="model1" (onDelete)="deleteForModel1($event)">
</app-child>

<app-child [model]="model2" (onDelete)="deleteForModel2($event)">
</app-child>
</code>```

I have this method in the component.

```<code>deleteItem(id: number): void{
  if(confirm('Do you want to delete this item?')){
    //...
    this.onDelete.emit(id);
  }
}
</code>```

Everything works fine when I click on the first child-component. However, when I click on the second component, deleteItem method runs 2x.

Does Angular fail to realize that there are 2 child components?

Thanks for helping

Body:
I have 2 identical child components on the page. The child component contains a table and a series of functionality.

<app-child [model]="model1" (onDelete)="deleteForModel1($event)">
</app-child>

<app-child [model]="model2" (onDelete)="deleteForModel2($event)">
</app-child>

I have this method in the component.

deleteItem(id: number): void{
  if(confirm('Do you want to delete this item?')){
    //...
    this.onDelete.emit(id);
  }
}

Everything works fine when I click on the first child-component. However, when I click on the second component, deleteItem method runs 2x.

Does Angular fail to realize that there are 2 child components?

Thanks for helping


问:
How to know what file was saved when using asynchronous filesystem fileWrite()?
I have the following code and I want to know what file was saved:

```<code>import fs from "fs";

class MyClass {

    saveFiles() {

       // loop through 1000000 files
       for loop {
           fs.writeFile(uploadFilePath, file.buffer, this.fileSaveHandler);
       }
    }

    fileSaveHandler(error: any = null) {
        // what file was just saved?
        // i need to do other stuff here
    }
}
</code>```

It looks like it's impossible to do it this way in node js.

I do NOT want to use promises or inline call backs.

Body:
I have the following code and I want to know what file was saved:

import fs from "fs";

class MyClass {

    saveFiles() {

       // loop through 1000000 files
       for loop {
           fs.writeFile(uploadFilePath, file.buffer, this.fileSaveHandler);
       }
    }

    fileSaveHandler(error: any = null) {
        // what file was just saved?
        // i need to do other stuff here
    }
}

It looks like it's impossible to do it this way in node js.

I do NOT want to use promises or inline call backs.


问:
Missing access_token attribute for child pages
I'm requesting child pages from a specific Page and I'm explicity requesting the access_token on fields but the response doesn't include the requested attribute.

Can someone help me understanding what's going on?

First of all I request the pages from an account through /v15.0/me/accounts endpoint:

https://graph.facebook.com/v15.0/me/accounts?access_token=[FILTERED]&fields=id,name,has_transitioned_to_new_page_experience,access_token

And here's the output:

```<code>{
  "data": [
    {
      "access_token": [FILTERED],
      "id": "10[...]80",
      "name": "Lorem Ipsum",
      "has_transitioned_to_new_page_experience": true
    }
  ],
  "paging": {
    "cursors": {
      "before": [FILTERED],
      "after": [FILTERED]
    }
  }
}
</code>```

Using that same id I then try to get all the child pages from that Page using /v15.0/OBJECT-ID/locations:

https://graph.facebook.com/v15.0/10[...]80/locations?access_token=[FILTERED]]&fields=id,name,access_token

```<code>{
  "data": [
    {
      "id": "16[...]55",
      "name": "Lorem Ipsum"
    },
    {
      "id": "10[...]68",
      "name": "Lorem Ipsum"
    }
  ],
  "paging": {
    "cursors": {
      "before": [FILTERED],
      "after": [FILTERED]
    },
    "next": "https:\/\/graph.facebook.com\/v15.0\/10[...]80\/locations?access_token=[FILTERED]&fields=id%2Cname%2Caccess_token&limit=25&after=[FILTERED]"
  }
}
</code>```

But even asking for the access_token the attribute is not returned.

Some considerations:

Permissions that I'm requesting during the authentication:

"email,pages_manage_metadata,pages_read_engagement,pages_read_user_content,pages_manage_engagement,pages_messaging,pages_messaging_subscriptions"

And the account has "MODERATE" role.

Am I missing something?

Requested the API as the docs show.
Expected to get the access_token attribute.

Body:
I'm requesting child pages from a specific Page and I'm explicity requesting the access_token on fields but the response doesn't include the requested attribute.

Can someone help me understanding what's going on?

First of all I request the pages from an account through /v15.0/me/accounts endpoint:

https://graph.facebook.com/v15.0/me/accounts?access_token=[FILTERED]&fields=id,name,has_transitioned_to_new_page_experience,access_token

And here's the output:

{
  "data": [
    {
      "access_token": [FILTERED],
      "id": "10[...]80",
      "name": "Lorem Ipsum",
      "has_transitioned_to_new_page_experience": true
    }
  ],
  "paging": {
    "cursors": {
      "before": [FILTERED],
      "after": [FILTERED]
    }
  }
}

Using that same id I then try to get all the child pages from that Page using /v15.0/OBJECT-ID/locations:

https://graph.facebook.com/v15.0/10[...]80/locations?access_token=[FILTERED]]&fields=id,name,access_token

{
  "data": [
    {
      "id": "16[...]55",
      "name": "Lorem Ipsum"
    },
    {
      "id": "10[...]68",
      "name": "Lorem Ipsum"
    }
  ],
  "paging": {
    "cursors": {
      "before": [FILTERED],
      "after": [FILTERED]
    },
    "next": "https:\/\/graph.facebook.com\/v15.0\/10[...]80\/locations?access_token=[FILTERED]&fields=id%2Cname%2Caccess_token&limit=25&after=[FILTERED]"
  }
}

But even asking for the access_token the attribute is not returned.

Some considerations:

Permissions that I'm requesting during the authentication:

"email,pages_manage_metadata,pages_read_engagement,pages_read_user_content,pages_manage_engagement,pages_messaging,pages_messaging_subscriptions"

And the account has "MODERATE" role.

Am I missing something?

Requested the API as the docs show.
Expected to get the access_token attribute.


问:
Implementing a constraint that arranges that a Task can not Start earlier than a beginning time B depending on the predeceaor
I have tried to implement a decision variable B that determines the beginning of a task at a certain location by a technician t:

```<code>dvar float B [technician, location];
</code>```

.

Now I want to implement a constraint that makes sure that if a technician t travels from a location i to a location j (if binary variable x[t, i, j]=1), the Beginning B at that location j can't be earlier than the Beginning of the task at the predecessor location i + the duration of the task at location i (d[i]) + the travel time it takes from i to j (traveltime [i, j]:

```<code>B[t,j] >= B[t,i] + d[i] + traveltime[i, j] - (1- x[t, i,j])* M;
</code>```

If I implement it like this into Cplex, i don't get a solution!
Does anybody have an idea what I am doing wrong?
Thanks for your help!

Body:
I have tried to implement a decision variable B that determines the beginning of a task at a certain location by a technician t:

dvar float B [technician, location];

.

Now I want to implement a constraint that makes sure that if a technician t travels from a location i to a location j (if binary variable x[t, i, j]=1), the Beginning B at that location j can't be earlier than the Beginning of the task at the predecessor location i + the duration of the task at location i (d[i]) + the travel time it takes from i to j (traveltime [i, j]:

B[t,j] >= B[t,i] + d[i] + traveltime[i, j] - (1- x[t, i,j])* M;

If I implement it like this into Cplex, i don't get a solution!
Does anybody have an idea what I am doing wrong?
Thanks for your help!


问:
how to save account details in selenium bot
```<code>browser.find_element(by=By.XPATH, value='//*[@id="email"]').send_keys()
</code>```

Hello, I made an account creation bot. The bot uses a random email when creating an account. How can I save the email I entered via xpath?

Body:
browser.find_element(by=By.XPATH, value='//*[@id="email"]').send_keys()

Hello, I made an account creation bot. The bot uses a random email when creating an account. How can I save the email I entered via xpath?


问:
How to capture week of the year seasonality using Fourier transform and use it as input in regression model?
I have weekly dataset with 1 input variable and 1 output variable. I want to include week of the year seasonality as a input variable in regression model. Generally we include seasonality in regression model by making dummy variable but as there are 52 weeks, including 52 dummy variable is not the feasible solution. I saw one blog here where we can use fourier series to capture seasonality. How I can use fourier series to capture week of the year seasonality? Something like

week
x1
seasoanl_inut
target

w1
0.5
3.4
1.22

w2
0.22
4,2
0.23

such that for every week I should have unique value in seasonal input variable.


问:
How to create a Git Repository with synchronised and tracking submodules
In simple terms I would like to create a Parent/Child repository where the Child is a submodule and its branch should track that of its parent.

I have been trying to get this working and thought I understood what I was doing but clearly I am missing something.

All seems to be setup correctly in config files until I switch branches 'Main -> UAT-> Main' and I end up with Child still in uat and if changes are committed to the Child, it looses its HEAD.

To keep things as simple as possible I would like to get this to working locally first.

git version 2.38.1.windows.1

Here are my steps

```<code># Setup main
# ------------
md Parent
cd Parent
git init
echo "Hello" > ReadMe.txt
git add .
git commit -m "Initialising Parent main"
cd ..

md Child
cd Child
git init
echo "Hello" > ReadMe.txt
git add .
git commit -m "Initialising Child main"
cd ..

# Add Submodule
# ------------------
cd Parent
git config --global protocol.file.allow always
git config submodule.recurse true
git config submodule.update rebase
git config push.recurseSubmodules on-demand
git submodule add -b main ..\Child
git add .
git commit -m "Added submodule"
git log --oneline
# All good on main branch
cd Child
git log --oneline
# All good on main branch
cd ..\..

# Setup uat
# -----------
cd Parent
git switch -c uat --recurse-submodules
cd Child
#! -- recurse-submodules didn't work
# Child still on main so switch manually
git switch -c uat
echo "Hello again" > Readme.txt
git add .
git commit -m "Initialising Child uat"
cd ..
git config -f .gitmodules submodule.Child.branch uat
git add .
git commit -m "Initialising Main at"
git log --oneline
# All good on uat branch
cd Child
git log --oneline
# All good on uat branch
cd ..\..

# Switch all to main
# ---------------------
# SPOILER Child Looses its HEAD
cd Parent
git switch main --recurse-submodules
cd Child
git log --oneline
#! Child lost its HEAD
</code>```

Update

Thanks @torek for suggestion to use

```<code>git submodule foreach git switch <branch>
</code>```

But I though the whole point of --recursive-submodules together with config settings

```<code>git config submodule.recurse true
git config submodule.update rebase
git config push.recurseSubmodules on-demand
</code>```

was to automate this

In fact I was of the understanding that git config submodule.recurse true should mean --recurse-submodules was implied for all operations that support it, except clone, and that git config push.recurseSubmodules on-demand would ensure warning on attempts to commit a parent having changes in submodules.

Body:
In simple terms I would like to create a Parent/Child repository where the Child is a submodule and its branch should track that of its parent.

I have been trying to get this working and thought I understood what I was doing but clearly I am missing something.

All seems to be setup correctly in config files until I switch branches 'Main -> UAT-> Main' and I end up with Child still in uat and if changes are committed to the Child, it looses its HEAD.

To keep things as simple as possible I would like to get this to working locally first.

git version 2.38.1.windows.1

Here are my steps

# Setup main
# ------------
md Parent
cd Parent
git init
echo "Hello" > ReadMe.txt
git add .
git commit -m "Initialising Parent main"
cd ..

md Child
cd Child
git init
echo "Hello" > ReadMe.txt
git add .
git commit -m "Initialising Child main"
cd ..

# Add Submodule
# ------------------
cd Parent
git config --global protocol.file.allow always
git config submodule.recurse true
git config submodule.update rebase
git config push.recurseSubmodules on-demand
git submodule add -b main ..\Child
git add .
git commit -m "Added submodule"
git log --oneline
# All good on main branch
cd Child
git log --oneline
# All good on main branch
cd ..\..

# Setup uat
# -----------
cd Parent
git switch -c uat --recurse-submodules
cd Child
#! -- recurse-submodules didn't work
# Child still on main so switch manually
git switch -c uat
echo "Hello again" > Readme.txt
git add .
git commit -m "Initialising Child uat"
cd ..
git config -f .gitmodules submodule.Child.branch uat
git add .
git commit -m "Initialising Main at"
git log --oneline
# All good on uat branch
cd Child
git log --oneline
# All good on uat branch
cd ..\..

# Switch all to main
# ---------------------
# SPOILER Child Looses its HEAD
cd Parent
git switch main --recurse-submodules
cd Child
git log --oneline
#! Child lost its HEAD

Update

Thanks @torek for suggestion to use

git submodule foreach git switch <branch>

But I though the whole point of --recursive-submodules together with config settings

git config submodule.recurse true
git config submodule.update rebase
git config push.recurseSubmodules on-demand

was to automate this

In fact I was of the understanding that git config submodule.recurse true should mean --recurse-submodules was implied for all operations that support it, except clone, and that git config push.recurseSubmodules on-demand would ensure warning on attempts to commit a parent having changes in submodules.


问:
How to create a migration of function and views from resource file in docker
I am workign on api and I will create adokcer for it, the problem raise with this part

```<code>protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(Query);
            foreach (var file in typeof(SqlResource).GetProperties())
            {
                var sql = file.GetValue(null).ToString();
                migrationBuilder.Sql(sql);
            }

            foreach (var entity in GetEntities())
            {
                var sql = BuildTriggerQuery(entity);
                migrationBuilder.Sql(sql);
            }
        }
</code>```

the exception raised at this line

```<code>var sql = file.GetValue(null).ToString();
</code>```

System.NullReferenceException: 'Object reference not set to an
instance of an object.'

I tried to migrate functions and views inside the docker (locally it works), I add the list of functions and views inside SqlResource. but creating the database from the code works.
My problem how to solve this issue? how to create a migration of function and views from resource file in docker?

Body:
I am workign on api and I will create adokcer for it, the problem raise with this part

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(Query);
            foreach (var file in typeof(SqlResource).GetProperties())
            {
                var sql = file.GetValue(null).ToString();
                migrationBuilder.Sql(sql);
            }

            foreach (var entity in GetEntities())
            {
                var sql = BuildTriggerQuery(entity);
                migrationBuilder.Sql(sql);
            }
        }

the exception raised at this line

var sql = file.GetValue(null).ToString();

System.NullReferenceException: 'Object reference not set to an
instance of an object.'

I tried to migrate functions and views inside the docker (locally it works), I add the list of functions and views inside SqlResource. but creating the database from the code works.
My problem how to solve this issue? how to create a migration of function and views from resource file in docker?


问:
How to make an Input element on a form carry a specific entry?
I am creating two different web pages, on the first page are a list of products for sale, on the second page is a form any buyer would fill to complete their purchase.

So, there is an input entry on the form that must carry the name of the product clicked on from the previous page. What JavaScript do I need to do this?

I created a function; var x == document.getElementByName("h3"), h3 carries the name of the product in the first page.


问:
Is it possible to use C code with cinterop in a Kotlin/Native Apple framework?
The goal is to use a C library in iOS trough Kotlin/Native.

Is this possible?

Thank you.


问:
Adding .htaccess file shows directory listing instead of redirecting to index.html, plus the directory listing is weird
Before I added a .htaccess file, if I typed in https://example.com/f/myfolder, it would redirect to https://example.com/f/myfolder/ (with a trailing slash). {documentRoot}/f is a symlink to a folder that contains a folder named myfolder, and myfolder contains an index.html file.

I then added the .htaccess file into {documentRoot}/f/myfolder with the contents:

```<code>RewriteEngine On

RewriteBase /f/myfolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /f/myfolder/index.html [L]
</code>```

Now if I type https://example.com/f/myfolder I get a directory listing instead of being redirected. If I type https://example.com/f/myfolder/ the rewrites work as expected.

The weird thing is that the directory listing shows the contents of {documentRoot}/f/myfolder, and the title is "Index of f/myfolder" but if I hover over (say) the index.html file, it points to https://example.com/f/index.html instead of https://example.com/f/myfolder/index.html (and if I click it, it takes me to the index.html that is in the parent folder).

I tried prepending

```<code>RewriteCond %{REQUEST_URI} !/f/myfolder/$
RewriteRule ^(.*)$ $1/ [L]
</code>```

to the .htaccess file, to try and add a trailing slash, but it didn't seem to make any difference.

One final tidbit of information. If I change +FollowSymLinks to just FollowSymLinks, I get a 403 forbidden page instead of the directory listing. EDIT: I am changing it in the apache2 config file, in the <Directory> section for the directory. The only other option in that section is AllowOverride All

I am curious as to why the directory listing is weird, but my real question is: How can I make it work both with and without trailing slashes?

Using Apache/2.4.29

EDIT: One more discovery, not sure if it helps. If I have a blank .htaccess file, then https://example.com/f/myfolder gets redirected to https://example.com/f/myfolder/. If I add RewriteEngine On to the .htaccess file and nothing else, the redirect no longer happens.

EDIT 2: It's definitely related to /f being a softlink. If I add an Alias in the apache2 config file so that it's aliased to the correct directory instead of softlinked, then it works fine. I would prefer to fix it in the .htaccess file if possible though!

Body:
Before I added a .htaccess file, if I typed in https://example.com/f/myfolder, it would redirect to https://example.com/f/myfolder/ (with a trailing slash). {documentRoot}/f is a symlink to a folder that contains a folder named myfolder, and myfolder contains an index.html file.

I then added the .htaccess file into {documentRoot}/f/myfolder with the contents:

RewriteEngine On

RewriteBase /f/myfolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /f/myfolder/index.html [L]

Now if I type https://example.com/f/myfolder I get a directory listing instead of being redirected. If I type https://example.com/f/myfolder/ the rewrites work as expected.

The weird thing is that the directory listing shows the contents of {documentRoot}/f/myfolder, and the title is "Index of f/myfolder" but if I hover over (say) the index.html file, it points to https://example.com/f/index.html instead of https://example.com/f/myfolder/index.html (and if I click it, it takes me to the index.html that is in the parent folder).

I tried prepending

RewriteCond %{REQUEST_URI} !/f/myfolder/$
RewriteRule ^(.*)$ $1/ [L]

to the .htaccess file, to try and add a trailing slash, but it didn't seem to make any difference.

One final tidbit of information. If I change +FollowSymLinks to just FollowSymLinks, I get a 403 forbidden page instead of the directory listing. EDIT: I am changing it in the apache2 config file, in the <Directory> section for the directory. The only other option in that section is AllowOverride All

I am curious as to why the directory listing is weird, but my real question is: How can I make it work both with and without trailing slashes?

Using Apache/2.4.29

EDIT: One more discovery, not sure if it helps. If I have a blank .htaccess file, then https://example.com/f/myfolder gets redirected to https://example.com/f/myfolder/. If I add RewriteEngine On to the .htaccess file and nothing else, the redirect no longer happens.

EDIT 2: It's definitely related to /f being a softlink. If I add an Alias in the apache2 config file so that it's aliased to the correct directory instead of softlinked, then it works fine. I would prefer to fix it in the .htaccess file if possible though!


问:
react redux-toolkit how to fetch product by id and display the specific product?
```<code>import { createSlice } from "@reduxjs/toolkit";
import { Productget,SingleProduct } from "../Action/UserAction";

const initialState=[]
const ProductSlice =createSlice(
    {
        name: "products",
        initialState,
        extraReducers:{
            [Productget.fulfilled]:(state,{payload})=>{
                return [...payload]
            },
            [SingleProduct.fulfilled]:(state,{payload})=>{
              state.find(post=>post.id === payload.id)
            }

        }
    }
)

const {reducer} = ProductSlice;

export default reducer
</code>```

React ProductDetail Component

```<code>import React,{useEffect,useCallback} from 'react'
import {useParams} from "react-router-dom"
import { SingleProduct } from '../Action/UserAction';
import {useDispatch, useSelector} from 'react-redux'

function ProductDetail() {
    const {productId} = useParams();
    const product = useSelector((state)=>state.products)

    console.log(product)
    const dispatch = useDispatch()

    const fetchDetails=useCallback(()=>{
        dispatch(SingleProduct({id:productId}))
    },[dispatch,productId])

    useEffect(()=>{
     fetchDetails()
    },[fetchDetails])

  return (

    <div className="container">
      <div className="row">
        <div className="col-md-12">
          <div className="card mt-2">
          <img src={product.image} style={{width:"300px"}} className="card-img-top mx-auto mt-3" alt="market" />
          <div className="card-body">
                            <h5 className="card-title">{product.title}</h5>
                                <p>{product.category}</p>
                                <p>{product.description}</p>
                                <div className="card-footer"> $ {product.price}</div>
                            </div>
          </div>
        </div>
      </div>
    </div>

  )
}

export default ProductDetail
</code>```

react redux-toolkit how to fetch product by id and display the specific product??

The product detail page does not display the specific product id details. In Redux devtool the action is displaying the specific product id detail (like the image of the product and data) but the state is displaying all product detail. should the need to update the ProductDetail component

Body:
import { createSlice } from "@reduxjs/toolkit";
import { Productget,SingleProduct } from "../Action/UserAction";

const initialState=[]
const ProductSlice =createSlice(
    {
        name: "products",
        initialState,
        extraReducers:{
            [Productget.fulfilled]:(state,{payload})=>{
                return [...payload]
            },
            [SingleProduct.fulfilled]:(state,{payload})=>{
              state.find(post=>post.id === payload.id)
            }

        }
    }
)

const {reducer} = ProductSlice;

export default reducer

React ProductDetail Component

import React,{useEffect,useCallback} from 'react'
import {useParams} from "react-router-dom"
import { SingleProduct } from '../Action/UserAction';
import {useDispatch, useSelector} from 'react-redux'

function ProductDetail() {
    const {productId} = useParams();
    const product = useSelector((state)=>state.products)

    console.log(product)
    const dispatch = useDispatch()

    const fetchDetails=useCallback(()=>{
        dispatch(SingleProduct({id:productId}))
    },[dispatch,productId])

    useEffect(()=>{
     fetchDetails()
    },[fetchDetails])

  return (

{product.title}

{product.category}

{product.description}

 $ {product.price}

  )
}

export default ProductDetail

react redux-toolkit how to fetch product by id and display the specific product??

The product detail page does not display the specific product id details. In Redux devtool the action is displaying the specific product id detail (like the image of the product and data) but the state is displaying all product detail. should the need to update the ProductDetail component


问:
How to get users' location and showing another user list of nearby users when he turn on his location in React Native
I am building react native app using Expo and I want to take location of one type of users and store location in firebase and then want to show the profiles of those users to another type of users based on their location like when user will turn their location on he will be shown the list of his nearby users based on his location(whose location was stored in firebase).
Now I don't know which react native library to use and how to store user's location and then showing users to other user when he will turn on his location and how to implement all this scenario.

Secondly, once I have stored the location (like latitude and altitude) of users, how will I show the list of users to other user who live near him like I say I want to show the list of users who live  in radius of 10km from him.

Kindly guide me how to tackle all this situation. Any type of help will be appreciated. Thank you!


问:
How to retrieve Switchgrass data on ArcGis :
I am using ArcGis online and I am trying to retrieve the SubStrateBG data using  python Arcgis API : https://developers.arcgis.com/python/guide/part3-data-io-writing-data/

My problem :  I cannot see how to use Python APi to retrieve those data

Here is an image of the data that I want to download : https://www.arcgis.com/apps/mapviewer/index.html?url=https://www.usda.gov/giseas1/rest/services/BioGas/SubStrateBG/MapServer

Thanks for you help


问:
What are these weird Postgresql connection attempts on my Heroku app?
We updated our database from Hobby to a paid one (50$/mo).

We're constantly seeing these weird connection attempts (it's being logged hundreds of times daily), one after another (like 100 attempts in 5 seconds, and then a delay)

153XXX7XXXX   2022-12-07 11:XX:XX 2022-12-07
11:XX:XX  130057XXXX  appname 3.227.75.243    Local0  Error   app/postgres.209796 [GREEN]
[9-1]  sql_error_code = 28000 time_ms = "2022-12-07 HIDDEN UTC"
pid="25283" proc_start_time="2022-12-07 HIDDEN UTC"
session_id="639HIDDEN" vtid="6/35726" tid="0" log_line="2"
database="postgres" connection_source="159.HIDDEN(35786)"
user="postgres" application_name="[unknown]" FATAL:  no pg_hba.conf
entry for host "159.HIDDEN", user "postgres", database "postgres",
no encryption

We have connection_logging and lock_waits enabled in the dashboard, but I don't think that's it.

Our app is a webserver written in Go. We're also directly connected through Jetbrain's DataGrip from our PC.

Is that connection attempt something default to Heroku?


问:
Why are BufferedReader and Scanner not identifying line breaks?
I have a program which is reading data from an external testing instrument via a serial port. It uses jSerialComm to communicate over the serial port. The data is line-delimited, so I decided to use a BufferedReader to read it line-by-line. Unfortunately, when the readLine() method is called, it blocks until the read times out. I tried using Scanner and I had the same issue with nextLine() blocking.

```<code>SerialPort port = SerialPort.getCommPort("COM4");
port.openPort();
port.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 10000, 0);
BufferedReader reader = new BufferedReader(new InputStreamReader(port.getInputStream()));
while(true) {
    // This line blocks forever
    System.out.println(reader.readLine());
}
</code>```

I thought that maybe a special character was being used for line-breaks, so I read the raw bytes from the stream and printed them to console:

```<code>int byteRead;
InputStream stream = port.getInputStream();
while ((byteRead = stream.read()) != -1) {
    System.out.write(byteRead);
    System.out.print(byteRead);
}
</code>```

This is a sample of the output:

```<code>10M77E69A65N78 32=61 32654957.46654654 32H72R82351048N78
13
10S83T84D68 32D68E69V86 32=61 32755.46553553 32H72R82351048N78
13
10L76O79W87E69S83T84 32=61 32250654.46351048 32H72R82351048N78
13
</code>```

You can clearly see that the ASCII character 13 (carriage return) is being used as the line delimiter, which in Java is represented as \r. The JavaDoc for BufferedReader#readLine says:

Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.

This leaves me very confused, as the BufferedReader should work in this scenario but does not. I drafted a proof-of-concept for a line-delimited reader which breaks on newline characters \n (or ASCII 10) and carriage returns \r (ASCII 13), and trims leading and trailing \r and \n characters:

```<code>public class ScaleReader {

    private InputStream scaleInputStream;

    public ScaleReader(InputStream scaleInputStream) {
        this.scaleInputStream = scaleInputStream;
    }

    public String readLine() throws IOException {
        StringBuilder builder = new StringBuilder();

        int charByte = scaleInputStream.read();
        while (charByte != -1 && charByte == 13 || charByte == 10)
            charByte = scaleInputStream.read();

        if (charByte == -1)
            return null;

        builder.append((char) charByte);

        while (true) {
            charByte = scaleInputStream.read();
            if (charByte == -1 || charByte == 13 || charByte == 10)
                break;

            builder.append((char) charByte);
        }

        return builder.length() == 0 ? null : builder.toString();
    }

}
</code>```

This code works as expected and returns the correct data for each call to readLine(). I cannot understand why BufferedReader is not working in this scenario, when it is clearly supposed to recognize carriage returns as line terminators.

Is there an explanation?

Body:
I have a program which is reading data from an external testing instrument via a serial port. It uses jSerialComm to communicate over the serial port. The data is line-delimited, so I decided to use a BufferedReader to read it line-by-line. Unfortunately, when the readLine() method is called, it blocks until the read times out. I tried using Scanner and I had the same issue with nextLine() blocking.

SerialPort port = SerialPort.getCommPort("COM4");
port.openPort();
port.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 10000, 0);
BufferedReader reader = new BufferedReader(new InputStreamReader(port.getInputStream()));
while(true) {
    // This line blocks forever
    System.out.println(reader.readLine());
}

I thought that maybe a special character was being used for line-breaks, so I read the raw bytes from the stream and printed them to console:

int byteRead;
InputStream stream = port.getInputStream();
while ((byteRead = stream.read()) != -1) {
    System.out.write(byteRead);
    System.out.print(byteRead);
}

This is a sample of the output:

10M77E69A65N78 32=61 32654957.46654654 32H72R82351048N78
13
10S83T84D68 32D68E69V86 32=61 32755.46553553 32H72R82351048N78
13
10L76O79W87E69S83T84 32=61 32250654.46351048 32H72R82351048N78
13

You can clearly see that the ASCII character 13 (carriage return) is being used as the line delimiter, which in Java is represented as \r. The JavaDoc for BufferedReader#readLine says:

Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.

This leaves me very confused, as the BufferedReader should work in this scenario but does not. I drafted a proof-of-concept for a line-delimited reader which breaks on newline characters \n (or ASCII 10) and carriage returns \r (ASCII 13), and trims leading and trailing \r and \n characters:

public class ScaleReader {

    private InputStream scaleInputStream;

    public ScaleReader(InputStream scaleInputStream) {
        this.scaleInputStream = scaleInputStream;
    }

    public String readLine() throws IOException {
        StringBuilder builder = new StringBuilder();

        int charByte = scaleInputStream.read();
        while (charByte != -1 && charByte == 13 || charByte == 10)
            charByte = scaleInputStream.read();

        if (charByte == -1)
            return null;

        builder.append((char) charByte);

        while (true) {
            charByte = scaleInputStream.read();
            if (charByte == -1 || charByte == 13 || charByte == 10)
                break;

            builder.append((char) charByte);
        }

        return builder.length() == 0 ? null : builder.toString();
    }

}

This code works as expected and returns the correct data for each call to readLine(). I cannot understand why BufferedReader is not working in this scenario, when it is clearly supposed to recognize carriage returns as line terminators.

Is there an explanation?


问:
Clang Error when installing DuckDb as part of a project
Was trying to setup a github repo locally (owid/owid-grapher) but keep running into this clang error issue which leads to node-gyp and node-pre-gyp errors

I call it using npm_config_build_from_source=true yarn install and then everything works up until the node-pre-gyp shows up with fallback to build. There is a clang error mentioned in the output and seems to be the reason.
Can't figure out why it's showing up.

`

```<code>error /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb: Command failed.
Exit code: 1
Command: node-pre-gyp install --fallback-to-build
Arguments:
Directory: /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
Output:
node-pre-gyp info it worked if it ends with ok
node-pre-gyp info using node-pre-gyp@1.0.10
node-pre-gyp info using node@16.13.2 | darwin | arm64
node-pre-gyp info check checked for "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node" (not found)
node-pre-gyp http GET https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
node-pre-gyp ERR! install response status 403 Forbidden on https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
node-pre-gyp WARN Pre-built binaries not installable for duckdb@0.5.1 and node@16.13.2 (node-v93 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error response status 403 Forbidden on https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info find Python using Python version 3.9.10 found at "/Users/yaboi/miniforge3/bin/python3"
(node:98425) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
(Use `node --trace-deprecation ...` to show where the warning was created)
gyp info spawn /Users/yaboi/miniforge3/bin/python3
gyp info spawn args [
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Library/Caches/node-gyp/16.13.2/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/yaboi/Library/Caches/node-gyp/16.13.2',
gyp info spawn args   '-Dnode_gyp_dir=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/yaboi/Library/Caches/node-gyp/16.13.2/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/duckdb/src/duckdb_node.o
clang: error: no such file or directory: 'coder/opensource/owid-grapher/node_modules/duckdb/node_modules/node-addon-api'
make[1]: *** [Release/obj.target/duckdb/src/duckdb_node.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
gyp ERR! System Darwin 22.1.0
gyp ERR! command "/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node" "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node" "--module_name=duckdb" "--module_path=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v93"
gyp ERR! cwd /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
gyp ERR! node -v v16.13.2
gyp ERR! node-gyp -v v7.1.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node --module_name=duckdb --module_path=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v93' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js:89:23)
node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
node-pre-gyp ERR! stack     at maybeClose (node:internal/child_process:1064:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
node-pre-gyp ERR! System Darwin 22.1.0
node-pre-gyp ERR! command "/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node" "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
node-pre-gyp ERR! node -v v16.13.2
node-pre-gyp ERR! node-pre-gyp -v v1.0.10
node-pre-gyp ERR! not ok
Failed to execute '/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/bi

</code>```

`

Tried reinstalling xcode build tools, node, nvm, etc everything.

Body:
Was trying to setup a github repo locally (owid/owid-grapher) but keep running into this clang error issue which leads to node-gyp and node-pre-gyp errors

I call it using npm_config_build_from_source=true yarn install and then everything works up until the node-pre-gyp shows up with fallback to build. There is a clang error mentioned in the output and seems to be the reason.
Can't figure out why it's showing up.

`

error /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb: Command failed.
Exit code: 1
Command: node-pre-gyp install --fallback-to-build
Arguments:
Directory: /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
Output:
node-pre-gyp info it worked if it ends with ok
node-pre-gyp info using node-pre-gyp@1.0.10
node-pre-gyp info using node@16.13.2 | darwin | arm64
node-pre-gyp info check checked for "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node" (not found)
node-pre-gyp http GET https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
node-pre-gyp ERR! install response status 403 Forbidden on https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
node-pre-gyp WARN Pre-built binaries not installable for duckdb@0.5.1 and node@16.13.2 (node-v93 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error response status 403 Forbidden on https://duckdb-node.s3.amazonaws.com/duckdb-v0.5.1-node-v93-darwin-arm64.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info find Python using Python version 3.9.10 found at "/Users/yaboi/miniforge3/bin/python3"
(node:98425) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
(Use `node --trace-deprecation ...` to show where the warning was created)
gyp info spawn /Users/yaboi/miniforge3/bin/python3
gyp info spawn args [
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/yaboi/Library/Caches/node-gyp/16.13.2/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/yaboi/Library/Caches/node-gyp/16.13.2',
gyp info spawn args   '-Dnode_gyp_dir=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/yaboi/Library/Caches/node-gyp/16.13.2/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@7.1.2
gyp info using node@16.13.2 | darwin | arm64
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/duckdb/src/duckdb_node.o
clang: error: no such file or directory: 'coder/opensource/owid-grapher/node_modules/duckdb/node_modules/node-addon-api'
make[1]: *** [Release/obj.target/duckdb/src/duckdb_node.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
gyp ERR! System Darwin 22.1.0
gyp ERR! command "/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node" "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node" "--module_name=duckdb" "--module_path=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v93"
gyp ERR! cwd /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
gyp ERR! node -v v16.13.2
gyp ERR! node-gyp -v v7.1.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding/duckdb.node --module_name=duckdb --module_path=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/binding --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v93' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js:89:23)
node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
node-pre-gyp ERR! stack     at maybeClose (node:internal/child_process:1064:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
node-pre-gyp ERR! System Darwin 22.1.0
node-pre-gyp ERR! command "/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node" "/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb
node-pre-gyp ERR! node -v v16.13.2
node-pre-gyp ERR! node-pre-gyp -v v1.0.10
node-pre-gyp ERR! not ok
Failed to execute '/Users/yaboi/.nvm/versions/node/v16.13.2/bin/node /Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/yaboi/Desktop/coder coder/opensource/owid-grapher/node_modules/duckdb/lib/bi

`

Tried reinstalling xcode build tools, node, nvm, etc everything.


问:
How can I change items in tabBar?
I created a custom bar but I can't change the location of the image and text in the itembar itself.

What I have:

and here is what I want to get:

How I initialize barItems:

```<code>private func initializeTabBar() {
    let mainNavigationController = MainNavigationController()
    mainNavigationController.tabBarItem = UITabBarItem(title: "Explorer", image: UIImage(named: "dot"), tag: 0)

    let mainCoordinator = coordinatorFactory.makeMainCoordinator(with: Router(rootController: mainNavigationController))

    let BasketViewController = BusketViewController()
    BasketViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "busket"), tag: 1)

    let FavoriteViewController = FavoriteViewController()
    FavoriteViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "heart"), tag: 2)

    let ProfileViewController = ProfileViewController()
    ProfileViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "profile"), tag: 3)

    tabBarController.viewControllers = [mainNavigationController,BasketViewController,FavoriteViewController,ProfileViewController]
</code>```

tabbar setup:

```<code>func setup() {
    tabBar.itemWidth = tabBar.bounds.width / 10
    tabBar.itemPositioning = .centered

    tabBar.tintColor = AppColors.white
    tabBar.unselectedItemTintColor = AppColors.white
}

func setupBackground() {
    let positionX: CGFloat = 0
    let PositionY: CGFloat = 8
    let width = tabBar.bounds.width - positionX * 2
    let height = tabBar.bounds.height + PositionY * 2
    let rounderLayer = CAShapeLayer()
    let bezierPath = UIBezierPath(
        roundedRect: CGRect(x: positionX, y: tabBar.bounds.minY - PositionY, width: width, height: height), cornerRadius: height / 2 )
    rounderLayer.path = bezierPath.cgPath
    rounderLayer.fillColor = AppColors.darkBlue.cgColor
    tabBar.layer.insertSublayer(rounderLayer, at: 0)
}
</code>```

I will accept all advice or solutions.

Title: How can I change items in tabBar?

Body:
I created a custom bar but I can't change the location of the image and text in the itembar itself.

What I have:

and here is what I want to get:

How I initialize barItems:

private func initializeTabBar() {
    let mainNavigationController = MainNavigationController()
    mainNavigationController.tabBarItem = UITabBarItem(title: "Explorer", image: UIImage(named: "dot"), tag: 0)

    let mainCoordinator = coordinatorFactory.makeMainCoordinator(with: Router(rootController: mainNavigationController))

    let BasketViewController = BusketViewController()
    BasketViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "busket"), tag: 1)

    let FavoriteViewController = FavoriteViewController()
    FavoriteViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "heart"), tag: 2)

    let ProfileViewController = ProfileViewController()
    ProfileViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "profile"), tag: 3)

    tabBarController.viewControllers = [mainNavigationController,BasketViewController,FavoriteViewController,ProfileViewController]

tabbar setup:

func setup() {
    tabBar.itemWidth = tabBar.bounds.width / 10
    tabBar.itemPositioning = .centered

    tabBar.tintColor = AppColors.white
    tabBar.unselectedItemTintColor = AppColors.white
}

func setupBackground() {
    let positionX: CGFloat = 0
    let PositionY: CGFloat = 8
    let width = tabBar.bounds.width - positionX * 2
    let height = tabBar.bounds.height + PositionY * 2
    let rounderLayer = CAShapeLayer()
    let bezierPath = UIBezierPath(
        roundedRect: CGRect(x: positionX, y: tabBar.bounds.minY - PositionY, width: width, height: height), cornerRadius: height / 2 )
    rounderLayer.path = bezierPath.cgPath
    rounderLayer.fillColor = AppColors.darkBlue.cgColor
    tabBar.layer.insertSublayer(rounderLayer, at: 0)
}

I will accept all advice or solutions.


问:
Locating balls on pool table using OpenCVSharp
I'm trying to detect circles on an image, however I don't know what I'm doing wrong but the code is getting for me only 2 circles on the right as shown on the image below:

Here it is the code that I have tried:

```<code>using System;

using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Windows.Forms.VisualStyles;
using OpenCvSharp;
using Point = System.Drawing.Point;

namespace ConsoleApplication1
{
    internal class Program
    {
        public static void Main(string[] args)
        {

            Mat image = Cv2.ImRead(@"C:\Users\User\Desktop\pool.jpg", ImreadModes.Color);

            Mat cImage = image.Clone();

            Mat grayedColor = new Mat();

            Cv2.CvtColor(cImage, grayedColor, ColorConversionCodes.BGR2GRAY);

            var cirlce = Cv2.HoughCircles(grayedColor, HoughModes.Gradient, 1.2, 1);

            foreach (var cirl in cirlce)
            {
                cImage.Circle(cirl.Center.ToPoint(), (int)cirl.Radius, Scalar.Magenta, 2, LineTypes.Link4);
            }

            Stopwatch timer = new Stopwatch();
            timer.Start();

            Cv2.ImShow("Original", cImage);
            Cv2.ImShow("Grayed Color", grayedColor);

            Console.WriteLine(timer.Elapsed.ToString(@"m\:ss\.fff"));

            Cv2.WaitKey();
            Cv2.DestroyAllWindows();

        }

    }
}
</code>```

Please if you post a solution explain to me what I'm doing wrong exactly.

Body:
I'm trying to detect circles on an image, however I don't know what I'm doing wrong but the code is getting for me only 2 circles on the right as shown on the image below:

Here it is the code that I have tried:

using System;

using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Windows.Forms.VisualStyles;
using OpenCvSharp;
using Point = System.Drawing.Point;

namespace ConsoleApplication1
{
    internal class Program
    {
        public static void Main(string[] args)
        {

            Mat image = Cv2.ImRead(@"C:\Users\User\Desktop\pool.jpg", ImreadModes.Color);

            Mat cImage = image.Clone();

            Mat grayedColor = new Mat();

            Cv2.CvtColor(cImage, grayedColor, ColorConversionCodes.BGR2GRAY);

            var cirlce = Cv2.HoughCircles(grayedColor, HoughModes.Gradient, 1.2, 1);

            foreach (var cirl in cirlce)
            {
                cImage.Circle(cirl.Center.ToPoint(), (int)cirl.Radius, Scalar.Magenta, 2, LineTypes.Link4);
            }

            Stopwatch timer = new Stopwatch();
            timer.Start();

            Cv2.ImShow("Original", cImage);
            Cv2.ImShow("Grayed Color", grayedColor);

            Console.WriteLine(timer.Elapsed.ToString(@"m\:ss\.fff"));

            Cv2.WaitKey();
            Cv2.DestroyAllWindows();

        }

    }
}

Please if you post a solution explain to me what I'm doing wrong exactly.


问:
How do I show a certain amount of of users while giving the option to load more?
Part of my app, I allow users to explore other users with a ForEach line - however I have quickly realised how inefficient and laggy this will become in the future.

My question is: How do I only show a few users at first (lets say 8) then once you scroll to the bottom of the displayed users more will load in?

My code is below.

SWIFT UI VIEW:

```<code>        NavigationView {
        VStack {
            SearchBar(text: $viewModel.searchText)
                .padding()
            ScrollView {
                LazyVStack {
                    ForEach(viewModel.searchableUsers) { user in
                        NavigationLink {
                                ProfileView(user: user)
                        } label: {
                            UserRowView(user: user)
                        }
                    }
                }
            }
        }
    }
</code>```

VIEW MODEL:

```<code>class ExploreViewModel: ObservableObject {
@Published var users = [User]()
@Published var searchText = ""
private let config: ExploreViewModelConfiguration

var searchableUsers: [User] {
    if searchText.isEmpty {
        return users
    } else {
        let lowercasedQuery = searchText.lowercased()

        return users.filter({
            $0.username.contains(lowercasedQuery) ||
            $0.name.lowercased().contains(lowercasedQuery)
        })
    }
}

let service = UserService()

init(config: ExploreViewModelConfiguration) {
    self.config = config
    fetchUsers(forConfig: config)
}

func fetchUsers(forConfig config: ExploreViewModelConfiguration) {
    service.fetchUsers { users in
        let users = users

        switch config {
        case .newMessage:
            self.users = users.filter({ !$0.isCurrentUser })
        case .search:
            self.users = users
        }
    }
}
</code>```

}

Body:
Part of my app, I allow users to explore other users with a ForEach line - however I have quickly realised how inefficient and laggy this will become in the future.

My question is: How do I only show a few users at first (lets say 8) then once you scroll to the bottom of the displayed users more will load in?

My code is below.

SWIFT UI VIEW:

        NavigationView {
        VStack {
            SearchBar(text: $viewModel.searchText)
                .padding()
            ScrollView {
                LazyVStack {
                    ForEach(viewModel.searchableUsers) { user in
                        NavigationLink {
                                ProfileView(user: user)
                        } label: {
                            UserRowView(user: user)
                        }
                    }
                }
            }
        }
    }

VIEW MODEL:

class ExploreViewModel: ObservableObject {
@Published var users = [User]()
@Published var searchText = ""
private let config: ExploreViewModelConfiguration

var searchableUsers: [User] {
    if searchText.isEmpty {
        return users
    } else {
        let lowercasedQuery = searchText.lowercased()

        return users.filter({
            $0.username.contains(lowercasedQuery) ||
            $0.name.lowercased().contains(lowercasedQuery)
        })
    }
}

let service = UserService()

init(config: ExploreViewModelConfiguration) {
    self.config = config
    fetchUsers(forConfig: config)
}

func fetchUsers(forConfig config: ExploreViewModelConfiguration) {
    service.fetchUsers { users in
        let users = users

        switch config {
        case .newMessage:
            self.users = users.filter({ !$0.isCurrentUser })
        case .search:
            self.users = users
        }
    }
}

}


问:
Shiny - change select input according to previous choose
I've some Shiny app with pop-up window (ask_confirmation).
In my pop-up window I've 3 select boxes (HTML).
The values of the select boxses are taken from my file - df.

Now there are all the possible values.
I would like to change the values of box2 according to the choice in box1,
and the values of box3 according to the choice in box1.

for example: if the user chose the value "numbers" in box1 so the values in box2
will be only "1" and "2".
and if the user chose "2" in box2 so the values in box3 will be only "21","22","23"

This is my code:

```<code>library(shiny)

df = readRDS("temp_df.rds")

func1 <- function(){
  z = ""
  for (i in unique(df$col1)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
  }
  return(z)
}

func2 <- function(){
  z = ""
  for (i in unique(df$col2)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
    }
  return(z)
}

func3 <- function(){
  z = ""
  for (i in unique(df$col3)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
    }
  return(z)
}

ui = fluidPage(
  mainPanel(
    actionButton("click", "Click")
  )
)

server = function(session, input, output) {
  observeEvent(input$click, {
    ask_confirmation(
      "hi",
      title = "hi",
      type = "info",
      width = '50%',
      html = TRUE,
      text =
        div(HTML("
                <form style = ' display:flex; flex-direction: row; justify-content: center; align-items: center' action=''>
               <select name='box1' id='box1'>",func1(),"</select>
               <select name='box2' id='box2'>",func2(),"</select>
               <select name='box3' id='box3'>",func3(),"</select>
               </form>
                  ")))

  })

}
shinyApp(ui = ui, server = server)
</code>```

Any help will be welcome!!

Body:
I've some Shiny app with pop-up window (ask_confirmation).
In my pop-up window I've 3 select boxes (HTML).
The values of the select boxses are taken from my file - df.

Now there are all the possible values.
I would like to change the values of box2 according to the choice in box1,
and the values of box3 according to the choice in box1.

for example: if the user chose the value "numbers" in box1 so the values in box2
will be only "1" and "2".
and if the user chose "2" in box2 so the values in box3 will be only "21","22","23"

This is my code:

library(shiny)

df = readRDS("temp_df.rds")

func1 <- function(){
  z = ""
  for (i in unique(df$col1)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
  }
  return(z)
}

func2 <- function(){
  z = ""
  for (i in unique(df$col2)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
    }
  return(z)
}

func3 <- function(){
  z = ""
  for (i in unique(df$col3)){
    z = paste(z,"<option style=' text-align:right;' selected>",i,"</option>",sep="")
    }
  return(z)
}

ui = fluidPage(
  mainPanel(
    actionButton("click", "Click")
  )
)

server = function(session, input, output) {
  observeEvent(input$click, {
    ask_confirmation(
      "hi",
      title = "hi",
      type = "info",
      width = '50%',
      html = TRUE,
      text =
        div(HTML("
                <form style = ' display:flex; flex-direction: row; justify-content: center; align-items: center' action=''>
               <select name='box1' id='box1'>",func1(),"</select>
               <select name='box2' id='box2'>",func2(),"</select>
               <select name='box3' id='box3'>",func3(),"</select>
               </form>
                  ")))

  })

}
shinyApp(ui = ui, server = server)

Any help will be welcome!!


问:
How to check the JSON Serialization provider that is used by my JEE8 app
I am searching a way to log the JSON Serialization provider name that's used by my application (is it Moxy or Jackson or Json-b) to be sure that when I configure one of these providers I have a way to check that my config is working.
I am deploying on both payara 4 and 5

Thank you for any help.


问:
Graph only specific variables in ggplot/R
I'm graphing growth curve data using ggplot with the x axis representing time, the y axis representing optical density/bacteria and each individual line representing a different well in a plate (variable).

```<code>ggplot(pmkmd, aes(x = Time, y = OD, color = variable))+
  geom_line()
</code>```

This code works when I want to graph every well together. However, I'd like to also create graphs displaying only certain wells. Each well is labeled in the format of letter-number, as in A7-A12 through H7-H12. I want to graph the B, D, F and H rows only.

I'm sort of a novice in R, so I'm not exactly sure where to start. One thing I remember learning was grepl/grep, which I think would work in this function if I knew how to implement it, but nothing I've tried works.

Body:
I'm graphing growth curve data using ggplot with the x axis representing time, the y axis representing optical density/bacteria and each individual line representing a different well in a plate (variable).

ggplot(pmkmd, aes(x = Time, y = OD, color = variable))+
  geom_line()

This code works when I want to graph every well together. However, I'd like to also create graphs displaying only certain wells. Each well is labeled in the format of letter-number, as in A7-A12 through H7-H12. I want to graph the B, D, F and H rows only.

I'm sort of a novice in R, so I'm not exactly sure where to start. One thing I remember learning was grepl/grep, which I think would work in this function if I knew how to implement it, but nothing I've tried works.


问:
How do I correect use a shared httpclient in .net 4.72
I am using a shared httpclient to download hundreds of files in parallel.  The library is compiled for both .net 6 and .net4.72, which means that IHttpClientFactory is not available for net472.  The server I am trying to download from is behind an Azure traffic monitor and a load balancer.  This means the same URI might go to a different IP for every request.  It works most of the time, but some users are complaining their downloads hang.  As far as I can tell, this happens when the traffic manager suddenly decides to route the traffic through an entirely different region.

What I have tried:

I have a timeout of 1 minute set on the httpclient, after which I cancel the download and get a new (non-shared) httpclient.  It tries this 5 times before giving up.

I tried disposing of the old httpclient when one download times out (this cancels all the other downloads in progress and closes the connection)

I tried setting the DNS refresh time to 10 seconds via the servicepoint manager.

Adding the ip address of the server to c:\windows\system32\etc\drivers\hosts file.  This bypasses the traffic manager and load balancer and actually solves the issue.  However, this is not a workable long term solution.

I am not sure what to try next.


问:
Some icons from FontAwesome aren't displayed
I use FontAwesome 5.15.4 Free edition on my site and I have a problem: icons with numbers f2e5 and higher are not displayed.

in site template css file:
.some-el::before {  content: "\f2e5"; /*you can print any other icon with a number above f2e0, for example, f358 or f590 or etc. */  font-family: 'Font Awesome 5 Free';  }