问:
Code to partition a dual graph taking too long to run?
I have census block population data (14,000 rows of population data) that I am trying to randomly partition into political districts. Most of the code works fine, but once I get to the "creating the initial partition" section, the code takes forever to run. I waited for an hour for the code to run, and it still did not finish. It seems strange to me that the code for partitioning the graph takes so long -- any ideas as to why and how I can fix this issue?</p>
```<code>

</code>```
```<code>""" Here, num_dist specifies the number of districts in each plan visited in
the short bursts. Hawaii has 51 legislative house districts. This document
runs short bursts on the State house plan. """
num_dist = 51

# Import the relevant libraries to run short bursts:
import matplotlib.pyplot as plt
import random
import gerrychain
import numpy as np
import networkx as nx
import geopandas as gpd
import pickle
import zipfile

"""This is to make the code more replicable. For example, if we want the
same result twice, we can run the code with exactly the same random seed. """
random.seed(48)

# Import attributes of gerrychain that we need to create the initial partition:
from gerrychain import Graph, Partition, Election, proposals, updaters, constraints, accept
from gerrychain.updaters import cut_edges, Tally
from gerrychain.tree import recursive_tree_part

# Import the Hawaii blocks graph:
hawaii_bl = gpd.read_file('hi_merge.zip')
# Create a dual graph
hawaii_bl_dg = Graph.from_geodataframe(hi_merge, ignore_errors = True)

# Ideal population calculation:
""" Here, the ideal population is calculated for each district. Conceptually,
this is the total population of Hawaii divided by the number of districts.
The total population is calculated by summing the population of all the nodes
in the census blocks dual graph. The number of districts depends on which plan
we are running short bursts on. The following code is for UNADJUSTED population
data.
"""
pop = 0
for v in range(len(hawaii_bl_dg.nodes())):
    totpop = hawaii_bl_dg.nodes[v]["total"]
    pop = pop + totpop
ideal_pop = pop/num_dist
print("Ideal Pop:", ideal_pop)

# Creating the initial partition:
"""
Here, the initial partition is created for the short bursts. The seed plan is
grown using Gerrychain's Partition class. Partition takes three arguments: a
graph, an assignment of nodes to districts, and a dictionary of updaters. The
relevant graph is the Hawaii blocks graph. The recursive_tree_part
function is used for the assignment argument, which partitions a tree into
range(num_dist) parts of a population that are within epsilon = 10% of the
ideal population. Then, we extract information from each district in the
partition through the updaters. Specifically, we extract the number of
cut edges, whether or not it is connected, its total population and Native
Hawaiian/Pacific Islander population.)
"""

initial_partition = Partition(hawaii_bl_dg,
assignment = recursive_tree_part(hawaii_bl_dg, range(num_dist), ideal_pop,
  "total", 0.1, 10),
updaters={
    "cut edges": cut_edges,
    "connectedness": (nx.is_connected(hawaii_bl_dg)),
    "totpop": Tally("total", alias = "totpop"),
    "NHPIpop": Tally("other_nhpi", alias = "NHPIpop")
})
</code>```
```<code>
</code>```

Body:
I have census block population data (14,000 rows of population data) that I am trying to randomly partition into political districts. Most of the code works fine, but once I get to the "creating the initial partition" section, the code takes forever to run. I waited for an hour for the code to run, and it still did not finish. It seems strange to me that the code for partitioning the graph takes so long -- any ideas as to why and how I can fix this issue?

""" Here, num_dist specifies the number of districts in each plan visited in
the short bursts. Hawaii has 51 legislative house districts. This document
runs short bursts on the State house plan. """
num_dist = 51

# Import the relevant libraries to run short bursts:
import matplotlib.pyplot as plt
import random
import gerrychain
import numpy as np
import networkx as nx
import geopandas as gpd
import pickle
import zipfile

"""This is to make the code more replicable. For example, if we want the
same result twice, we can run the code with exactly the same random seed. """
random.seed(48)

# Import attributes of gerrychain that we need to create the initial partition:
from gerrychain import Graph, Partition, Election, proposals, updaters, constraints, accept
from gerrychain.updaters import cut_edges, Tally
from gerrychain.tree import recursive_tree_part

# Import the Hawaii blocks graph:
hawaii_bl = gpd.read_file('hi_merge.zip')
# Create a dual graph
hawaii_bl_dg = Graph.from_geodataframe(hi_merge, ignore_errors = True)

# Ideal population calculation:
""" Here, the ideal population is calculated for each district. Conceptually,
this is the total population of Hawaii divided by the number of districts.
The total population is calculated by summing the population of all the nodes
in the census blocks dual graph. The number of districts depends on which plan
we are running short bursts on. The following code is for UNADJUSTED population
data.
"""
pop = 0
for v in range(len(hawaii_bl_dg.nodes())):
    totpop = hawaii_bl_dg.nodes[v]["total"]
    pop = pop + totpop
ideal_pop = pop/num_dist
print("Ideal Pop:", ideal_pop)

# Creating the initial partition:
"""
Here, the initial partition is created for the short bursts. The seed plan is
grown using Gerrychain's Partition class. Partition takes three arguments: a
graph, an assignment of nodes to districts, and a dictionary of updaters. The
relevant graph is the Hawaii blocks graph. The recursive_tree_part
function is used for the assignment argument, which partitions a tree into
range(num_dist) parts of a population that are within epsilon = 10% of the
ideal population. Then, we extract information from each district in the
partition through the updaters. Specifically, we extract the number of
cut edges, whether or not it is connected, its total population and Native
Hawaiian/Pacific Islander population.)
"""

initial_partition = Partition(hawaii_bl_dg,
assignment = recursive_tree_part(hawaii_bl_dg, range(num_dist), ideal_pop,
  "total", 0.1, 10),
updaters={
    "cut edges": cut_edges,
    "connectedness": (nx.is_connected(hawaii_bl_dg)),
    "totpop": Tally("total", alias = "totpop"),
    "NHPIpop": Tally("other_nhpi", alias = "NHPIpop")
})


来源: stackexchange

问:
Bad exit status from /var/tmp/rpm-tmp.9hCo4Y (%build)
Currently working with a RHEL 6 offline system.

I am using a RHEL6 repo server to compile a new IGB driver (Intel® Network Adapter Driver for 82575/6, 82580, I350, and I210/211-based Gigabit Network Connections for Linux*) with a RHEL6 kernel update. It will be included in a RHEL6 patch update for an offline system. The IGB driver version I am using is igb-5.13.7 and the kernel update I am using for this patch is 2.6.32-754.48.1.el6 (x86_64).

When I use the command "rpmbuild -tb igb-5.13.7.tar.gz", the compilation errors out and I receive the following message: "Bad exit status from /var/tmp/rpm-tmp.9hCo4Y (%build)".

The last IGB network driver I compiled successfully was igb-5.10.2. Since then, I installed the most recent RHEL6 kernel update to the repo server, removed the old repodata, created new repodata, ran yum update, and restarted the repo started. I have done nothing out of the ordinary for my patch update and I have no idea why I am receiving the above error.

I read on another Stack Overflow question that if you look in the network driver's spec file (in this case igb.spec), you can find the error on line 28. For me, line 28 was "LANG=C" so I'm pretty sure that's not the issue.

Any advice on how to fix this issue or about what files I should look into?

I've tried using an older version of the IGB driver (igb-5.11.4) in case the new driver file was bad. I've tried redownloading the IGB driver I was using (igb-5.13.7) in case the file I had was corrupted.

I've tried checking the SPEC file which was recommended in another Stack Overflow to find the issue on line 28.

I've tried deleting all of the patch files and network driver from the repo server to start the whole process over from scratch. Same issue arises every time.

I've tried a solution that involves rebuilding an RPM from the Source RPM, installing the RPM spec, and rebuilding the package. However, I can't find the source RPM for the latest IGB driver. Willing to continue down this path if someone knows where to find the igb-5.13.7 source rpm or how to obtain it.

ContentLicense: CC BY-SA 4.0


问:
Storybook v6 with storybook-readme
So I have a app created with create react app with typescript. I have some components in a component folder and they have a file called .readme.md.

Now when I run storybook I se the readme part in the sidebar, but it says it can not find the readme file. If I in the storie file do a console.log on the Readme variable I import. I get the content from the readme.

My storybook/addons.js looks like this:

```<code>import 'storybook-readme/register';
</code>```

Storybook dont allow me to have a config.js and a main.js. Now the storybook-readme documentations says I need to put the following code in config.js and it does not work to put in in main.js. Så where does this part go?

```<code>import { addReadme } from 'storybook-readme';
addDecorator(addReadme);
</code>```

Title: Storybook v6 with storybook-readme

Body:
So I have a app created with create react app with typescript. I have some components in a component folder and they have a file called .readme.md.

Now when I run storybook I se the readme part in the sidebar, but it says it can not find the readme file. If I in the storie file do a console.log on the Readme variable I import. I get the content from the readme.

My storybook/addons.js looks like this:

import 'storybook-readme/register';

Storybook dont allow me to have a config.js and a main.js. Now the storybook-readme documentations says I need to put the following code in config.js and it does not work to put in in main.js. Så where does this part go?

import { addReadme } from 'storybook-readme';
addDecorator(addReadme);


问:
Is it possible to use -Like with ADSI query?
Sometimes my AD queries using the ADSI method fails on surnames with Jr. or III on the end of the name. Is it possible with ADSI to capture the last names using the -LIKE filter?

For example:
$search = [adsisearcher]"(&(objectCategory=person)(objectClass=User)(sn -like Perry))"


问:
sonar scanner error "Unable to load component class org.sonar.scanner.sensor.ModuleSensorsExecutor"
Team,
my same steps locally from MacBook work fine and when I built the same in shell script and invoked from Jenkins pipeline I get this error. any hint is it permission related because am setting Jenkins as USER in docker file? or is it bug? no clue. any hint?

sonar-scanner ${SONAR_PROJECT_KEY} ${CODE_PATH} ${SONAR_HOST_URL} ${SONAR_TOKEN} ${SONAR_PROJECT_NAME}

```<code>echo "Running Sonar Setup"
Running Sonar Setup
sonar-scanner --version
INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarScanner 4.7.0.2747
INFO: Java 11.0.14.1 Eclipse Adoptium (64-bit)
INFO: Linux 5.4.0-65-generic amd64
</code>```

Jenkins log

```INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarScanner 4.7.0.2747
INFO: Java 11.0.14.1 Eclipse Adoptium (64-bit)
INFO: Linux 5.4.0-65-generic amd64
INFO: User cache: /home/jenkins/.sonar/cache
INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: Analyzing on SonarQube server 9.2.4
INFO: Default locale: "en_US", source code encoding: "US-ASCII" (analysis is platform dependent)
INFO: Load global settings
INFO: Load global settings (done) | time=537ms
INFO: Server id: C00CED92-AWlyCvw4VSvNnYFw3U2r
INFO: User cache: /home/jenkins/.sonar/cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=243ms
INFO: Load/download plugins (done) | time=40489ms
INFO: Loaded core extensions: developer-scanner
INFO: Process project properties
INFO: Process project properties (done) | time=6ms
INFO: Execute project builders
INFO: Execute project builders (done) | time=1ms
INFO: Project key: AIgroup_product_Main
INFO: Base dir: /home/jenkins/agent/workspace/product/code-coverage-WIP
INFO: Working dir: /home/jenkins/agent/workspace/product/code-coverage-WIP/.scannerwork
INFO: Load project settings for component key: 'AIgroup_product_Main'
INFO: Load project settings for component key: 'AIgroup_product_Main' (done) | time=222ms
INFO: Load project branches
INFO: Load project branches (done) | time=217ms
INFO: Load project pull requests
INFO: Load project pull requests (done) | time=214ms
INFO: Load branch configuration
INFO: Load branch configuration (done) | time=1ms
INFO: Auto-configuring with CI 'Jenkins'
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=450ms
INFO: Auto-configuring with CI 'Jenkins'
INFO: Load active rules
INFO: Load active rules (done) | time=8916ms
INFO: Indexing files...
INFO: Project configuration:
INFO: 49659 files indexed...  (last one was bazel-code-coverage-WIP/src/ui/labeling/apps/mapgt-validator/src/app/routed/jobs/job/job.component.ts)
INFO: Load project repositories
INFO: Load project repositories (done) | time=218ms
INFO: 86490 files indexed...  (last one was bazel-code-coverage-WIP/external/com_github_gogo_protobuf/protoc-gen-gogo/Makefile)
WARN: Invalid character encountered in file /home/jenkins/agent/workspace/product/code-coverage-WIP/bazel-code-coverage-WIP/external/com_google_protobuf/php/src/GPBMetadata/Google/Protobuf/Type.php at line 21 for encoding US-ASCII. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.
WARN: Invalid character encountered in file /home/jenkins/agent/workspace/product/code-coverage-WIP/bazel-code-coverage-WIP/external/com_google_protobuf/php/src/GPBMetadata/Google/Protobuf/Api.php at line 21 for encoding US-ASCII. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.
INFO: 125923 files indexed...  (last one was bazel-code-coverage-WIP/devops/terraform/live/product-sjc4/product-dev0-sjc4.nonprod-nvkong.com/modules/hl-accessmanagement/rds.tf)
INFO: 152919 files indexed...  (last one was bazel-code-coverage-WIP/bazel-out/host/bin/external/bazel_tools/tools/build_defs/hash/sha256.runfiles/product/external/python3_9_x86_64-unknown-linux-gnu/lib/python3.9/lib2to3/fixes/fix_funcattrs.py)
INFO: 188294 files indexed...  (last one was bazel-out/host/bin/external/bazel_tools/tools/build_defs/hash/sha256.runfiles/product/external/python3_9_x86_64-unknown-linux-gnu/lib/python3.9/site-packages/pip/_vendor/distlib/locators.py)
INFO: 192531 files indexed
INFO: Quality profile for c: Sonar way
INFO: Quality profile for cpp: Sonar way
INFO: Quality profile for cs: Sonar way
INFO: Quality profile for css: Sonar way
INFO: Quality profile for go: Sonar way
INFO: Quality profile for java: Sonar way
INFO: Quality profile for js: Sonar way
INFO: Quality profile for json: Sonar way
INFO: Quality profile for kotlin: Sonar way
INFO: Quality profile for objc: Sonar way
INFO: Quality profile for php: Sonar way
INFO: Quality profile for plsql: Sonar way
INFO: Quality profile for py: Sonar way
INFO: Quality profile for ruby: Sonar way
INFO: Quality profile for scala: Sonar way
INFO: Quality profile for swift: Sonar way
INFO: Quality profile for terraform: Sonar way
INFO: Quality profile for ts: Sonar way
INFO: Quality profile for web: Sonar way
INFO: Quality profile for xml: Sonar way
INFO: Quality profile for yaml: Sonar way
INFO: ------------- Run sensors on module AIgroup_product_Main_Project
INFO: Load metrics repository
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
INFO: Total time: 2:44.377s
INFO: Final Memory: 8M/120M
INFO: ------------------------------------------------------------------------
ERROR: Error during SonarScanner execution
java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorsExecutor
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at org.sonar.core.platform.ComponentContainer.getComponentByType(ComponentContainer.java:282)
    at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:79)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:384)
    at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:380)
    at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:349)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.scanner.bootstrap.GlobalContainer.doAfterStart(GlobalContainer.java:136)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.batch.bootstrapper.Batch.doExecute(Batch.java:72)
    at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:66)
    at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:46)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
    at com.sun.proxy.$Proxy0.execute(Unknown Source)
    at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:189)
    at org.sonarsource.scanner.api.EmbeddedScanner.execute(EmbeddedScanner.java:138)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:112)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:75)
    at org.sonarsource.scanner.cli.Main.main(Main.java:61)
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorExtensionDictionnary
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 27 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorContext
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 41 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.DefaultSensorStorage
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 55 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.DefaultSensorStorage
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:621)
    at org.picocontainer.containers.ImmutablePicoContainer.getComponent(ImmutablePicoContainer.java:40)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:718)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 69 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.scan.measure.DefaultMetricFinder
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 74 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.repository.MetricsRepository
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 88 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.repository.MetricsRepository
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:621)
    at org.picocontainer.containers.ImmutablePicoContainer.getComponent(ImmutablePicoContainer.java:40)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:718)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 102 more
Caused by: java.lang.IllegalStateException: Unable to load metrics
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.load(DefaultMetricsRepositoryLoader.java:47)
    at org.sonar.scanner.repository.MetricsRepositoryProvider.provide(MetricsRepositoryProvider.java:36)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.picocontainer.injectors.MethodInjector.invokeMethod(MethodInjector.java:129)
    at org.picocontainer.injectors.MethodInjector.access$000(MethodInjector.java:39)
    at org.picocontainer.injectors.MethodInjector$2.run(MethodInjector.java:113)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.MethodInjector.decorateComponentInstance(MethodInjector.java:120)
    at org.picocontainer.injectors.CompositeInjector.decorateComponentInstance(CompositeInjector.java:58)
    at org.picocontainer.injectors.Reinjector.reinject(Reinjector.java:142)
    at org.picocontainer.injectors.ProviderAdapter.getComponentInstance(ProviderAdapter.java:96)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 107 more
Caused by: java.lang.IllegalStateException: Fail to request url: http://sonar.company.com:9119/api/metrics/search?ps=500&p=1
    at org.sonarqube.ws.client.HttpConnector.doCall(HttpConnector.java:205)
    at org.sonarqube.ws.client.HttpConnector.get(HttpConnector.java:124)
    at org.sonarqube.ws.client.HttpConnector.call(HttpConnector.java:111)
    at org.sonar.scanner.bootstrap.DefaultScannerWsClient.call(DefaultScannerWsClient.java:73)
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.loadFromPaginatedWs(DefaultMetricsRepositoryLoader.java:57)
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.load(DefaultMetricsRepositoryLoader.java:45)
    ... 123 more
Caused by: java.net.SocketTimeoutException: timeout
    at okio.SocketAsyncTimeout.newTimeoutException(JvmOkio.kt:143)
    at okio.AsyncTimeout.access$newTimeoutException(AsyncTimeout.kt:162)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:335)
    at okio.RealBufferedSource.indexOf(RealBufferedSource.kt:427)
    at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.kt:320)
    at okhttp3.internal.http1.HeadersReader.readLine(HeadersReader.kt:29)
    at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:178)
    at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at org.sonarqube.ws.client.OkHttpClientBuilder.addHeaders(OkHttpClientBuilder.java:222)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
    at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
    at org.sonarqube.ws.client.HttpConnector.doCall(HttpConnector.java:203)
    ... 128 more
Caused by: java.net.SocketException: Socket closed
    at java.base/java.net.SocketInputStream.read(Unknown Source)
    at java.base/java.net.SocketInputStream.read(Unknown Source)
    at okio.InputStreamSource.read(JvmOkio.kt:90)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:129)
    ... 148 more
ERROR:
ERROR: Re-run SonarScanner using the -X switch to enable full debug logging.
[Pipeline] }
```
<p>DOCKERFILE running this</p>
```FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
  build-essential \
  ca-certificates \
  curl \
  dnsutils \
  g++ \
  gcc \
  git \
  openjdk-11-jdk-headless \
  python \
  python-dev \
  python-pkg-resources \
  python-setuptools \
  python3 \
  python3-dev \
  python3-pip \
  python3-pkg-resources \
  python3-setuptools \
  software-properties-common \
  unzip \
  wget \
  zip \
  zlib1g-dev \
  && rm -rf /var/lib/apt/lists/* && apt-get clean

RUN mkdir /downloads/sonarqube -p
RUN cd /downloads/sonarqube
RUN wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747-linux.zip
RUN unzip sonar-scanner-cli-4.7.0.2747-linux.zip
RUN mv sonar-scanner-4.7.0.2747-linux /opt/sonar-scanner
ENV PATH="$PATH:/opt/sonar-scanner/bin"
RUN rm /sonar-scanner-cli-4.7.0.2747-linux.zip
RUN useradd -ms /bin/bash jenkins
USER jenkins
WORKDIR /home/jenkins
```

Body:
Team,
my same steps locally from MacBook work fine and when I built the same in shell script and invoked from Jenkins pipeline I get this error. any hint is it permission related because am setting Jenkins as USER in docker file? or is it bug? no clue. any hint?

sonar-scanner ${SONAR_PROJECT_KEY} ${CODE_PATH} ${SONAR_HOST_URL} ${SONAR_TOKEN} ${SONAR_PROJECT_NAME}

echo "Running Sonar Setup"
Running Sonar Setup
sonar-scanner --version
INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarScanner 4.7.0.2747
INFO: Java 11.0.14.1 Eclipse Adoptium (64-bit)
INFO: Linux 5.4.0-65-generic amd64

Jenkins log

INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarScanner 4.7.0.2747
INFO: Java 11.0.14.1 Eclipse Adoptium (64-bit)
INFO: Linux 5.4.0-65-generic amd64
INFO: User cache: /home/jenkins/.sonar/cache
INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: Analyzing on SonarQube server 9.2.4
INFO: Default locale: "en_US", source code encoding: "US-ASCII" (analysis is platform dependent)
INFO: Load global settings
INFO: Load global settings (done) | time=537ms
INFO: Server id: C00CED92-AWlyCvw4VSvNnYFw3U2r
INFO: User cache: /home/jenkins/.sonar/cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=243ms
INFO: Load/download plugins (done) | time=40489ms
INFO: Loaded core extensions: developer-scanner
INFO: Process project properties
INFO: Process project properties (done) | time=6ms
INFO: Execute project builders
INFO: Execute project builders (done) | time=1ms
INFO: Project key: AIgroup_product_Main
INFO: Base dir: /home/jenkins/agent/workspace/product/code-coverage-WIP
INFO: Working dir: /home/jenkins/agent/workspace/product/code-coverage-WIP/.scannerwork
INFO: Load project settings for component key: 'AIgroup_product_Main'
INFO: Load project settings for component key: 'AIgroup_product_Main' (done) | time=222ms
INFO: Load project branches
INFO: Load project branches (done) | time=217ms
INFO: Load project pull requests
INFO: Load project pull requests (done) | time=214ms
INFO: Load branch configuration
INFO: Load branch configuration (done) | time=1ms
INFO: Auto-configuring with CI 'Jenkins'
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=450ms
INFO: Auto-configuring with CI 'Jenkins'
INFO: Load active rules
INFO: Load active rules (done) | time=8916ms
INFO: Indexing files...
INFO: Project configuration:
INFO: 49659 files indexed...  (last one was bazel-code-coverage-WIP/src/ui/labeling/apps/mapgt-validator/src/app/routed/jobs/job/job.component.ts)
INFO: Load project repositories
INFO: Load project repositories (done) | time=218ms
INFO: 86490 files indexed...  (last one was bazel-code-coverage-WIP/external/com_github_gogo_protobuf/protoc-gen-gogo/Makefile)
WARN: Invalid character encountered in file /home/jenkins/agent/workspace/product/code-coverage-WIP/bazel-code-coverage-WIP/external/com_google_protobuf/php/src/GPBMetadata/Google/Protobuf/Type.php at line 21 for encoding US-ASCII. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.
WARN: Invalid character encountered in file /home/jenkins/agent/workspace/product/code-coverage-WIP/bazel-code-coverage-WIP/external/com_google_protobuf/php/src/GPBMetadata/Google/Protobuf/Api.php at line 21 for encoding US-ASCII. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.
INFO: 125923 files indexed...  (last one was bazel-code-coverage-WIP/devops/terraform/live/product-sjc4/product-dev0-sjc4.nonprod-nvkong.com/modules/hl-accessmanagement/rds.tf)
INFO: 152919 files indexed...  (last one was bazel-code-coverage-WIP/bazel-out/host/bin/external/bazel_tools/tools/build_defs/hash/sha256.runfiles/product/external/python3_9_x86_64-unknown-linux-gnu/lib/python3.9/lib2to3/fixes/fix_funcattrs.py)
INFO: 188294 files indexed...  (last one was bazel-out/host/bin/external/bazel_tools/tools/build_defs/hash/sha256.runfiles/product/external/python3_9_x86_64-unknown-linux-gnu/lib/python3.9/site-packages/pip/_vendor/distlib/locators.py)
INFO: 192531 files indexed
INFO: Quality profile for c: Sonar way
INFO: Quality profile for cpp: Sonar way
INFO: Quality profile for cs: Sonar way
INFO: Quality profile for css: Sonar way
INFO: Quality profile for go: Sonar way
INFO: Quality profile for java: Sonar way
INFO: Quality profile for js: Sonar way
INFO: Quality profile for json: Sonar way
INFO: Quality profile for kotlin: Sonar way
INFO: Quality profile for objc: Sonar way
INFO: Quality profile for php: Sonar way
INFO: Quality profile for plsql: Sonar way
INFO: Quality profile for py: Sonar way
INFO: Quality profile for ruby: Sonar way
INFO: Quality profile for scala: Sonar way
INFO: Quality profile for swift: Sonar way
INFO: Quality profile for terraform: Sonar way
INFO: Quality profile for ts: Sonar way
INFO: Quality profile for web: Sonar way
INFO: Quality profile for xml: Sonar way
INFO: Quality profile for yaml: Sonar way
INFO: ------------- Run sensors on module AIgroup_product_Main_Project
INFO: Load metrics repository
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
INFO: Total time: 2:44.377s
INFO: Final Memory: 8M/120M
INFO: ------------------------------------------------------------------------
ERROR: Error during SonarScanner execution
java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorsExecutor
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at org.sonar.core.platform.ComponentContainer.getComponentByType(ComponentContainer.java:282)
    at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:79)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:384)
    at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:380)
    at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:349)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.scanner.bootstrap.GlobalContainer.doAfterStart(GlobalContainer.java:136)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:137)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:123)
    at org.sonar.batch.bootstrapper.Batch.doExecute(Batch.java:72)
    at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:66)
    at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:46)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
    at com.sun.proxy.$Proxy0.execute(Unknown Source)
    at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:189)
    at org.sonarsource.scanner.api.EmbeddedScanner.execute(EmbeddedScanner.java:138)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:112)
    at org.sonarsource.scanner.cli.Main.execute(Main.java:75)
    at org.sonarsource.scanner.cli.Main.main(Main.java:61)
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorExtensionDictionnary
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 27 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.ModuleSensorContext
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 41 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.DefaultSensorStorage
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 55 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.sensor.DefaultSensorStorage
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:621)
    at org.picocontainer.containers.ImmutablePicoContainer.getComponent(ImmutablePicoContainer.java:40)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:718)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 69 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.scan.measure.DefaultMetricFinder
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 74 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.repository.MetricsRepository
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 88 more
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.repository.MetricsRepository
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:66)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:621)
    at org.picocontainer.containers.ImmutablePicoContainer.getComponent(ImmutablePicoContainer.java:40)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:718)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 102 more
Caused by: java.lang.IllegalStateException: Unable to load metrics
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.load(DefaultMetricsRepositoryLoader.java:47)
    at org.sonar.scanner.repository.MetricsRepositoryProvider.provide(MetricsRepositoryProvider.java:36)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.picocontainer.injectors.MethodInjector.invokeMethod(MethodInjector.java:129)
    at org.picocontainer.injectors.MethodInjector.access$000(MethodInjector.java:39)
    at org.picocontainer.injectors.MethodInjector$2.run(MethodInjector.java:113)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.MethodInjector.decorateComponentInstance(MethodInjector.java:120)
    at org.picocontainer.injectors.CompositeInjector.decorateComponentInstance(CompositeInjector.java:58)
    at org.picocontainer.injectors.Reinjector.reinject(Reinjector.java:142)
    at org.picocontainer.injectors.ProviderAdapter.getComponentInstance(ProviderAdapter.java:96)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:64)
    ... 107 more
Caused by: java.lang.IllegalStateException: Fail to request url: http://sonar.company.com:9119/api/metrics/search?ps=500&p=1
    at org.sonarqube.ws.client.HttpConnector.doCall(HttpConnector.java:205)
    at org.sonarqube.ws.client.HttpConnector.get(HttpConnector.java:124)
    at org.sonarqube.ws.client.HttpConnector.call(HttpConnector.java:111)
    at org.sonar.scanner.bootstrap.DefaultScannerWsClient.call(DefaultScannerWsClient.java:73)
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.loadFromPaginatedWs(DefaultMetricsRepositoryLoader.java:57)
    at org.sonar.scanner.repository.DefaultMetricsRepositoryLoader.load(DefaultMetricsRepositoryLoader.java:45)
    ... 123 more
Caused by: java.net.SocketTimeoutException: timeout
    at okio.SocketAsyncTimeout.newTimeoutException(JvmOkio.kt:143)
    at okio.AsyncTimeout.access$newTimeoutException(AsyncTimeout.kt:162)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:335)
    at okio.RealBufferedSource.indexOf(RealBufferedSource.kt:427)
    at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.kt:320)
    at okhttp3.internal.http1.HeadersReader.readLine(HeadersReader.kt:29)
    at okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:178)
    at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at org.sonarqube.ws.client.OkHttpClientBuilder.addHeaders(OkHttpClientBuilder.java:222)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
    at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
    at org.sonarqube.ws.client.HttpConnector.doCall(HttpConnector.java:203)
    ... 128 more
Caused by: java.net.SocketException: Socket closed
    at java.base/java.net.SocketInputStream.read(Unknown Source)
    at java.base/java.net.SocketInputStream.read(Unknown Source)
    at okio.InputStreamSource.read(JvmOkio.kt:90)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:129)
    ... 148 more
ERROR:
ERROR: Re-run SonarScanner using the -X switch to enable full debug logging.
[Pipeline] }

DOCKERFILE running this

FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
  build-essential \
  ca-certificates \
  curl \
  dnsutils \
  g++ \
  gcc \
  git \
  openjdk-11-jdk-headless \
  python \
  python-dev \
  python-pkg-resources \
  python-setuptools \
  python3 \
  python3-dev \
  python3-pip \
  python3-pkg-resources \
  python3-setuptools \
  software-properties-common \
  unzip \
  wget \
  zip \
  zlib1g-dev \
  && rm -rf /var/lib/apt/lists/* && apt-get clean

RUN mkdir /downloads/sonarqube -p
RUN cd /downloads/sonarqube
RUN wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747-linux.zip
RUN unzip sonar-scanner-cli-4.7.0.2747-linux.zip
RUN mv sonar-scanner-4.7.0.2747-linux /opt/sonar-scanner
ENV PATH="$PATH:/opt/sonar-scanner/bin"
RUN rm /sonar-scanner-cli-4.7.0.2747-linux.zip
RUN useradd -ms /bin/bash jenkins
USER jenkins
WORKDIR /home/jenkins


问:
Javascript async await - why is my await not stopping execution of following code until resolved?
I know there are already many questions about promises but I dont understand in my specific case why an await does not stop the execution of following code. In my case its about sending push notifications but mostly about the async/await inside the code.

```<code>const NotificationsService = {
    async notifyFollowers(followers, message) {
        let pushTokens = [];
        const {title, body} = message;
         followers.map(async (follower) => {

> console.log("called 1st 4 times as 4 followers")

             const notification = await this.createNotification(follower._id, message);

>   //called 3rd / last

            console.log("follower.expoPushToken")
            if (!pushTokens.includes(follower.expoPushToken)) {
                pushTokens.push(follower.expoPushToken);
            };

> if I put it here instead, it all works as executed

           // const notification = await this.createNotification(follower._id, message);
            if (follower._id.toString() === notification.to.toString()) {
                ...
            }
        });

>  //called 2nd

        console.log("is this line reached?")
        this.sendPushNotification(pushTokens, title, body);
    },

    async createNotification (to, message) {
        const notification = await Notification.findOneAndUpdate({to:to},
            {$push: {...}}
        )
        return notification;
   },
}
</code>```

so my question is: Shouldnt this await

```<code>const notification = await this.createNotification(follower._id, message)
</code>```

make the execution of following code:

```<code>console.log("follower.expoPushToken")
            if (!pushTokens.includes(follower.expoPushToken)) {
                pushTokens.push(follower.expoPushToken);
            };
</code>```

stop until promise is resolved?

Body:
I know there are already many questions about promises but I dont understand in my specific case why an await does not stop the execution of following code. In my case its about sending push notifications but mostly about the async/await inside the code.

const NotificationsService = {
    async notifyFollowers(followers, message) {
        let pushTokens = [];
        const {title, body} = message;
         followers.map(async (follower) => {

> console.log("called 1st 4 times as 4 followers")

             const notification = await this.createNotification(follower._id, message);

>   //called 3rd / last

            console.log("follower.expoPushToken")
            if (!pushTokens.includes(follower.expoPushToken)) {
                pushTokens.push(follower.expoPushToken);
            };

> if I put it here instead, it all works as executed

           // const notification = await this.createNotification(follower._id, message);
            if (follower._id.toString() === notification.to.toString()) {
                ...
            }
        });

>  //called 2nd

        console.log("is this line reached?")
        this.sendPushNotification(pushTokens, title, body);
    },

    async createNotification (to, message) {
        const notification = await Notification.findOneAndUpdate({to:to},
            {$push: {...}}
        )
        return notification;
   },
}

so my question is: Shouldnt this await

const notification = await this.createNotification(follower._id, message)

make the execution of following code:

console.log("follower.expoPushToken")
            if (!pushTokens.includes(follower.expoPushToken)) {
                pushTokens.push(follower.expoPushToken);
            };

stop until promise is resolved?


问:
How to use 2 EmbedBuilders in 1 slash command? (DiscordJS)
I am trying to use 2 EmbedBuilders in one slash command. So i have 2 embeds that named as embed1 and embed2, but i dont know how to use them in if statement.
I am trying to do :

```<code>if (userRoll > cellRoll)
{ run embed1 }
else
{ run embed2 }
</code>```

What should i type instead of 'run embed1' and 'run embed2'? Can you help? Good morning/evening to everyone.

Body:
I am trying to use 2 EmbedBuilders in one slash command. So i have 2 embeds that named as embed1 and embed2, but i dont know how to use them in if statement.
I am trying to do :

if (userRoll > cellRoll)
{ run embed1 }
else
{ run embed2 }

What should i type instead of 'run embed1' and 'run embed2'? Can you help? Good morning/evening to everyone.


问:
Dash Plotly: What is the best way to plot an image grid of (n_rows, n_cols) images? n_rows needs to be changeable by a user
I am having trouble plotting a grid of images in dash. In particular, I want to create a grid of n_rows x n_cols, where n_cols can be anywhere between 5 and 10 and n_rows need to be user specified. Every image is the same size.

So far, I have used px.imshow() with the facet_col option. However, for a large number of images the images get very small.

I have used plotly.subplots.make_subplots() directly, however, when I change n_rows within the app the images do not stay in their respective positions and get moved around. In particular, when I first choose to plot 5 images beneath each other, the plot will look fine, plotting five images closely together (chosen first). However, when the user subsequently chooses to plot 2 points,
the images will be plotted in the same space the five images were. Similarly, when the user first chooses to plot 2 images the image looks fine. Subsequently, when the user plots 5 images, they all get messed up.

See the following code to reproduce:

```<code>from dash import Dash, dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import dash.exceptions
import numpy as np
from plotly.subplots import make_subplots

def create_fig(n_rows):
    fig = make_subplots(n_rows, 1)

    for i in range(n_rows):
        fig.add_trace(go.Image(z=np.random.randint(0, 255, size=(60, 60, 3))), i+1, j)

    fig.update_layout(autosize=True,
                      width=100,
                      height=n_rows*100,
                      margin=dict(l=0, r=0, b=0, t=0)
                      )
    return fig

def create_fig_using_pximshow(n_rows):
    images = np.random.randint(0, 255, size=(n_rows, 60, 60, 3))
    fig = px.imshow(images, facet_col=0, facet_col_wrap=1, facet_row_spacing=0.3/n_rows)

    fig.update_layout(autosize=True,
                      width=100,
                      height=n_rows*100,
                      margin=dict(l=0, r=0, b=0, t=0)
                      )
    return fig

app = Dash(__name__)
app.layout = html.Div(
    [dcc.Graph(id='graph', style={'overflow':'scroll'}),
     dcc.Input(value=0, id='input', type='number')])

@app.callback(Output('graph', 'figure'), Input('input', 'value'))
def create_graph(n_rows):
    if n_rows == 0:
        raise dash.exceptions.PreventUpdate("Prevent update")
    else:
        if n_rows is not None:

            return create_fig(int(n_rows))
            # return create_fig_using_pximshow(int(n_rows))

if __name__ == '__main__':
    app.run_server(debug=True)

</code>```

Note that changing go.Image to go.Scatter makes the code work and the dashboard graph adapt to the amount of rows present.
Is there a better/easier way to plot a grid of images?

Body:
I am having trouble plotting a grid of images in dash. In particular, I want to create a grid of n_rows x n_cols, where n_cols can be anywhere between 5 and 10 and n_rows need to be user specified. Every image is the same size.

So far, I have used px.imshow() with the facet_col option. However, for a large number of images the images get very small.

I have used plotly.subplots.make_subplots() directly, however, when I change n_rows within the app the images do not stay in their respective positions and get moved around. In particular, when I first choose to plot 5 images beneath each other, the plot will look fine, plotting five images closely together (chosen first). However, when the user subsequently chooses to plot 2 points,
the images will be plotted in the same space the five images were. Similarly, when the user first chooses to plot 2 images the image looks fine. Subsequently, when the user plots 5 images, they all get messed up.

See the following code to reproduce:

from dash import Dash, dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import dash.exceptions
import numpy as np
from plotly.subplots import make_subplots

def create_fig(n_rows):
    fig = make_subplots(n_rows, 1)

    for i in range(n_rows):
        fig.add_trace(go.Image(z=np.random.randint(0, 255, size=(60, 60, 3))), i+1, j)

    fig.update_layout(autosize=True,
                      width=100,
                      height=n_rows*100,
                      margin=dict(l=0, r=0, b=0, t=0)
                      )
    return fig

def create_fig_using_pximshow(n_rows):
    images = np.random.randint(0, 255, size=(n_rows, 60, 60, 3))
    fig = px.imshow(images, facet_col=0, facet_col_wrap=1, facet_row_spacing=0.3/n_rows)

    fig.update_layout(autosize=True,
                      width=100,
                      height=n_rows*100,
                      margin=dict(l=0, r=0, b=0, t=0)
                      )
    return fig

app = Dash(__name__)
app.layout = html.Div(
    [dcc.Graph(id='graph', style={'overflow':'scroll'}),
     dcc.Input(value=0, id='input', type='number')])

@app.callback(Output('graph', 'figure'), Input('input', 'value'))
def create_graph(n_rows):
    if n_rows == 0:
        raise dash.exceptions.PreventUpdate("Prevent update")
    else:
        if n_rows is not None:

            return create_fig(int(n_rows))
            # return create_fig_using_pximshow(int(n_rows))

if __name__ == '__main__':
    app.run_server(debug=True)

Note that changing go.Image to go.Scatter makes the code work and the dashboard graph adapt to the amount of rows present.
Is there a better/easier way to plot a grid of images?


问:
Get the position of the cursor relativ to the cell when mouseover in JointJS
I have an HeaderedRecord with 2 columns and 2 lines per column...so 4 items. Each of these items has an icon and a label. If I do a cell:mouseover I want to show a tooltip depending on which Icon+Label I hover over.

I was able to calculate this with the size of the cell in cell:pointerup, but since x and y are not provided in cell:mouseover, I have no idea how to do this. Is there any way to bind an event listener to the items via the id?

The next Problem is the tooltip. Until now I was only able to bind it to the whole HeaderedRecord, but not to the items.

Maybe HeaderedRecord is not the best choice, but it was the only shape I've found, to accomplish that, even through the customization of the item is very limited. I'm open for any suggestions.


问:
Failed to create provisioning profile in Xcode
I randomly just got this error on a project I've been working on for a while.

Failed to create provisioning profile. There are no devices registered in your account on the developer website. Select a device run destination to have Xcode register it.

and

No profiles for 'com.user.App' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.user.App'.

This just randomly happened while I was trying to preview my program, just as I have done many times before.  It says None Required on provisioning profile and I'm trying to select either Sign to Run Locally or Development under signing certificate and I can't pick either option.

When I clean the project all 97 errors go away, but return when I try and preview the project.  I have been previewing in the simulator but now I have no option to do that for some reason.  It just says "My Mac" and "Any Mac" where "iPhone 11" and other options used to be

Edit: I have updated my project to recommended settings and there was no change.  It is also telling me that there is an error verifying my apple ID but there is nothing for me to verify when I click on the message.

Edit: I clicked the minus button on my Apple ID and xCode immediately quit.  It ran some update and now I "think" its working, except when I tried to log back in it told me that my Apple ID has been locked.


问:
Android reconnect to WebSocket with callbackFlow
I am working on a multiplayer game server. To do that I implemented an okhttp websocket. I use callbackFlow to handle the callback functions like onMessage or onFailure. This is my repo code:

class WebSocketRepository {

    fun socketEventsFlow(): Flow<GameServerResponse> = callbackFlow {

        val socketListener = object : WebSocketListener() {

            override fun onMessage(webSocket: WebSocket, text: String) {
                val message = Gson().fromJson(text, GameServerResponse::class.java)
                trySendBlocking(message)
            }
        }

        attachWebSocketListener(socketListener)
        awaitClose {
            socket.close(1000, "application in Background")
        }
    }

    private fun attachWebSocketListener(listener: WebSocketListener) {
        val client = OkHttpClient()
        val request = Request
            .Builder()
            .url("ws://10.0.2.2:8080")
            .build()

        socket = client.newWebSocket(request, listener)
    }
}
```
<p>I then forward pass this Flow through the viewModel to the Activity to for example launch a new fragment. This is the viewModel's code:</p>
<pre class="lang-kotlin prettyprint-override"><code>class MainActivityViewModel @Inject constructor(
    private val repository: WebSocketRepository
) : ViewModel() {
    val events = repository.socketEventsFlow()
}
</code>```

I finally collect the flow in the activity like this:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainActivityViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.events.collect { event ->
                    //Do stuff here
                }
            }
        }
    }
}
```

There are two problems though.

If the user closes the app (in the background, not fully terminate it), the socket is closed due to the awaitClose statement. I could easily fix that by setting Lifecycle.state.STARTED to Lifecycle.state.CREATED. I worry though that if I do that I would run into problems. For example navigating while the app is in the background. I don't want to create a new socket every time the user closes the app though.

The second problem is the "more important" one. How do I correctly handle reconncetions with this approach? If for example the internet connections drops the server will detect that the client is not there anymore and terminate the connection. I want the app to try to automatically reconnect though. But I have no clue how to implement that. I believe that I would somehow have to re-collect the viewModel's event Flow. But I have no idea on how to actually do that. Is there a better way to handle reconnections?

Body:
I am working on a multiplayer game server. To do that I implemented an okhttp websocket. I use callbackFlow to handle the callback functions like onMessage or onFailure. This is my repo code:

class WebSocketRepository {

    fun socketEventsFlow(): Flow<GameServerResponse> = callbackFlow {

        val socketListener = object : WebSocketListener() {

            override fun onMessage(webSocket: WebSocket, text: String) {
                val message = Gson().fromJson(text, GameServerResponse::class.java)
                trySendBlocking(message)
            }
        }

        attachWebSocketListener(socketListener)
        awaitClose {
            socket.close(1000, "application in Background")
        }
    }

    private fun attachWebSocketListener(listener: WebSocketListener) {
        val client = OkHttpClient()
        val request = Request
            .Builder()
            .url("ws://10.0.2.2:8080")
            .build()

        socket = client.newWebSocket(request, listener)
    }
}

I then forward pass this Flow through the viewModel to the Activity to for example launch a new fragment. This is the viewModel's code:

class MainActivityViewModel @Inject constructor(
    private val repository: WebSocketRepository
) : ViewModel() {
    val events = repository.socketEventsFlow()
}

I finally collect the flow in the activity like this:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainActivityViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.events.collect { event ->
                    //Do stuff here
                }
            }
        }
    }
}

There are two problems though.

If the user closes the app (in the background, not fully terminate it), the socket is closed due to the awaitClose statement. I could easily fix that by setting Lifecycle.state.STARTED to Lifecycle.state.CREATED. I worry though that if I do that I would run into problems. For example navigating while the app is in the background. I don't want to create a new socket every time the user closes the app though.

The second problem is the "more important" one. How do I correctly handle reconncetions with this approach? If for example the internet connections drops the server will detect that the client is not there anymore and terminate the connection. I want the app to try to automatically reconnect though. But I have no clue how to implement that. I believe that I would somehow have to re-collect the viewModel's event Flow. But I have no idea on how to actually do that. Is there a better way to handle reconnections?


问:
Formalize english question into a knowledge base using ALC formulas
I have the following four sentences:

Mary is a person.

Bulldog is a specie of dog. French bulldog is a specie of bulldog.

The only kind of dog that Mary owns is French bulldog.

A French is a person who owns only bulldog dogs.

I would like to formalize those into a Knowledge Base KB.

I will right below my approach and will also post some questions.

```<code>Concepts = Person, Dog, Bulldog
Individuals = MARY, FRENCHBULLDOG, BULLDOG
Roles = ownsDog

ABox = { Person(MARY),
         Dog(BULLDOG),
         Bulldog(FRENCHBULLDOG),
         Person ⨅∀ ownsDog.Bulldog{FRENCHBULLDOG}(MARY), (1)
         ownsDog(MARY, FRENCHBULLDOG) (2)
}

TBox = { French ≡ Person⨅∀ownsDog.Bulldog, Bulldog ⊆ Dog }
</code>```

First I would like to know if the Knowledge Base is correct. And also if I should keep the axiom (1) or (2) or both of them.

Body:
I have the following four sentences:

Mary is a person.

Bulldog is a specie of dog. French bulldog is a specie of bulldog.

The only kind of dog that Mary owns is French bulldog.

A French is a person who owns only bulldog dogs.

I would like to formalize those into a Knowledge Base KB.

I will right below my approach and will also post some questions.

Concepts = Person, Dog, Bulldog
Individuals = MARY, FRENCHBULLDOG, BULLDOG
Roles = ownsDog

ABox = { Person(MARY),
         Dog(BULLDOG),
         Bulldog(FRENCHBULLDOG),
         Person ⨅∀ ownsDog.Bulldog{FRENCHBULLDOG}(MARY), (1)
         ownsDog(MARY, FRENCHBULLDOG) (2)
}

TBox = { French ≡ Person⨅∀ownsDog.Bulldog, Bulldog ⊆ Dog }

First I would like to know if the Knowledge Base is correct. And also if I should keep the axiom (1) or (2) or both of them.


问:
A simple CSS code for hamburger Icon that shows content when I focus or hover on it
I have created a hamburger menu icon i need a css code that will show the menu content when I hover on the icon

Like I said previously I have e created the hamburger code just need a css code to display the content when I hover or focus on the icon


问:
Request not accepting Authorization header for every second request

Description

I have an API which I have created and I have some endpoints protected. The problem I am facing now on the client making a request is that the first request comes through with the Authorization header provided but a second request is blocked because Authorization is not present.
I can confirm that Authorization is present and worked perfectly when I was running Typescript till I recreated the endpoints in Go with Gin.

How to reproduce

Call estimate endpoint from client (iOS app) response succeceds

Make a second call from Client (iOS app) response failed because it is not taking the Authorization header which contains token

```<code>package main

import (
    "github.com/gin-gonic/gin"
)

type App struct {
    Router   *gin.Engine
    Gateman  *gateman.Gateman
    Database *mongo.Client
}

func (a *App) StartApp() {

    err := godotenv.Load()
    if err != nil {
        fmt.Printf("Could not load .env \n")
    }

    a.Database = database.DB
    a.Router = gin.New()

    a.Gateman = middleware.Gateman()
    a.Router.Use(gin.Recovery())

    a.Router.Use(middleware.DefaultHelmet())

    a.Router.Use(middleware.GinContextToContextMiddleware())
    a.Router.Use(middleware.RequestID(nil))
    a.Router.Use(middleware.ErrorHandler())
    a.Router.Use(middleware.Logger("package-service"))

    connection, err := amqp091.Dial(os.Getenv("AMQP_URL"))

    if err != nil {
        log.Fatal(fmt.Printf("Error on dial %v\n", err.Error()))
    }
    routes.Routes(a.Router, database.GetDatabase(a.Database), a.Gateman, connection)

}

func (a *App) Run(addr string) {
    logs := log.New(os.Stdout, "package-service", log.LstdFlags)

    server := &http.Server{
        Addr:         addr,
        Handler:      a.Router,
        ErrorLog:     logs,
        IdleTimeout:  120 * time.Second, // max time for connections using TCP Keep-Alive
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    go func() {
        if err := server.ListenAndServe(); err != nil {
            logs.Fatal(err)
        }
    }()

    // trap sigterm or interrupt and gracefully shutdown the server
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt)
    signal.Notify(c, os.Kill)

    sig := <-c
    logs.Println("Recieved terminate, graceful shutdown", sig)
    tc, _ := context.WithTimeout(context.Background(), 30*time.Second)
    server.Shutdown(tc)
}

func Routes(r *gin.Engine, db *mongo.Database, g *gateman.Gateman, conn *amqp091.Connection) {

    atHandler := pc.NewPackagesController(ps.NewPackagesService(pr.NewPackagesRepository(db)), g, events.NewEventEmitter(conn))

    r.Use(CORS())
    v1 := r.Group("/api/v1/package")
    {
        v1.POST("/query", GraphqlHandler(db, directives.NewDirectivesManager(g)))
        v1.GET("/", PlaygroundHandler(db))
        v1.POST("/", g.Guard([]string{"user"}, nil), atHandler.Create)
        v1.POST("/estimate", g.Guard([]string{"user"}, nil), atHandler.Estimate)
        v1.PUT("/:packageID", g.Guard([]string{"user", "admin"}, nil), atHandler.Update)
        v1.PUT("/:packageID/assign", g.Guard([]string{"admin"}, nil), atHandler.Assign)
        v1.POST("/:packageID/cancel", g.Guard([]string{"user", "admin"}, nil), atHandler.CancelRequest)
        v1.POST("/:packageID/complete", g.Guard([]string{"admin"}, nil), atHandler.Complete)
        v1.POST("/:packageID/reject", g.Guard([]string{"admin"}, nil), atHandler.RejectRequest)

        v1.GET("/healthz", atHandler.GetHealth)

    }
    r.GET("/", atHandler.GetUP)
}

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

func main() {
    start := App{}
    start.StartApp()
    start.Run(":3009")
}
</code>```

Expectations

All endpoints that are Guarded simply checks the header for Authorization and if provided in the request, it should be successful

Actual result

First request succeed /estimate
Second request / POST request fails to accept Authorization header

Also irrespective of what the first post request is, the second post request just never accept the Authorization header

Also need to mention that I do not have this issue with postman. Both request run independently but using another client for the request, gives this problem

Environment

go version: 1.19

gin version (or commit ref): v1.8.1

operating system: Mac and iOS mobile

Here is my client code

```<code>func request<T>(with builder: BaseRequest) -> AnyPublisher<T, APIError> where T: Codable {
        request(with: builder, customDecoder: JSONDecoder())
    }
    func request<T>(with builder: BaseRequest, customDecoder: JSONDecoder) -> AnyPublisher<T, APIError> where T: Codable {

        let encoding: ParametersEncoder = [.get, .delete].contains(builder.method) ? URLParameretersEncoder() : JSONParametersEncoder()
        customDecoder.keyDecodingStrategy = .convertFromSnakeCase
        var url: URL {
            var components = URLComponents()
            components.scheme = "https"
            components.host = builder.baseUrl
            components.path = "/api/v1" + builder.path

            guard let url = components.url else {
                preconditionFailure("Invalid URL components: \(components)")
            }

            return url
        }
        var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 46.0)
        urlRequest.httpMethod = builder.method.rawValue
        builder.headers.forEach { key, value in
            urlRequest.setValue(value, forHTTPHeaderField: key)
        }
        if let token = tokenManager.token {
            urlRequest.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
//            urlRequest.setValue("ABC", forHTTPHeaderField: "testing123")
        }

        if let parameters = builder.parameters {
            guard let encoded = try? encoding.encode(parameters: parameters, in: urlRequest) else {
                fatalError()
            }
            urlRequest = encoded
        }
        self.log(request: urlRequest)
        return URLSession.shared
            .dataTaskPublisher(for: urlRequest)
            .receive(on: DispatchQueue.main)
            .mapError {_  -> APIError in
                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                return .unknown

            }
            .flatMap { data, response -> AnyPublisher<T, APIError> in
                guard let response = response as? HTTPURLResponse else {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    return Fail(error: APIError.invalidResponse).eraseToAnyPublisher()
                }
                self.log(response: response, data: data, error: nil)
                if (200...299).contains(response.statusCode) {
                    return Just(data)
                        .decode(type: T.self, decoder: customDecoder)
//                        .map {
//                            print($0)
//                            return $0
//                        } //added
                        .mapError {
                            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                            return .decodingError(underlyingError: $0)

                        }

                        .eraseToAnyPublisher()
                } else {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    if response.statusCode == 401 {
                        // Send notification to remove corrdinator and return to root
//                        rxNotificationCenter.post(.invalidToken)
                    }
                    guard let errorResponse = try? customDecoder.decode(BaseResponse.self, from: data) else {
                        return Fail(error: APIError.decodingError(underlyingError: NSError("Can't decode error"))).eraseToAnyPublisher()
                    }
                    return Fail(error: APIError.server(response: errorResponse))
                        .eraseToAnyPublisher()
                }
            }
            .eraseToAnyPublisher()
    }

protocol BaseRequest {
    var baseUrl: String { get }
    var path: String { get }
    var headers: HTTPHeaders { get }
    var method: HTTPRequestMethod { get }
    var parameters: HTTPParameters { get }
}

public typealias HTTPHeaders = [String: String]
public typealias HTTPParameters = [String: Any]?
</code>```

Another point, calling a single endpoint multiple time, works fine, calling a different one is where the header is rejected

Body:
Description

I have an API which I have created and I have some endpoints protected. The problem I am facing now on the client making a request is that the first request comes through with the Authorization header provided but a second request is blocked because Authorization is not present.
I can confirm that Authorization is present and worked perfectly when I was running Typescript till I recreated the endpoints in Go with Gin.

How to reproduce

Call estimate endpoint from client (iOS app) response succeceds

Make a second call from Client (iOS app) response failed because it is not taking the Authorization header which contains token

package main

import (
    "github.com/gin-gonic/gin"
)

type App struct {
    Router   *gin.Engine
    Gateman  *gateman.Gateman
    Database *mongo.Client
}

func (a *App) StartApp() {

    err := godotenv.Load()
    if err != nil {
        fmt.Printf("Could not load .env \n")
    }

    a.Database = database.DB
    a.Router = gin.New()

    a.Gateman = middleware.Gateman()
    a.Router.Use(gin.Recovery())

    a.Router.Use(middleware.DefaultHelmet())

    a.Router.Use(middleware.GinContextToContextMiddleware())
    a.Router.Use(middleware.RequestID(nil))
    a.Router.Use(middleware.ErrorHandler())
    a.Router.Use(middleware.Logger("package-service"))

    connection, err := amqp091.Dial(os.Getenv("AMQP_URL"))

    if err != nil {
        log.Fatal(fmt.Printf("Error on dial %v\n", err.Error()))
    }
    routes.Routes(a.Router, database.GetDatabase(a.Database), a.Gateman, connection)

}

func (a *App) Run(addr string) {
    logs := log.New(os.Stdout, "package-service", log.LstdFlags)

    server := &http.Server{
        Addr:         addr,
        Handler:      a.Router,
        ErrorLog:     logs,
        IdleTimeout:  120 * time.Second, // max time for connections using TCP Keep-Alive
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
    }

    go func() {
        if err := server.ListenAndServe(); err != nil {
            logs.Fatal(err)
        }
    }()

    // trap sigterm or interrupt and gracefully shutdown the server
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt)
    signal.Notify(c, os.Kill)

    sig := <-c
    logs.Println("Recieved terminate, graceful shutdown", sig)
    tc, _ := context.WithTimeout(context.Background(), 30*time.Second)
    server.Shutdown(tc)
}

func Routes(r *gin.Engine, db *mongo.Database, g *gateman.Gateman, conn *amqp091.Connection) {

    atHandler := pc.NewPackagesController(ps.NewPackagesService(pr.NewPackagesRepository(db)), g, events.NewEventEmitter(conn))

    r.Use(CORS())
    v1 := r.Group("/api/v1/package")
    {
        v1.POST("/query", GraphqlHandler(db, directives.NewDirectivesManager(g)))
        v1.GET("/", PlaygroundHandler(db))
        v1.POST("/", g.Guard([]string{"user"}, nil), atHandler.Create)
        v1.POST("/estimate", g.Guard([]string{"user"}, nil), atHandler.Estimate)
        v1.PUT("/:packageID", g.Guard([]string{"user", "admin"}, nil), atHandler.Update)
        v1.PUT("/:packageID/assign", g.Guard([]string{"admin"}, nil), atHandler.Assign)
        v1.POST("/:packageID/cancel", g.Guard([]string{"user", "admin"}, nil), atHandler.CancelRequest)
        v1.POST("/:packageID/complete", g.Guard([]string{"admin"}, nil), atHandler.Complete)
        v1.POST("/:packageID/reject", g.Guard([]string{"admin"}, nil), atHandler.RejectRequest)

        v1.GET("/healthz", atHandler.GetHealth)

    }
    r.GET("/", atHandler.GetUP)
}

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

func main() {
    start := App{}
    start.StartApp()
    start.Run(":3009")
}

Expectations

All endpoints that are Guarded simply checks the header for Authorization and if provided in the request, it should be successful

Actual result

First request succeed /estimate
Second request / POST request fails to accept Authorization header

Also irrespective of what the first post request is, the second post request just never accept the Authorization header

Also need to mention that I do not have this issue with postman. Both request run independently but using another client for the request, gives this problem

Environment

go version: 1.19

gin version (or commit ref): v1.8.1

operating system: Mac and iOS mobile

Here is my client code

func request<T>(with builder: BaseRequest) -> AnyPublisher<T, APIError> where T: Codable {
        request(with: builder, customDecoder: JSONDecoder())
    }
    func request<T>(with builder: BaseRequest, customDecoder: JSONDecoder) -> AnyPublisher<T, APIError> where T: Codable {

        let encoding: ParametersEncoder = [.get, .delete].contains(builder.method) ? URLParameretersEncoder() : JSONParametersEncoder()
        customDecoder.keyDecodingStrategy = .convertFromSnakeCase
        var url: URL {
            var components = URLComponents()
            components.scheme = "https"
            components.host = builder.baseUrl
            components.path = "/api/v1" + builder.path

            guard let url = components.url else {
                preconditionFailure("Invalid URL components: \(components)")
            }

            return url
        }
        var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 46.0)
        urlRequest.httpMethod = builder.method.rawValue
        builder.headers.forEach { key, value in
            urlRequest.setValue(value, forHTTPHeaderField: key)
        }
        if let token = tokenManager.token {
            urlRequest.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
//            urlRequest.setValue("ABC", forHTTPHeaderField: "testing123")
        }

        if let parameters = builder.parameters {
            guard let encoded = try? encoding.encode(parameters: parameters, in: urlRequest) else {
                fatalError()
            }
            urlRequest = encoded
        }
        self.log(request: urlRequest)
        return URLSession.shared
            .dataTaskPublisher(for: urlRequest)
            .receive(on: DispatchQueue.main)
            .mapError {_  -> APIError in
                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                return .unknown

            }
            .flatMap { data, response -> AnyPublisher<T, APIError> in
                guard let response = response as? HTTPURLResponse else {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    return Fail(error: APIError.invalidResponse).eraseToAnyPublisher()
                }
                self.log(response: response, data: data, error: nil)
                if (200...299).contains(response.statusCode) {
                    return Just(data)
                        .decode(type: T.self, decoder: customDecoder)
//                        .map {
//                            print($0)
//                            return $0
//                        } //added
                        .mapError {
                            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                            return .decodingError(underlyingError: $0)

                        }

                        .eraseToAnyPublisher()
                } else {
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    if response.statusCode == 401 {
                        // Send notification to remove corrdinator and return to root
//                        rxNotificationCenter.post(.invalidToken)
                    }
                    guard let errorResponse = try? customDecoder.decode(BaseResponse.self, from: data) else {
                        return Fail(error: APIError.decodingError(underlyingError: NSError("Can't decode error"))).eraseToAnyPublisher()
                    }
                    return Fail(error: APIError.server(response: errorResponse))
                        .eraseToAnyPublisher()
                }
            }
            .eraseToAnyPublisher()
    }

protocol BaseRequest {
    var baseUrl: String { get }
    var path: String { get }
    var headers: HTTPHeaders { get }
    var method: HTTPRequestMethod { get }
    var parameters: HTTPParameters { get }
}

public typealias HTTPHeaders = [String: String]
public typealias HTTPParameters = [String: Any]?

Another point, calling a single endpoint multiple time, works fine, calling a different one is where the header is rejected