问:
Correct way to pass function in reactjs with hooks
Hello I have a question about the correct way to pass a function to a children
Basically in my highest level component I have a theme:

```<code>export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {});

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <Header />
      </div>
    </ThemeProvider>
  );
}
</code>```

this is my custom hook for get and set theme:

```<code>export default function useAppTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}
</code>```

and then in my component header I use useTheme from EMOTION Theme

```<code>const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
      <TopHeader theme={Theme} />
      <NavBar theme={Theme} />
    </Container>
  );
};
</code>```

and then I have a component that is a child of my header where I need my setTheme function to change the theme:

```<code>const ItemsTop = props => {
  return (
    <WrapperTop
      justify={'space-between'}
      align={'center'}
      flexdirection={'row'}
    >
      <img src={LogoImg} />
      <SearchContainer>
        <div>
          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />
        </div>
        <input placeholder="Pesquisar"></input>
      </SearchContainer>

      <AccessibilityTwo>
        <FontAwesomeIcon
          className="adjust"
          icon={faAdjust}
          size="1x"
          fixedWidth
          color="white"
        />
        <FontAwesomeIcon
          icon={faTextHeight}
          size="1x"
          fixedWidth
          color="white"
        />
      </AccessibilityTwo>
    </WrapperTop>
  );
};
</code>```

So I would like to know what is the correct way to pass my setTheme function from my custom hook to the children of my component Header

答:
I don't know how you are using the ItemsTop component, but imagine you call it in the Header:

```<code>const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
       ...
      <ItemsTop setTheme={props.setTheme}/>
    </Container>
  );
};
</code>```

The code above is passing the function setTheme to the props of ItemsTop, but for this function to be present in the props of Header you have to pass it like:

```<code>export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {});

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <Header setTheme={setTheme} />
      </div>
    </ThemeProvider>
  );
}
</code>```

Finally, you can use it in ItemsTop accessing props: props.setTheme

Body:
Hello I have a question about the correct way to pass a function to a children
Basically in my highest level component I have a theme:

export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {});

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

    </ThemeProvider>
  );
}

this is my custom hook for get and set theme:

export default function useAppTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

and then in my component header I use useTheme from EMOTION Theme

const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
      <TopHeader theme={Theme} />
      <NavBar theme={Theme} />
    </Container>
  );
};

and then I have a component that is a child of my header where I need my setTheme function to change the theme:

const ItemsTop = props => {
  return (
    <WrapperTop
      justify={'space-between'}
      align={'center'}
      flexdirection={'row'}
    >

      <SearchContainer>

          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />

        <input placeholder="Pesquisar"></input>
      </SearchContainer>

      <AccessibilityTwo>
        <FontAwesomeIcon
          className="adjust"
          icon={faAdjust}
          size="1x"
          fixedWidth
          color="white"
        />
        <FontAwesomeIcon
          icon={faTextHeight}
          size="1x"
          fixedWidth
          color="white"
        />
      </AccessibilityTwo>
    </WrapperTop>
  );
};

So I would like to know what is the correct way to pass my setTheme function from my custom hook to the children of my component Header

Body:
I don't know how you are using the ItemsTop component, but imagine you call it in the Header:

const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
       ...
      <ItemsTop setTheme={props.setTheme}/>
    </Container>
  );
};

The code above is passing the function setTheme to the props of ItemsTop, but for this function to be present in the props of Header you have to pass it like:

export default function App() {
  const { theme, setTheme } = useAppTheme();

  useEffect(() => {});

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <Header setTheme={setTheme} />
      </div>
    </ThemeProvider>
  );
}

Finally, you can use it in ItemsTop accessing props: props.setTheme


来源: stackexchange

问:
Kubernetes - How to setup parallels clusters (Prod, Dev) sharing the same repositories/pipeline
I am currently facing a situation where I need to deploy a small cluster (only 4 pods for now) which will be containing 4 different microservices. This cluster has to be duplicated so I can have one PRODUCTION cluster and one DEVELOPMENT cluster.

Even if it's not hard from my point of view (Creating a cluster and then uploading docker images to pods with parameters in order to use the right resources connection strings), I am stuck at the CD/CI part..

From a CloudBuild trigger, how to push the Docker image to the right "cluster's pod", I have absolutely no idea AT ALL how to achieve it...

There is my cloudbuild.yaml

```<code>steps:
  #step 1 - Getting the previous (current) image
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args: [
      '-c',
      'docker pull gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest || exit 0'
    ]
  #step 2 - Build the image and push it to gcr.io
  - name: 'gcr.io/cloud-builders/docker'
    args: [
      'build',
      '-t',
      'gcr.io/{PROJECT_ID}/{SERVICE_NAME}',
      '-t',
      'gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest',
      '.'
    ]
  #step 3 - Deploy our container to our cluster
  - name: 'gcr.io/cloud-builders/kubectl'
    args: ['apply', '-f', 'service.yaml', '--force']
    env:
      - 'CLOUDSDK_COMPUTE_ZONE={CLUSTER_ZONE}'
      - 'CLOUDSDK_CONTAINER_CLUSTER={CLUSTER_NAME}'
  #step 4 - Set the image
  - name: 'gcr.io/cloud-builders/kubectl'
    args: [
      'set',
      'image',
      'deployment',
      '{SERVICE_NAME}',
      '{SERVICE_NAME}=gcr.io/{PROJECT_ID}/{SERVICE_NAME}'
    ]
    env:
      - 'CLOUDSDK_COMPUTE_ZONE={CLUSTER_ZONE}'
      - 'CLOUDSDK_CONTAINER_CLUSTER={CLUSTER_NAME}'
# push images to Google Container Registry with tags
images: [
  'gcr.io/{PROJECT_ID}/{SERVICE_NAME}',
  'gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest'
]
</code>```

Can anyone help me out? I don't really know in which direction to go to..

答:
So my question is:

How are you triggering these builds? Manually? GitHub Trigger? HTTP Trigger using the REST API?

so you're almost there for the building/pushing part, you would need to use substitution variables https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values

If you would be triggering the builds manually, you would edit the build trigger and change the sub variable for what you want it to be.
GitHub Trigger -- this is a little more complex as you might want to do releases or branches.
HTTP Trigger, same as manual, in your request you change the sub variable.

So here's part of one of our repo build files, as you will see there are different sub. variables we use, sometimes we want to build the image AND deploy to cluster, other times we just want to build or deploy.

```<code>steps:
# pull docker image
- name: 'gcr.io/cloud-builders/docker'
  id: pull-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    docker pull $${_TAG_DOCKER_IMAGE} || exit 0

# build docker image
- name: 'gcr.io/cloud-builders/docker'
  id: build-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_BUILD_IMAGE}" == "true" ]]; then
       docker build -t ${_DOCKER_IMAGE_TAG} --cache-from $${_TAG_DOCKER_IMAGE} .;
    else
       echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
    fi

# push docker image
- name: 'gcr.io/cloud-builders/docker'
  id: push-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
     if [[ "${_BUILD_IMAGE}" == "true" ]]; then
        docker push ${_DOCKER_IMAGE_TAG};
     else
        echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
     fi

# tag docker image
- name: 'gcr.io/cloud-builders/gcloud'
  id: tag-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_BUILD_IMAGE}" == "true" ]]; then
       gcloud container images add-tag ${_DOCKER_IMAGE_TAG} $${_TAG_DOCKER_IMAGE} -q;
    else
       echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
    fi

# update service image on environment
- name: 'gcr.io/cloud-builders/kubectl'
  id: update service deployment image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_UPDATE_CLUSTER}" == "true" ]]; then
       /builder/kubectl.bash set image deployment $REPO_NAME master=${_DOCKER_IMAGE_TAG} --namespace=${_DEFAULT_NAMESPACE};
    else
       echo "skipping ... UPDATE_CLUSTER=${_UPDATE_CLUSTER}";
    fi
  env:
  - 'CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}'
  - 'CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}'

# subs are needed because of our different ENVs
# _DOCKER_IMAGE_TAG = ['gcr.io/$PROJECT_ID/$REPO_NAME:gcb-${_COMPANY_ENV}-$SHORT_SHA', 'other']
# _COMPANY_ENV = ['dev', 'staging', 'prod']
# _DEFAULT_NAMESPACE = ['default'] or ['custom1', 'custom2']
# _CLOUDSDK_CONTAINER_CLUSTER = ['dev', 'prod']
# _CLOUDSDK_COMPUTE_ZONE = ['us-central1-a']
# _BUILD_IMAGE = ['true', 'false']
# _UPDATE_CLUSTER = ['true', 'false']
substitutions:
    _DOCKER_IMAGE_TAG: $DOCKER_IMAGE_TAG
    _COMPANY_ENV: dev
    _DEFAULT_NAMESPACE: default
    _CLOUDSDK_CONTAINER_CLUSTER: dev
    _CLOUDSDK_COMPUTE_ZONE: us-central1-a
    _BUILD_IMAGE: 'true'
    _UPDATE_CLUSTER: 'true'
options:
    substitution_option: 'ALLOW_LOOSE'
    env:
    - _TAG_DOCKER_IMAGE=gcr.io/$PROJECT_ID/$REPO_NAME:${_COMPANY_ENV}-latest
    - DOCKER_IMAGE_TAG=gcr.io/$PROJECT_ID/$REPO_NAME:gcb-${_COMPANY_ENV}-$SHORT_SHA
tags:
- '${_COMPANY_ENV}'
- 'build-${_BUILD_IMAGE}'
- 'update-${_UPDATE_CLUSTER}'
</code>```

we have two workflows --

github trigger builds and deploys under the 'dev' environment.

we trigger via REST API https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds/create (we replace the variables via the request.json) -- this method also works using the gcloud builds --substitutions CLI.

Hope that answers your question!

ContentLicense: CC BY-SA 4.0

Body:
I am currently facing a situation where I need to deploy a small cluster (only 4 pods for now) which will be containing 4 different microservices. This cluster has to be duplicated so I can have one PRODUCTION cluster and one DEVELOPMENT cluster.

Even if it's not hard from my point of view (Creating a cluster and then uploading docker images to pods with parameters in order to use the right resources connection strings), I am stuck at the CD/CI part..

From a CloudBuild trigger, how to push the Docker image to the right "cluster's pod", I have absolutely no idea AT ALL how to achieve it...

There is my cloudbuild.yaml

steps:
  #step 1 - Getting the previous (current) image
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args: [
      '-c',
      'docker pull gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest || exit 0'
    ]
  #step 2 - Build the image and push it to gcr.io
  - name: 'gcr.io/cloud-builders/docker'
    args: [
      'build',
      '-t',
      'gcr.io/{PROJECT_ID}/{SERVICE_NAME}',
      '-t',
      'gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest',
      '.'
    ]
  #step 3 - Deploy our container to our cluster
  - name: 'gcr.io/cloud-builders/kubectl'
    args: ['apply', '-f', 'service.yaml', '--force']
    env:
      - 'CLOUDSDK_COMPUTE_ZONE={CLUSTER_ZONE}'
      - 'CLOUDSDK_CONTAINER_CLUSTER={CLUSTER_NAME}'
  #step 4 - Set the image
  - name: 'gcr.io/cloud-builders/kubectl'
    args: [
      'set',
      'image',
      'deployment',
      '{SERVICE_NAME}',
      '{SERVICE_NAME}=gcr.io/{PROJECT_ID}/{SERVICE_NAME}'
    ]
    env:
      - 'CLOUDSDK_COMPUTE_ZONE={CLUSTER_ZONE}'
      - 'CLOUDSDK_CONTAINER_CLUSTER={CLUSTER_NAME}'
# push images to Google Container Registry with tags
images: [
  'gcr.io/{PROJECT_ID}/{SERVICE_NAME}',
  'gcr.io/{PROJECT_ID}/{SERVICE_NAME}:latest'
]

Can anyone help me out? I don't really know in which direction to go to..

Body:
So my question is:

How are you triggering these builds? Manually? GitHub Trigger? HTTP Trigger using the REST API?

so you're almost there for the building/pushing part, you would need to use substitution variables https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values

If you would be triggering the builds manually, you would edit the build trigger and change the sub variable for what you want it to be.
GitHub Trigger -- this is a little more complex as you might want to do releases or branches.
HTTP Trigger, same as manual, in your request you change the sub variable.

So here's part of one of our repo build files, as you will see there are different sub. variables we use, sometimes we want to build the image AND deploy to cluster, other times we just want to build or deploy.

steps:
# pull docker image
- name: 'gcr.io/cloud-builders/docker'
  id: pull-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    docker pull $${_TAG_DOCKER_IMAGE} || exit 0

# build docker image
- name: 'gcr.io/cloud-builders/docker'
  id: build-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_BUILD_IMAGE}" == "true" ]]; then
       docker build -t ${_DOCKER_IMAGE_TAG} --cache-from $${_TAG_DOCKER_IMAGE} .;
    else
       echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
    fi

# push docker image
- name: 'gcr.io/cloud-builders/docker'
  id: push-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
     if [[ "${_BUILD_IMAGE}" == "true" ]]; then
        docker push ${_DOCKER_IMAGE_TAG};
     else
        echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
     fi

# tag docker image
- name: 'gcr.io/cloud-builders/gcloud'
  id: tag-docker-image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_BUILD_IMAGE}" == "true" ]]; then
       gcloud container images add-tag ${_DOCKER_IMAGE_TAG} $${_TAG_DOCKER_IMAGE} -q;
    else
       echo "skipping ... BUILD_IMAGE=${_BUILD_IMAGE}";
    fi

# update service image on environment
- name: 'gcr.io/cloud-builders/kubectl'
  id: update service deployment image
  entrypoint: 'bash'
  args:
  - '-c'
  - |
    if [[ "${_UPDATE_CLUSTER}" == "true" ]]; then
       /builder/kubectl.bash set image deployment $REPO_NAME master=${_DOCKER_IMAGE_TAG} --namespace=${_DEFAULT_NAMESPACE};
    else
       echo "skipping ... UPDATE_CLUSTER=${_UPDATE_CLUSTER}";
    fi
  env:
  - 'CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}'
  - 'CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}'

# subs are needed because of our different ENVs
# _DOCKER_IMAGE_TAG = ['gcr.io/$PROJECT_ID/$REPO_NAME:gcb-${_COMPANY_ENV}-$SHORT_SHA', 'other']
# _COMPANY_ENV = ['dev', 'staging', 'prod']
# _DEFAULT_NAMESPACE = ['default'] or ['custom1', 'custom2']
# _CLOUDSDK_CONTAINER_CLUSTER = ['dev', 'prod']
# _CLOUDSDK_COMPUTE_ZONE = ['us-central1-a']
# _BUILD_IMAGE = ['true', 'false']
# _UPDATE_CLUSTER = ['true', 'false']
substitutions:
    _DOCKER_IMAGE_TAG: $DOCKER_IMAGE_TAG
    _COMPANY_ENV: dev
    _DEFAULT_NAMESPACE: default
    _CLOUDSDK_CONTAINER_CLUSTER: dev
    _CLOUDSDK_COMPUTE_ZONE: us-central1-a
    _BUILD_IMAGE: 'true'
    _UPDATE_CLUSTER: 'true'
options:
    substitution_option: 'ALLOW_LOOSE'
    env:
    - _TAG_DOCKER_IMAGE=gcr.io/$PROJECT_ID/$REPO_NAME:${_COMPANY_ENV}-latest
    - DOCKER_IMAGE_TAG=gcr.io/$PROJECT_ID/$REPO_NAME:gcb-${_COMPANY_ENV}-$SHORT_SHA
tags:
- '${_COMPANY_ENV}'
- 'build-${_BUILD_IMAGE}'
- 'update-${_UPDATE_CLUSTER}'

we have two workflows --

github trigger builds and deploys under the 'dev' environment.

we trigger via REST API https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds/create (we replace the variables via the request.json) -- this method also works using the gcloud builds --substitutions CLI.

Hope that answers your question!


问:
How do I get the name of the request's content file from a master page?
In my SiteMaster.cs file I have the following snippet:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    pageName.Text = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
}
</code>```

The idea with this is on my SiteMaster I can display the current file name by using:

```<code><asp:Label ID="pageName" runat="server" />
</code>```

However, I'd like to use pageName in an if statement.
For example, like this

```<code>if (pageName == 'default.aspx')
Then  Response.Write ("test")
End if //pseudo code
</code>```

Is this possible or am I doing it the wrong way?

答:
Use this for retrieving Current page name from master page like</p>

```<code>String pageName  = Request.FilePath;

//return like that /example.aspx

if (pageName == "/default.aspx")
{
// your code
}
</code>```

Body:
In my SiteMaster.cs file I have the following snippet:

protected void Page_Load(object sender, EventArgs e)
{
    pageName.Text = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
}

The idea with this is on my SiteMaster I can display the current file name by using:

<asp:Label ID="pageName" runat="server" />

However, I'd like to use pageName in an if statement.
For example, like this

if (pageName == 'default.aspx')
Then  Response.Write ("test")
End if //pseudo code

Is this possible or am I doing it the wrong way?

Body:
Use this for retrieving Current page name from master page like

String pageName  = Request.FilePath;

//return like that /example.aspx

if (pageName == "/default.aspx")
{
// your code
}

ContentLicense: CC BY-SA 3.0


问:
how to execute shell command files in python
I am having trouble executing the following shell command.  I'm in windows 10.  I had to delete the user authorization here and left it as 'tktk' as i dind't want my authorization out here like that.

```<code>curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json' -H 'authorization: tktk' -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' -H 'content-type: application/json' -H 'origin: https://akita.etflogic.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'referer: https://akita.etflogic.com/portfolio-analysis' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9' --data-binary '{"portfolio":{"currency":"usd","id":"8576e266-c6f4-44fe-a6a6-9c64869b55dd","name":"test1","records":[{"locale":"US","id":"df92931e-3063-4889-8e4b-100c66f14d22","name":"SSGA SPDR S&P 500 - SSgA Active Trust","secid":549535,"size":100,"ticker":"SPY US"}],"size_type":"notional","type":"primary"}}' --compressed > /tmp/jsonpayload
</code>```

I stored the above command in a test.sh file
I'm having trouble executing the above shell command.  It works on the linux terminal.  But it doesn't work on my windows cmd.  I need to read the above url, get the json object and do some analysis with it.

What i tried:

```<code>import subprocess
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])
</code>```

This fails.  ok...

I tried then...

```<code>subprocess.call(['test.sh'])
</code>```

I'm getting error '%1 is not a valid Win32 application'

答:
try: </p>

```<code># Importing the necessary packages
$ from subprocess import call

# Executing the test.sh script
$ call('sh test.sh 2>/dev/null', shell=True)
</code>```

Body:
I am having trouble executing the following shell command.  I'm in windows 10.  I had to delete the user authorization here and left it as 'tktk' as i dind't want my authorization out here like that.

curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json' -H 'authorization: tktk' -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' -H 'content-type: application/json' -H 'origin: https://akita.etflogic.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'referer: https://akita.etflogic.com/portfolio-analysis' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9' --data-binary '{"portfolio":{"currency":"usd","id":"8576e266-c6f4-44fe-a6a6-9c64869b55dd","name":"test1","records":[{"locale":"US","id":"df92931e-3063-4889-8e4b-100c66f14d22","name":"SSGA SPDR S&P 500 - SSgA Active Trust","secid":549535,"size":100,"ticker":"SPY US"}],"size_type":"notional","type":"primary"}}' --compressed > /tmp/jsonpayload

I stored the above command in a test.sh file
I'm having trouble executing the above shell command.  It works on the linux terminal.  But it doesn't work on my windows cmd.  I need to read the above url, get the json object and do some analysis with it.

What i tried:

import subprocess
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])

This fails.  ok...

I tried then...

subprocess.call(['test.sh'])

I'm getting error '%1 is not a valid Win32 application'

Body:
try:

# Importing the necessary packages
$ from subprocess import call

# Executing the test.sh script
$ call('sh test.sh 2>/dev/null', shell=True)


问:
javascript merge sort and recursion
I am trying to understand how JavaScript merge sort function work. And I struggle understanding how the recursive function work. This is the code:</p>
```<code>const mergeSort = array => {
  if (array.length < 2) {
    //function stop here
    return array
  }

  const middle = Math.floor(array.length / 2);
  const leftSide = array.slice(0, middle);
  const rightSide = array.slice(middle, array.length);
  return merge(mergeSort(leftSide), mergeSort(rightSide))

};

const merge = (left, right) => {
  const result = [];

  while (left.length && right.length) {
    if (left[0] <= right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift);
    }
  }

  while(left.length) result.push(left.shift());

  while(right.length) result.push(right.shift());

  return result;
}
mergeSort([5,3,8,10,4,1])
</code>```

答:
To understand recursion you can trace all recursion levels with indentation. For example:

```<code>const mergeSort = (array, level) => {
  logWithLevel(level, "Start sort array " + array);
  if(array.length < 2) {
    //function stop here
    logWithLevel(level, "Finish sort array " + array);
    return array;
  }

  const middle = Math.floor(array.length / 2);
  logWithLevel(level, "middle element is " + array[middle])
  const leftSide = array.slice(0, middle);
  const rightSide = array.slice(middle, array.length);
  var result = merge(mergeSort(leftSide, level + 1), mergeSort(rightSide, level + 1));
  logWithLevel(level, "Finish sort array " + result);
  return result;
};

const merge = (left, right) => {
  const result = [];

  while(left.length && right.length){
    if(left[0] <= right[0]){
      result.push(left.shift());
    }else{
      result.push(right.shift());
    }
  }

  while(left.length) result.push(left.shift());

  while(right.length) result.push(right.shift());

  return result;
}

const logWithLevel = (level, data) => {
    var s = ""
    for (i = 0; i < level; i++) {
        s += "    ";
    }
    console.log(s + data);
}
</code>```

And result:

```<code>> mergeSort([5,3,8,10,4,1], 0)
    Start sort array 5,3,8,10,4,1
    middle element is 10
        Start sort array 5,3,8
        middle element is 3
            Start sort array 5
            Finish sort array 5
            Start sort array 3,8
            middle element is 8
                Start sort array 3
                Finish sort array 3
                Start sort array 8
                Finish sort array 8
            Finish sort array 3,8
        Finish sort array 3,5,8
        Start sort array 10,4,1
        middle element is 4
            Start sort array 10
            Finish sort array 10
            Start sort array 4,1
            middle element is 1
                Start sort array 4
                Finish sort array 4
                Start sort array 1
                Finish sort array 1
            Finish sort array 1,4
        Finish sort array 1,4,10
    Finish sort array 1,3,4,5,8,10
</code>```

Title: javascript merge sort and recursion

Body:
I am trying to understand how JavaScript merge sort function work. And I struggle understanding how the recursive function work. This is the code:

const mergeSort = array => {
  if (array.length < 2) {
    //function stop here
    return array
  }

  const middle = Math.floor(array.length / 2);
  const leftSide = array.slice(0, middle);
  const rightSide = array.slice(middle, array.length);
  return merge(mergeSort(leftSide), mergeSort(rightSide))

};

const merge = (left, right) => {
  const result = [];

  while (left.length && right.length) {
    if (left[0] <= right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift);
    }
  }

  while(left.length) result.push(left.shift());

  while(right.length) result.push(right.shift());

  return result;
}
mergeSort([5,3,8,10,4,1])

Body:
To understand recursion you can trace all recursion levels with indentation. For example:

const mergeSort = (array, level) => {
  logWithLevel(level, "Start sort array " + array);
  if(array.length < 2) {
    //function stop here
    logWithLevel(level, "Finish sort array " + array);
    return array;
  }

  const middle = Math.floor(array.length / 2);
  logWithLevel(level, "middle element is " + array[middle])
  const leftSide = array.slice(0, middle);
  const rightSide = array.slice(middle, array.length);
  var result = merge(mergeSort(leftSide, level + 1), mergeSort(rightSide, level + 1));
  logWithLevel(level, "Finish sort array " + result);
  return result;
};

const merge = (left, right) => {
  const result = [];

  while(left.length && right.length){
    if(left[0] <= right[0]){
      result.push(left.shift());
    }else{
      result.push(right.shift());
    }
  }

  while(left.length) result.push(left.shift());

  while(right.length) result.push(right.shift());

  return result;
}

const logWithLevel = (level, data) => {
    var s = ""
    for (i = 0; i < level; i++) {
        s += "    ";
    }
    console.log(s + data);
}

And result:

> mergeSort([5,3,8,10,4,1], 0)
    Start sort array 5,3,8,10,4,1
    middle element is 10
        Start sort array 5,3,8
        middle element is 3
            Start sort array 5
            Finish sort array 5
            Start sort array 3,8
            middle element is 8
                Start sort array 3
                Finish sort array 3
                Start sort array 8
                Finish sort array 8
            Finish sort array 3,8
        Finish sort array 3,5,8
        Start sort array 10,4,1
        middle element is 4
            Start sort array 10
            Finish sort array 10
            Start sort array 4,1
            middle element is 1
                Start sort array 4
                Finish sort array 4
                Start sort array 1
                Finish sort array 1
            Finish sort array 1,4
        Finish sort array 1,4,10
    Finish sort array 1,3,4,5,8,10


问:
How do I generate a JWT to use in API authentication for Swift app
I am trying to implement the use of an API service which requires JWT authentication for all its API calls.

I understand what JWT tokens are and how they are used, my issue is that I am writing a Swift app and can't quite figure out the process to generate the token so that I can attach it as a Bearer in my API calls.

Can I generate the JWT token on the client side (swift app)?

Create a Google Cloud Function to generate token then write back to Firebase
to use in my API calls?

答:
It depends on how you plan to sign your token.  Fundamentally, you'll want some sort of secret to sign the payload of the JWT.

Is your secret an API key that the client already has?  If so, there's not a lot of harm just generating it client side.

Is your secret a certificate that's super secret and you can't give out to clients?  Then you'll probably want to go with your Firebase idea.

It's pretty common to just have the client do the signing via API key in these situations, but your motivations for locking down your API to begin with are the driving force here.

IBM-Swift looks like the most complete JWT library for swift these days should you decide to go client side.

Jsonwebtoken is a very good JS one should you decide to deploy a GC Function.

Both libraries are very straightforward to use.


问:
Spring Cloud Gateway and TokenRelay Filter
I’m trying to migrate JHipster from using Zuul to Spring Cloud Gateway. JHipster uses Eureka to look up routes and I believe I’ve configured Spring Cloud Gateway correctly to look up routes and propagate the access token to them. Here’s my config:

```<code>spring:
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          route-id-prefix: /services/
      httpclient:
        pool:
          max-connections: 1000
</code>```

The problem I’m experiencing is the access token is not sending an Authorization header to the downstream services.

Here's how things were configured with Zuul in my application.yml:

```<code>zuul: # those values must be configured depending on the application specific needs
  sensitive-headers: Cookie,Set-Cookie #see https://github.com/spring-cloud/spring-cloud-netflix/issues/3126
  host:
    max-total-connections: 1000
    max-per-route-connections: 100
  prefix: /services
  semaphore:
    max-semaphores: 500
</code>```

I created a pull request to show what's changed after integrating Spring Cloud Gateway.

https://github.com/mraible/jhipster-reactive-microservices-oauth2/pull/4

Steps to reproduce the issue:

```<code>git clone -b reactive git@github.com:mraible/jhipster-reactive-microservices-oauth2.git
</code>```

Start JHipster Registry, Keycloak, and the gateway app:

```<code>cd jhipster-reactive-microservices-oauth2/gateway
docker-compose -f src/main/docker/jhipster-registry.yml up -d
docker-compose -f src/main/docker/keycloak.yml up -d
./mvnw
</code>```

Start MongoDB and the blog app:

```<code>cd ../blog
docker-compose -f src/main/docker/mongodb.yml up -d
./mvnw
</code>```

Navigate to http://localhost:8080 in your browser, log in with admin/admin, and try to go to Entities > Blog. You will get a 403 access denied error. If you look in Chrome Developer Tools at the network traffic, you'll see the access token isn't included in any headers.

答:
I was able to solve this using this answer.

```<code>spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          predicates:
            - name: Path
              args:
                pattern: "'/services/'+serviceId.toLowerCase()+'/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/services/' + serviceId.toLowerCase() + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"
</code>```

I also had to add .pathMatchers("/services/**").authenticated() to my security config, which wasn't needed for Zuul. You can see my commit here.

Body:
I’m trying to migrate JHipster from using Zuul to Spring Cloud Gateway. JHipster uses Eureka to look up routes and I believe I’ve configured Spring Cloud Gateway correctly to look up routes and propagate the access token to them. Here’s my config:

spring:
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          route-id-prefix: /services/
      httpclient:
        pool:
          max-connections: 1000

The problem I’m experiencing is the access token is not sending an Authorization header to the downstream services.

Here's how things were configured with Zuul in my application.yml:

zuul: # those values must be configured depending on the application specific needs
  sensitive-headers: Cookie,Set-Cookie #see https://github.com/spring-cloud/spring-cloud-netflix/issues/3126
  host:
    max-total-connections: 1000
    max-per-route-connections: 100
  prefix: /services
  semaphore:
    max-semaphores: 500

I created a pull request to show what's changed after integrating Spring Cloud Gateway.

https://github.com/mraible/jhipster-reactive-microservices-oauth2/pull/4

Steps to reproduce the issue:

git clone -b reactive git@github.com:mraible/jhipster-reactive-microservices-oauth2.git

Start JHipster Registry, Keycloak, and the gateway app:

cd jhipster-reactive-microservices-oauth2/gateway
docker-compose -f src/main/docker/jhipster-registry.yml up -d
docker-compose -f src/main/docker/keycloak.yml up -d
./mvnw

Start MongoDB and the blog app:

cd ../blog
docker-compose -f src/main/docker/mongodb.yml up -d
./mvnw

Navigate to http://localhost:8080 in your browser, log in with admin/admin, and try to go to Entities > Blog. You will get a 403 access denied error. If you look in Chrome Developer Tools at the network traffic, you'll see the access token isn't included in any headers.

Body:
I was able to solve this using this answer.

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          predicates:
            - name: Path
              args:
                pattern: "'/services/'+serviceId.toLowerCase()+'/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/services/' + serviceId.toLowerCase() + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"

I also had to add .pathMatchers("/services/**").authenticated() to my security config, which wasn't needed for Zuul. You can see my commit here.


问:
How to change the options for a symfony admin filter
I have a table/class called ImportBundle. ImportBundle has an active flag that can be set to 1 or 0.

On one of my admin pages I have a select field showing all the ImportBundles in my database. I would like to only see the active ones.

How do I change this?

答:
If your select field is a sfWidgetFormDoctrineChoice, then you should set the table_method option.

For example, if your have Model with many-to-many relation to Related:

```<code>class ModelFormFilter extends BaseModelFormFilter
{
  public function configure()
  {
    $this->getWidget('related_list')->setOption('table_method', 'getActive');
  }
}

class RelatedTable extends Doctrine_Table
{
  public function getActive()
  {
    return $this->createQuery('r')
      ->where('r.is_active = ?', true)
      ->execute();
  }
}
</code>```

Body:
If your select field is a sfWidgetFormDoctrineChoice, then you should set the table_method option.

For example, if your have Model with many-to-many relation to Related:

class ModelFormFilter extends BaseModelFormFilter
{
  public function configure()
  {
    $this->getWidget('related_list')->setOption('table_method', 'getActive');
  }
}

class RelatedTable extends Doctrine_Table
{
  public function getActive()
  {
    return $this->createQuery('r')
      ->where('r.is_active = ?', true)
      ->execute();
  }
}


问:
reactjs serve xml file from root path
I want to show the sitemap.xml file from the root path but i get the following error.

Cannot GET /sitemap.xml

This is the url i am trying to access: http://localhost:8080/sitemap.xml

i added the file to the public directory.

this is my webpack configuration:

devServer: removeEmpty({
      hot: ifDevelopment(true),
      publicPath: "/",
      historyApiFallback: true,
    }),

答:
You need to copy sitemap.xml file to the build directory
you can use CopyWebpackPlugin for that

Title: reactjs serve xml file from root path


问:
Finish this class method - Do you know how?
Could someone help me out finishing this task? I'd be very grateful!

Finish the class method 'copy(Fraction source, Fraction target)', so that after calling this method 'source' is unchanged and 'target' is made identical to 'source'.

At this line: target = source; // Here I need to put the code

class Fraction {

    Integer nominator;
    Integer denominator;

}

class Main
{
 public static void copy(Fraction source, Fraction target)
 {
  target = source; // Here I need to put the code
 }

 public static Fraction createFraction(Integer nominator, Integer denominator)
 {
        Fraction fraction = new Fraction();
        fraction.nominator = nominator;
        fraction.denominator = denominator;
        return fraction;
 }

 public static void main(String[] arguments)
 {
  final Integer ONE = 1;
  final Integer TWO = 2;
  final Integer THREE = 3;
  final Fraction SOURCE = createFraction(ONE, TWO);
  final Fraction TARGET = createFraction(TWO, THREE);
  copy(SOURCE, TARGET);
  System.out.println("SOURCE: " + toString(SOURCE));
  System.out.println("TARGET: " + toString(TARGET));
 }

 public static String toString(Fraction fraction)
 {
                return fraction.nominator + "/" + fraction.denominator;

 }
}```

答:
Update target (not the reference), specifically copy the source nominator and denominator values to target.nominator and target.denominator respectively. Like,

```<code>public static void copy(Fraction source, Fraction target)
{
    // target = source; // Good try, but this just updates a local reference
    target.nominator = source.nominator; // <-- copy the `nominator`
    target.denominator = source.denominator; // <-- copy the `denominator`
}
</code>```

Alternatively, but along the same lines, add a setFraction function to Fraction like,

```<code>public void setFraction(Fraction f) {
    this.nominator = f.nominator;
    this.denominator = f.denominator;
}
</code>```

Also, you shouldn't modify toString() like that. Add it to Fraction as well,

```<code>@Override
public String toString() {
    return nominator + "/" + denominator;
}
</code>```

And I would also override Object.equals(Object) in Fraction.

```<code>@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o instanceof Fraction) {
        Fraction that = (Fraction) o;
        return nominator.equals(that.nominator) && denominator.equals(that.denominator);
    }
    return false;
}
</code>```

Then you can write

```<code>public static void copy(Fraction source, Fraction target)
{
    target.setFraction(source);
}
</code>```

And if you followed along with toString then

```<code>System.out.println("SOURCE: " + toString(SOURCE));
System.out.println("TARGET: " + toString(TARGET));
</code>```

Can be

```<code>System.out.println("SOURCE: " + SOURCE);
System.out.println("TARGET: " + TARGET);
System.out.println("TARGET.equals(SOURCE): " + TARGET.equals(SOURCE));
</code>```

Body:
Update target (not the reference), specifically copy the source nominator and denominator values to target.nominator and target.denominator respectively. Like,

public static void copy(Fraction source, Fraction target)
{
    // target = source; // Good try, but this just updates a local reference
    target.nominator = source.nominator; // <-- copy the `nominator`
    target.denominator = source.denominator; // <-- copy the `denominator`
}

Alternatively, but along the same lines, add a setFraction function to Fraction like,

public void setFraction(Fraction f) {
    this.nominator = f.nominator;
    this.denominator = f.denominator;
}

Also, you shouldn't modify toString() like that. Add it to Fraction as well,

@Override
public String toString() {
    return nominator + "/" + denominator;
}

And I would also override Object.equals(Object) in Fraction.

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o instanceof Fraction) {
        Fraction that = (Fraction) o;
        return nominator.equals(that.nominator) && denominator.equals(that.denominator);
    }
    return false;
}

Then you can write

public static void copy(Fraction source, Fraction target)
{
    target.setFraction(source);
}

And if you followed along with toString then

System.out.println("SOURCE: " + toString(SOURCE));
System.out.println("TARGET: " + toString(TARGET));

Can be

System.out.println("SOURCE: " + SOURCE);
System.out.println("TARGET: " + TARGET);
System.out.println("TARGET.equals(SOURCE): " + TARGET.equals(SOURCE));


问:
Firestore query a document based on starts with in any of the 2 fields
My Firestore set up is the following:

Collection : Users |
DocumentID : [Auto-generated] |
Fields ->
name: robert downey jr,
username: iron_man

I would like to query this document with a search query like "robert" or "rob" or "iron" or "ir". How do I do this in Firestore? I tried whereArrayContains() but that query looks for perfect match rather than starts with

答: You won't be able to do this in one query, because Firestore does not support logical OR queries that span multiple fields.  What you can do instead is make two queries, one for name, and the other for username that do string prefix sorts (read other questions about that here, here, here).  Then, after you do both queries, merge the results on the client to build the final list of results.


问:
Is there a way to install an ipa file to tester without all the apple stuff?
I have some ipa files and it turns out that I can install directly on my device without having to do anything unusual, just itunes. These apps are not in the app store, so I guess they've done something with Xcode or with the ipas, right? How is this possible?

When I pass the apps I've done to some beta testers I have to ask IDs and after putting it in the certificate, it can be installed, but if not, no.

So anyone have any idea? What happened?

If you have an Enterprise account, you still need the ID's of the testers, right?

sorry for my bad english, but at least I try!

Greetings and thanks!

答:
Have you look at Test Flight?

EDIT

Come to think of it, if one is able to give their applications to anonymous testers he could sell the app outside the AppStore. That would be counterproductive for Apple and unless the user jailbreaks the device it shouldn't be possible.


问:
JAVA quiz - Same question repeating while answers do cycle correctly
I'm doing a quiz that has a sequence of 3 questions. After choosing the right or wrong answer, it should go to the next question and present the next set of possible answers.

My code does show the answers correctly, but the question repeats itself three times. As another side effect, the set of three quizzes become nine, with the following order: Q1/A1, Q1/A2, Q1/A3, Q2/A1, Q2/A2, Q2/A3, Q3/A1, Q3/A2, Q3/A3.

The desired result is Q1/A1, Q2/A2, Q3/A3.

Here is my code:

import javax.swing.JOptionPane;

public class Quiz {

    private static String answer = null;
    private static String answer2 = null;
    private static String answer3 = null;

    static int nQuestions = 0;
    static int nCorrect = 0;

    //Main program, will call the questions to be answered in the quiz and checks if it's correct
    //counting both the number of questions and correct answers.
    public static void main(String[] args) {

        String question = "What is the planet with fastest orbit?\n";
        check(question, answer);
        nQuestions = nQuestions+1;
        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");

        String question2 = "The sum of 2 + 2.0 is?\n";
        check(question2, answer2);
        nQuestions = nQuestions+1;

        String question3 = "What is the sport the player shoots the ball in a basket\n";
        check(question3, answer3);
        nQuestions = nQuestions+1;

        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
    }

    //The quiz #1
    static String ask(String question) {

        question += "A. Mercury, with a rotation that takes 58d 16h.\n";

        question += "B. Earth, with a rotation that takes 23h 56m.\n";

        question += "C. Mars, with a rotation that takes 24h 36m.\n";

        question += "D. Venus, with a rotation that takes 243d 26m.\n";

        question += "E. Uranus, with a rotation that takes 17h 14m.\n";

        String answer = JOptionPane.showInputDialog(question);

        answer = answer.toUpperCase();

        while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer = JOptionPane.showInputDialog(question);
            answer = answer.toUpperCase();

        }

        return answer;

    }

    //The quiz #2
    static String ask2(String question2) {

        question2 += "A. 4\n";

        question2 += "B. 4.0\n";

        question2 += "C. 3\n";

        question2 += "D. 5\n";

        question2 += "E. -4\n";

        String answer2 = JOptionPane.showInputDialog(question2);

        answer2 = answer2.toUpperCase();

        while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer2 = JOptionPane.showInputDialog(question2);
            answer2 = answer2.toUpperCase();

        }

        return answer2;

    }

    //The quiz #3
    static String ask3(String question3) {

        question3 += "A. Basketball.\n";

        question3 += "B. Volleyball.\n";

        question3 += "C. Baseball.\n";

        question3 += "D. Football.\n";

        question3 += "E. Tennis\n";

        String answer3 = JOptionPane.showInputDialog(question3);

        answer3 = answer3.toUpperCase();

        while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer3 = JOptionPane.showInputDialog(question3);
            answer3 = answer3.toUpperCase();

        }

        return answer3;

    }

    //Answer verifier
    static void check(String question,  String correctAnswer) {
        String answer = ask(question);
        String correct = "D";
        if (answer.equals(correct)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
        }

        //checking Quiz#2
        String answer2 = ask2(question);
        String correct2 = "B";
        if (answer2.equals(correct2)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);

        }

        //checking Quiz#3
        String answer3 = ask3(question);
        String correct3 = "A";
        if (answer3.equals(correct3)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);

        }
    }
}

```

I'm a beginner java student and I do realize some sort of unintended loop, but I'm not being able to fix it.

Any suggestions? Thanks in advance.

答:
Welcome to SO.

There are a lot of issues with your code, but since you've just started that's understandable.

You should really consider using arrays, and that's why I added one for you so you can get a feel for them.

Your main issue was that you are using the same answer selections for each question 3 times.

The following code should give you what you want:

```<code>import javax.swing.JOptionPane;

public class Quiz {

    private static String answer = null;
    private static String answer2 = null;
    private static String answer3 = null;

    static int nQuestions = 0;
    static int nCorrect = 0;

    //Main program, will call the questions to be answered in the quiz and checks if it's correct
    //counting both the number of questions and correct answers.
    public static void main(String[] args) {

        String[] questions = {"What is the planet with fastest orbit?\n",
                "The sum of 2 + 2.0 is?\n",
                "What is the sport the player shoots the ball in a basket\n"
        };

        nQuestions = questions.length;

        checkQuestions(questions, answer3);

        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
    }

    //The quiz #1
    static String ask(String question) {

        question += "A. Mercury, with a rotation that takes 58d 16h.\n";

        question += "B. Earth, with a rotation that takes 23h 56m.\n";

        question += "C. Mars, with a rotation that takes 24h 36m.\n";

        question += "D. Venus, with a rotation that takes 243d 26m.\n";

        question += "E. Uranus, with a rotation that takes 17h 14m.\n";

        String answer = JOptionPane.showInputDialog(question);

        answer = answer.toUpperCase();

        while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer = JOptionPane.showInputDialog(question);
            answer = answer.toUpperCase();

        }

        return answer;

    }

    //The quiz #2
    static String ask2(String question2) {

        question2 += "A. 4\n";

        question2 += "B. 4.0\n";

        question2 += "C. 3\n";

        question2 += "D. 5\n";

        question2 += "E. -4\n";

        String answer2 = JOptionPane.showInputDialog(question2);

        answer2 = answer2.toUpperCase();

        while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer2 = JOptionPane.showInputDialog(question2);
            answer2 = answer2.toUpperCase();

        }

        return answer2;

    }

    //The quiz #3
    static String ask3(String question3) {

        question3 += "A. Basketball.\n";

        question3 += "B. Volleyball.\n";

        question3 += "C. Baseball.\n";

        question3 += "D. Football.\n";

        question3 += "E. Tennis\n";

        String answer3 = JOptionPane.showInputDialog(question3);

        answer3 = answer3.toUpperCase();

        while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer3 = JOptionPane.showInputDialog(question3);
            answer3 = answer3.toUpperCase();

        }

        return answer3;

    }

    //Answer verifier
    static void checkQuestions(String[] questions,  String correctAnswer) {
        String answer = ask(questions[0]);
        String correct = "D";
        if (answer.equals(correct)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
        }

        //checking Quiz#2
        String answer2 = ask2(questions[1]);
        String correct2 = "B";
        if (answer2.equals(correct2)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);

        }

        //checking Quiz#3
        String answer3 = ask3(questions[2]);
        String correct3 = "A";
        if (answer3.equals(correct3)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);

        }
    }
}
</code>```

Let me know if you have any questions about what I did.  I tried to keep as much of the code the same while fixing the issue.

Good luck.

Body:
I'm doing a quiz that has a sequence of 3 questions. After choosing the right or wrong answer, it should go to the next question and present the next set of possible answers.

My code does show the answers correctly, but the question repeats itself three times. As another side effect, the set of three quizzes become nine, with the following order: Q1/A1, Q1/A2, Q1/A3, Q2/A1, Q2/A2, Q2/A3, Q3/A1, Q3/A2, Q3/A3.

The desired result is Q1/A1, Q2/A2, Q3/A3.

Here is my code:

import javax.swing.JOptionPane;

public class Quiz {

    private static String answer = null;
    private static String answer2 = null;
    private static String answer3 = null;

    static int nQuestions = 0;
    static int nCorrect = 0;

    //Main program, will call the questions to be answered in the quiz and checks if it's correct
    //counting both the number of questions and correct answers.
    public static void main(String[] args) {

        String question = "What is the planet with fastest orbit?\n";
        check(question, answer);
        nQuestions = nQuestions+1;
        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");

        String question2 = "The sum of 2 + 2.0 is?\n";
        check(question2, answer2);
        nQuestions = nQuestions+1;

        String question3 = "What is the sport the player shoots the ball in a basket\n";
        check(question3, answer3);
        nQuestions = nQuestions+1;

        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
    }

    //The quiz #1
    static String ask(String question) {

        question += "A. Mercury, with a rotation that takes 58d 16h.\n";

        question += "B. Earth, with a rotation that takes 23h 56m.\n";

        question += "C. Mars, with a rotation that takes 24h 36m.\n";

        question += "D. Venus, with a rotation that takes 243d 26m.\n";

        question += "E. Uranus, with a rotation that takes 17h 14m.\n";

        String answer = JOptionPane.showInputDialog(question);

        answer = answer.toUpperCase();

        while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer = JOptionPane.showInputDialog(question);
            answer = answer.toUpperCase();

        }

        return answer;

    }

    //The quiz #2
    static String ask2(String question2) {

        question2 += "A. 4\n";

        question2 += "B. 4.0\n";

        question2 += "C. 3\n";

        question2 += "D. 5\n";

        question2 += "E. -4\n";

        String answer2 = JOptionPane.showInputDialog(question2);

        answer2 = answer2.toUpperCase();

        while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer2 = JOptionPane.showInputDialog(question2);
            answer2 = answer2.toUpperCase();

        }

        return answer2;

    }

    //The quiz #3
    static String ask3(String question3) {

        question3 += "A. Basketball.\n";

        question3 += "B. Volleyball.\n";

        question3 += "C. Baseball.\n";

        question3 += "D. Football.\n";

        question3 += "E. Tennis\n";

        String answer3 = JOptionPane.showInputDialog(question3);

        answer3 = answer3.toUpperCase();

        while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer3 = JOptionPane.showInputDialog(question3);
            answer3 = answer3.toUpperCase();

        }

        return answer3;

    }

    //Answer verifier
    static void check(String question,  String correctAnswer) {
        String answer = ask(question);
        String correct = "D";
        if (answer.equals(correct)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
        }

        //checking Quiz#2
        String answer2 = ask2(question);
        String correct2 = "B";
        if (answer2.equals(correct2)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);

        }

        //checking Quiz#3
        String answer3 = ask3(question);
        String correct3 = "A";
        if (answer3.equals(correct3)) {
             JOptionPane.showMessageDialog(null,"Correct!");
             nCorrect = nCorrect+1;
            }

        else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
             JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);

        }
    }
}

I'm a beginner java student and I do realize some sort of unintended loop, but I'm not being able to fix it.

Any suggestions? Thanks in advance.

Body:
Welcome to SO.

There are a lot of issues with your code, but since you've just started that's understandable.

You should really consider using arrays, and that's why I added one for you so you can get a feel for them.

Your main issue was that you are using the same answer selections for each question 3 times.

The following code should give you what you want:

import javax.swing.JOptionPane;

public class Quiz {

    private static String answer = null;
    private static String answer2 = null;
    private static String answer3 = null;

    static int nQuestions = 0;
    static int nCorrect = 0;

    //Main program, will call the questions to be answered in the quiz and checks if it's correct
    //counting both the number of questions and correct answers.
    public static void main(String[] args) {

        String[] questions = {"What is the planet with fastest orbit?\n",
                "The sum of 2 + 2.0 is?\n",
                "What is the sport the player shoots the ball in a basket\n"
        };

        nQuestions = questions.length;

        checkQuestions(questions, answer3);

        JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
    }

    //The quiz #1
    static String ask(String question) {

        question += "A. Mercury, with a rotation that takes 58d 16h.\n";

        question += "B. Earth, with a rotation that takes 23h 56m.\n";

        question += "C. Mars, with a rotation that takes 24h 36m.\n";

        question += "D. Venus, with a rotation that takes 243d 26m.\n";

        question += "E. Uranus, with a rotation that takes 17h 14m.\n";

        String answer = JOptionPane.showInputDialog(question);

        answer = answer.toUpperCase();

        while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer = JOptionPane.showInputDialog(question);
            answer = answer.toUpperCase();

        }

        return answer;

    }

    //The quiz #2
    static String ask2(String question2) {

        question2 += "A. 4\n";

        question2 += "B. 4.0\n";

        question2 += "C. 3\n";

        question2 += "D. 5\n";

        question2 += "E. -4\n";

        String answer2 = JOptionPane.showInputDialog(question2);

        answer2 = answer2.toUpperCase();

        while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer2 = JOptionPane.showInputDialog(question2);
            answer2 = answer2.toUpperCase();

        }

        return answer2;

    }

    //The quiz #3
    static String ask3(String question3) {

        question3 += "A. Basketball.\n";

        question3 += "B. Volleyball.\n";

        question3 += "C. Baseball.\n";

        question3 += "D. Football.\n";

        question3 += "E. Tennis\n";

        String answer3 = JOptionPane.showInputDialog(question3);

        answer3 = answer3.toUpperCase();

        while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {

            JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
            answer3 = JOptionPane.showInputDialog(question3);
            answer3 = answer3.toUpperCase();

        }

        return answer3;

    }

    //Answer verifier
    static void checkQuestions(String[] questions,  String correctAnswer) {
        String answer = ask(questions[0]);
        String correct = "D";
        if (answer.equals(correct)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
        }

        //checking Quiz#2
        String answer2 = ask2(questions[1]);
        String correct2 = "B";
        if (answer2.equals(correct2)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);

        }

        //checking Quiz#3
        String answer3 = ask3(questions[2]);
        String correct3 = "A";
        if (answer3.equals(correct3)) {
            JOptionPane.showMessageDialog(null,"Correct!");
            nCorrect = nCorrect+1;
        }

        else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
            JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);

        }
    }
}

Let me know if you have any questions about what I did.  I tried to keep as much of the code the same while fixing the issue.

Good luck.


问:
kafka connect jdbc sink Value schema must be of type Struct
I want to use a kafka connect jdbc sink connector with the avro converter.

Those are my avro configs :

```<code>"key.converter":"io.confluent.connect.avro.AvroConverter",
"key.converter.schema.registry.url" : "http://myurl.com" ,
"value.converter":"io.confluent.connect.avro.AvroConverter",
"value.converter.schema.registry.url" : "http://myurl.com" ,
</code>```

Schemas are set to false

```<code>key.converter.schemas.enable=false
value.converter.schemas.enable=false
</code>```

Now, when i start the connector, i get this error

Caused by: org.apache.kafka.connect.errors.ConnectException: Value schema must be of type Struct

From what i read, Struct are for json schemas, right ? i should not have any struct if i am using an avro schema ?

Avro schema types are : record, enum, arrays, maps, unions and fixed but there is no struct.

What am i missing ?

Thanks !!

答:
An Avro record creates a Struct Connect data type.

The error is saying your data is not a record.

Schemas are set to false

Those properties don't mean anything to the Avro converter. Avro always has a schema

I want to use a kafka connect jdbc sink connector with the avro converter.

Then the producer needs to send records with schemas. This includes Avro records or JSON with schemas enabled

Body:
I want to use a kafka connect jdbc sink connector with the avro converter.

Those are my avro configs :

"key.converter":"io.confluent.connect.avro.AvroConverter",
"key.converter.schema.registry.url" : "http://myurl.com" ,
"value.converter":"io.confluent.connect.avro.AvroConverter",
"value.converter.schema.registry.url" : "http://myurl.com" ,

Schemas are set to false

key.converter.schemas.enable=false
value.converter.schemas.enable=false

Now, when i start the connector, i get this error

Caused by: org.apache.kafka.connect.errors.ConnectException: Value schema must be of type Struct

From what i read, Struct are for json schemas, right ? i should not have any struct if i am using an avro schema ?

Avro schema types are : record, enum, arrays, maps, unions and fixed but there is no struct.

What am i missing ?

Thanks !!


问:
Do .py Python files contain metadata?
.doc files, .pdf files, and some image formats all contain metadata about the file, such as the author.

Is a .py file just a plain text file whose contents are all visible once opened with a code editor like Sublime, or does it also contain metadata? If so, how does one access this metadata?

答:
On Linux and most Unixes, .py's are just text (sometimes unicode text).

On Windows and Mac, there are cubbyholes where you can stash data, but I doubt Python uses them.

.pyc's, on the other hand, have at least a little metadata stuff in them - or so I've heard.  Specifically: there's supposed to be a timestamp in them, so that if you copy a filesystem hierarchy, python won't automatically recreate all the .pyc's on import.  There may or may not be more.

Title: Do .py Python files contain metadata?


问:
Add characters to the end of a string using regex notepad2
I have a massive string (a SQL query..) that I have written out in notepad2.  I'm using Java, and I was just wondering if there was a fast and easy way to add something to the end of each line? For example:</p>

```<code>String query = ""
+ " select column1
+ " , column2
+ " , column3
+ " from table
);
//want to add \n" at the end of each line
</code>```

答:
For anyone still here 5 years later, and you are attempting to add something onto the end a line for a large non-code file (and don't want to use REGEX), there are helpful online converter tools like https://pinetools.com/add-text-each-line.

Helped me out a bunch for creating CSV files for a neural network I was making

Body:
I have a massive string (a SQL query..) that I have written out in notepad2.  I'm using Java, and I was just wondering if there was a fast and easy way to add something to the end of each line? For example:

String query = ""
+ " select column1
+ " , column2
+ " , column3
+ " from table
);
//want to add \n" at the end of each line


问:
scraping multiple page web table with vba
i'm trying to save in excel with vba the second page of the table in the url below in code but i'm unable to use the click property, may you help me please? i have searched everywhere on the web without results. thanks.

Sub BrowseSiteTableObjectX()
    Dim IE As New SHDocVw.InternetExplorer
    Dim Docm As MSHTML.HTMLDocument
    Dim HTMLAtab As MSHTML.IHTMLElement
    Dim HTMLArow As MSHTML.IHTMLElement
    Dim iRow As Long

    With IE
        .navigate "https://www.nasdaq.com/market-activity/stocks/screener"
        Do While .Busy Or .readyState <> 4
           DoEvents
        Loop
    End With

    Set Docm = IE.document

    Docm.getElementsByClassName("symbol-screener__pagination")(0).getElementsByClassName("next")(0).Click

    Set Docm = IE.document

    Set HTMLAtab = Docm.getElementsByClassName("symbol-screener__table")(0)

    For Each HTMLArow In HTMLAtab.getElementsByClassName("symbol-screener__row")
        iRow = iRow + 1
        Cells(iRow, 1) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--ticker")(0).innerText
        Cells(iRow, 2) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--company")(0).innerText
        DoEvents
    Next HTMLArow

    IE.Quit
    Set IE = Nothing
    Set Docm = Nothing
End Sub
```

答:
Pagination is sometimes a tricky thing but on this page it's easy. I fixed also some other issues. Please read the comments in the code:</p>

```<code>Sub BrowseSiteTableObjectX()
  Dim IE As New SHDocVw.InternetExplorer
  Dim Docm As MSHTML.HTMLDocument
  Dim HTMLAtab As MSHTML.IHTMLElement
  Dim HTMLArow As MSHTML.IHTMLElement
  Dim nodePagiantionNext As Object 'I do those things always by late binding
  Dim iRow As Long
  Dim lastPage As Boolean

  With IE
    'Set the following line to 'False' to make IE invisible
    'You can also set IE to full screen, scroll to the page
    'count and watch it advance. I give each page 5 seconds
    'to load. From what I have seen, this is partly necessary
    .Visible = True
    .navigate "https://www.nasdaq.com/market-activity/stocks/screener"
    Do While .Busy Or .readyState <> 4: DoEvents: Loop
  End With
  'The page loads data after the IE says he's ready. So you need a manual break for a few seconds
  'Application.Wait (Now + TimeSerial(pause_hours, pause_minutes, pause_seconds))
  Application.Wait (Now + TimeSerial(0, 0, 5))

  Set Docm = IE.document

  'You need a loop to go through all pages
  '(The IE is a diva. It can be you must start him every loop round. But for the given url it
  'works for 312 pages with the 5 second break)
  Do
    'If you click the 'next' link here, you are on the second page before you read out any data
    'You must do the click after reading data from the first page
    '
    'Give some seconds after the click to load the new page
    Application.Wait (Now + TimeSerial(0, 0, 5))

    Set Docm = IE.document

    Set HTMLAtab = Docm.getElementsByClassName("symbol-screener__table")(0)

    For Each HTMLArow In HTMLAtab.getElementsByClassName("symbol-screener__row")
      iRow = iRow + 1
      Cells(iRow, 1) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--ticker")(0).innerText
      Cells(iRow, 2) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--company")(0).innerText
      'DoEvents 'Why?
    Next HTMLArow

    'You can't click the li tag. You must click the link which is the first child of the li tag
    'But you must also know when the last page is reached. Thats  when the CSS class changes to "next disabled"
    Set nodePagiantionNext = Docm.getElementsByClassName("symbol-screener__pagination")(0).getElementsByClassName("next")(0)
    '
    'Check if the CSS class has been changed to "disabled".
    'Short explanation, because we ask for "next" first, and if this should work,
    '"next" must also match "next disabled". This is true.  "next" is the first
    'part of "next disabled". All CSS class names with the same beginning fit for
    'a node collection to be created
    If nodePagiantionNext.getAttribute("class") = "next disabled" Then
      'If last page end loop
      lastPage = True
    Else
      'If not the last page, click for next page
      nodePagiantionNext.FirstChild.Click
    End If
  Loop Until lastPage

  IE.Quit
  Set IE = Nothing
  Set Docm = Nothing
End Sub
</code>```

Body:
Pagination is sometimes a tricky thing but on this page it's easy. I fixed also some other issues. Please read the comments in the code:

Sub BrowseSiteTableObjectX()
  Dim IE As New SHDocVw.InternetExplorer
  Dim Docm As MSHTML.HTMLDocument
  Dim HTMLAtab As MSHTML.IHTMLElement
  Dim HTMLArow As MSHTML.IHTMLElement
  Dim nodePagiantionNext As Object 'I do those things always by late binding
  Dim iRow As Long
  Dim lastPage As Boolean

  With IE
    'Set the following line to 'False' to make IE invisible
    'You can also set IE to full screen, scroll to the page
    'count and watch it advance. I give each page 5 seconds
    'to load. From what I have seen, this is partly necessary
    .Visible = True
    .navigate "https://www.nasdaq.com/market-activity/stocks/screener"
    Do While .Busy Or .readyState <> 4: DoEvents: Loop
  End With
  'The page loads data after the IE says he's ready. So you need a manual break for a few seconds
  'Application.Wait (Now + TimeSerial(pause_hours, pause_minutes, pause_seconds))
  Application.Wait (Now + TimeSerial(0, 0, 5))

  Set Docm = IE.document

  'You need a loop to go through all pages
  '(The IE is a diva. It can be you must start him every loop round. But for the given url it
  'works for 312 pages with the 5 second break)
  Do
    'If you click the 'next' link here, you are on the second page before you read out any data
    'You must do the click after reading data from the first page
    '
    'Give some seconds after the click to load the new page
    Application.Wait (Now + TimeSerial(0, 0, 5))

    Set Docm = IE.document

    Set HTMLAtab = Docm.getElementsByClassName("symbol-screener__table")(0)

    For Each HTMLArow In HTMLAtab.getElementsByClassName("symbol-screener__row")
      iRow = iRow + 1
      Cells(iRow, 1) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--ticker")(0).innerText
      Cells(iRow, 2) = HTMLArow.getElementsByClassName("symbol-screener__cell symbol-screener__cell--company")(0).innerText
      'DoEvents 'Why?
    Next HTMLArow

    'You can't click the li tag. You must click the link which is the first child of the li tag
    'But you must also know when the last page is reached. Thats  when the CSS class changes to "next disabled"
    Set nodePagiantionNext = Docm.getElementsByClassName("symbol-screener__pagination")(0).getElementsByClassName("next")(0)
    '
    'Check if the CSS class has been changed to "disabled".
    'Short explanation, because we ask for "next" first, and if this should work,
    '"next" must also match "next disabled". This is true.  "next" is the first
    'part of "next disabled". All CSS class names with the same beginning fit for
    'a node collection to be created
    If nodePagiantionNext.getAttribute("class") = "next disabled" Then
      'If last page end loop
      lastPage = True
    Else
      'If not the last page, click for next page
      nodePagiantionNext.FirstChild.Click
    End If
  Loop Until lastPage

  IE.Quit
  Set IE = Nothing
  Set Docm = Nothing
End Sub


问:
Typecasting HashSets in C#
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?</p>

```<code>public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}
</code>```

答:
You cannot convert a HashSet<Derived> to a HashSet<Base> without casting each item.

To explain why this is not possible, have a look at the following code example:

```<code>HashSet<Derived> mySet = ...;
HashSet<Base> x = (HashSet<Base>)mySet;  // imagine this were possible

x.Add(new Base());  // legal code, but cannot work, since x is really a HashSet<Derived>
</code>```

However, since the IEnumerable interface is covariant, the following should be possible:

```<code>HashSet<Derived> mySet = ...;
IEnumerable<Base> x = mySet;  // works in C# 4

// no problem here, since no items can be added to an IEnumerable
</code>```

Thus, you could change your method declaration:

```<code>public IEnumerable<Base> GetList { get { return mList; } }
</code>```

Title: Typecasting HashSets in C#

Body:
I have two classes where one derives the other. I also have a HashSet field which stores a bunch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?

public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}

Body:
You cannot convert a HashSet<Derived> to a HashSet<Base> without casting each item.

To explain why this is not possible, have a look at the following code example:

HashSet<Derived> mySet = ...;
HashSet<Base> x = (HashSet<Base>)mySet;  // imagine this were possible

x.Add(new Base());  // legal code, but cannot work, since x is really a HashSet<Derived>

However, since the IEnumerable interface is covariant, the following should be possible:

HashSet<Derived> mySet = ...;
IEnumerable<Base> x = mySet;  // works in C# 4

// no problem here, since no items can be added to an IEnumerable

Thus, you could change your method declaration:

public IEnumerable<Base> GetList { get { return mList; } }


问:
(Matplotlib) Setting the space of first x tick (0) and y axis
I want the first x tick (0) nearer to the y axis. I tried setting xlim, but I don't want to have the first x tick where the axes are crossing. Like just half the space between the y axis and the first x tick.
I didn't find an solution, maybe you can help me.

This is a minimal reproducible example:

```<code>import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
</code>```

答:
You can use plt.margins to specify the margins for x and y axis spearately.

```<code>plt.margins(x=0.02)
</code>```

Body:
I want the first x tick (0) nearer to the y axis. I tried setting xlim, but I don't want to have the first x tick where the axes are crossing. Like just half the space between the y axis and the first x tick.
I didn't find an solution, maybe you can help me.

This is a minimal reproducible example:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

Body:
You can use plt.margins to specify the margins for x and y axis spearately.

plt.margins(x=0.02)


问:
Kafka Connect Hangs when Kafka Node Goes Down
we are testing out kafka connect and in our testing noticed that when one of our kafka nodes goes down or is unavailable, kafka connect goes down (hangs).

In our rest and distributed properties, our broker configuration looks like: dp-kafka-01:9092, dp-kafka-02:9092, dp-kafka-03:9092.

We are looking at possibly using a load balancer to maintain uptime but I would be interested in seeing 1) if others have had this problem 2) their solution to it.

Many Thanks.

答:
Putting a load balancer in front of the Connect REST API will not stop them from crashing upon broker failure. </p>

<p>You need to administer Kafka better to prevent the whole system from going down. </p>

Body:
Putting a load balancer in front of the Connect REST API will not stop them from crashing upon broker failure.

You need to administer Kafka better to prevent the whole system from going down.


问:
Augment Base Color Class on Android
I have a lot of code written for later Android APIs (26+) which supports things like Color.valueOf() and numeric color channels.  I want to back-port some of that code to work with older API devices without having to change every instance of my Color class use to be something else.

Is there a way in Java to modify a class without having to create a derived class with the new functionality?

Basically, I want to augment the lesser-API Color class and code in the missing functions I use.

In my thinking, I see it conceptually like this:

```<code>augment class Color() {

    // Add in missing functions
    public static int valueOf(float r, float g, float b) {
    }

    public static int valueOf(int r, int g, int b) {
    }

    // Other functions here
}
</code>```

It would compile the default Color class adding in those additional functions so they'd be available from that point forward in that app in the lesser-API device.

答:
Is there a way in Java to modify a class without having to create a derived class with the new functionality?

There is nothing built into Java for this, sorry.

Note that the methods in question (valueOf()) are static methods. Your current code calls them like this:

```<code>Color.valueOf(foo, bar, goo);
</code>```

It would not take much to write a script that replaces those calls with:

```<code>RickColorCompat.valueOf(foo, bar, goo);
</code>```

Or, try Edit > Find > Replace in Path in Android Studio. Personally, I have a command-line gsub Ruby script that I wrote a while back for this sort of search-and-replace work.

Depending on what else you are using from Color, though, that approach may not work.

Title: Augment Base Color Class on Android

Body:
I have a lot of code written for later Android APIs (26+) which supports things like Color.valueOf() and numeric color channels.  I want to back-port some of that code to work with older API devices without having to change every instance of my Color class use to be something else.

Is there a way in Java to modify a class without having to create a derived class with the new functionality?

Basically, I want to augment the lesser-API Color class and code in the missing functions I use.

In my thinking, I see it conceptually like this:

augment class Color() {

    // Add in missing functions
    public static int valueOf(float r, float g, float b) {
    }

    public static int valueOf(int r, int g, int b) {
    }

    // Other functions here
}

It would compile the default Color class adding in those additional functions so they'd be available from that point forward in that app in the lesser-API device.

Body:
Is there a way in Java to modify a class without having to create a derived class with the new functionality?

There is nothing built into Java for this, sorry.

Note that the methods in question (valueOf()) are static methods. Your current code calls them like this:

Color.valueOf(foo, bar, goo);

It would not take much to write a script that replaces those calls with:

RickColorCompat.valueOf(foo, bar, goo);

Or, try Edit > Find > Replace in Path in Android Studio. Personally, I have a command-line gsub Ruby script that I wrote a while back for this sort of search-and-replace work.

Depending on what else you are using from Color, though, that approach may not work.


问:
Checking if isset and is true?
Is there a function to check both

if (isset($var) && $var) ?

答:
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:

$var = 'carrots'; if (!empty($var)){print 1;} //prints 1

in fact your current solution also has this type problem

$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1

as does even this

$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1

in fact... if you want to do as you described exactly, you need:

$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1

I suppose the shortest valid way to test this case is :

if (@$var === true){ print 1;}

But suppressing errors for something like this is pretty awful practice.

ContentLicense: CC BY-SA 2.5

Title: Checking if isset and is true?


问:
Sum values in double nested List of Dictionaries in C#
I have (for certain reasons not to get into now...) a List of the following structure:

```<code>List1<Dictionary1<string, List2<Dictionary2<string, string>>>>
</code>```

(I added the 1 and 2 naming for clarity).
I want to iterate over List1 and sum up Dictionary1, so that all values of identical keys in Dictionary2 will add up.

For example if each Dictionary1 item contains a Dictionary2:
{ "Price", 23},
{ "Customers", 3}

then I want to iterate over all List2 elements, and over all List1 elements, and have a final dictionary of the total sum of all prices and customers as a single key for each category:
{ "Price", 15235},
{ "Customers", 236}

I hope that's clear.. In other words, I want to sum up this double-nested list in a way that I'm left with all unique keys across all nested dictionaries and have the values summed up.

I believe it can be done with LINQ, but I'm not sure how to do that..

答:
Ok, so it looks like that you were attempting to create an Dictionary of Items with various properties (Cost, Customers, etc...), which begs the question: why not just create a class?

After all, it would be pretty simple to turn your dictionary of dictionary of items into a single dictionary of properties, such as below.

```<code>public class ItemProperties
{
public double Price {get; set;} = 0;
public int Customers {get; set;} = 0;
//Whichever other properties you were thinking of using.
}

static ItemProperties AddAll(Dictionary<string, ItemProperties> items)
ItemProperties finalitem = new ItemProperties();
{
foreach (var item in items)
{
finalitem.Price += item.Price;
finalitem.Customers += item.Customers;
//Repeat for all other existing properties.
}
return finalitem;
}
</code>```

Of course, this only works if the number and kind of properties is immutable. Another way to approach this problem would be to use TryParse to find properties in Dictionary2 that you think can be added. This is problematic however, and requires some good error checking.

```<code>static Dictionary < string, string > AddNestedDictionary(Dictionary < string, Dictionary < string, string > items) {

 Dictionary < string, string > finalitem = new Dictionary < string, string > ();
 foreach(var item in items) {
  foreach(var prop in item) {
   if (!finalitem.ContainsKey(prop.Key)) {
    finalitem.Add(prop);
   }
   double i = 0;
   if (Double.TryParse(prop.Value, out i)) {
    finalitem[prop.Key] += i;
   }
  }
 }
return finalitem;
}
</code>```

Again, not the best answer compared to the simplicity of a static class. But that would be the price you pay for nonclarity.

Body:
I have (for certain reasons not to get into now...) a List of the following structure:

List1<Dictionary1<string, List2<Dictionary2<string, string>>>>

(I added the 1 and 2 naming for clarity).
I want to iterate over List1 and sum up Dictionary1, so that all values of identical keys in Dictionary2 will add up.

For example if each Dictionary1 item contains a Dictionary2:
{ "Price", 23},
{ "Customers", 3}

then I want to iterate over all List2 elements, and over all List1 elements, and have a final dictionary of the total sum of all prices and customers as a single key for each category:
{ "Price", 15235},
{ "Customers", 236}

I hope that's clear.. In other words, I want to sum up this double-nested list in a way that I'm left with all unique keys across all nested dictionaries and have the values summed up.

I believe it can be done with LINQ, but I'm not sure how to do that..

Body:
Ok, so it looks like that you were attempting to create an Dictionary of Items with various properties (Cost, Customers, etc...), which begs the question: why not just create a class?

After all, it would be pretty simple to turn your dictionary of dictionary of items into a single dictionary of properties, such as below.

public class ItemProperties
{
public double Price {get; set;} = 0;
public int Customers {get; set;} = 0;
//Whichever other properties you were thinking of using.
}

static ItemProperties AddAll(Dictionary<string, ItemProperties> items)
ItemProperties finalitem = new ItemProperties();
{
foreach (var item in items)
{
finalitem.Price += item.Price;
finalitem.Customers += item.Customers;
//Repeat for all other existing properties.
}
return finalitem;
}

Of course, this only works if the number and kind of properties is immutable. Another way to approach this problem would be to use TryParse to find properties in Dictionary2 that you think can be added. This is problematic however, and requires some good error checking.

static Dictionary < string, string > AddNestedDictionary(Dictionary < string, Dictionary < string, string > items) {

 Dictionary < string, string > finalitem = new Dictionary < string, string > ();
 foreach(var item in items) {
  foreach(var prop in item) {
   if (!finalitem.ContainsKey(prop.Key)) {
    finalitem.Add(prop);
   }
   double i = 0;
   if (Double.TryParse(prop.Value, out i)) {
    finalitem[prop.Key] += i;
   }
  }
 }
return finalitem;
}

Again, not the best answer compared to the simplicity of a static class. But that would be the price you pay for nonclarity.


问:
Android Studio Git .gitignore vs Project > Settings > Version Control > Ignored Files
I am somewhat confused, I noticed that upon setting up my first Git repository in Android Studio all of the correct files to ignore were automatically added to the Project's Settings under Settings > Version Control > Ignored Files.

This appeared to be magic, I never told it what to ignore. Moreover, there is no .gitignore file in any directory of my project as I'm used to creating.

This being said, I can't get my second project to automatically add ignored files, and really, I just want to use the simple .gitignore method.

Does anyone know how to override Android Studio's ignored files list and simply use a .gitignore instead? I'd like the ease of copying my .gitignore to all other projects I make, it does not appear you can copy Settings > Version Control > Ignored Files.

Thank you for commenting on how I can just use .gitignore.

答:
For me it works:

Add files to be ignored (Settings -> Version Control -> Ignored Files -> Remove all ignored files -> Apply).

Then delete these files in the Android Studio project (after copying in advance).

Then copy these files back into the project.

They will turn brown color and will not commit to git/github.


问:
How to tap two points with InjectTouchInput
I want to tap two points (c[0] and c[1]) with InjectTouchInput(), but only c[1] is tapped, c[0] is not tapped.

Is there something wrong?

InjectTouchInput() is a API to emulate touch events.

https://learn.microsoft.com/ja-jp/windows/win32/api/winuser/nf-winuser-injecttouchinput

It can be called by C#.
https://www.nuget.org/packages/TCD.System.TouchInjection/

using System;
using TCD.System.TouchInjection;
using static TCD.System.TouchInjection.TouchInjector;

// https://learn.microsoft.com/ja-jp/windows/win32/api/winuser/nf-winuser-injecttouchinput?redirectedfrom=MSDN

namespace HelloWorld
{
    class Program
    {
        private static PointerTouchInfo createPointer(uint id)
        {
            var pointer = new PointerTouchInfo();
            //We can add different additional touch data
            pointer.TouchMasks = TouchMask.PRESSURE;
            pointer.Pressure = 100;

            //Pointer ID is for gesture tracking
            pointer.PointerInfo.PointerId = id;
            pointer.PointerInfo.pointerType = PointerInputType.TOUCH;

            return pointer;
        }
        private static void tap(int x, int y)
        {
            var c = new[] { createPointer(1), createPointer(2) };

            // Touch contact down
            c[0].PointerInfo.PtPixelLocation.X = x;
            c[0].PointerInfo.PtPixelLocation.Y = y;
            c[0].PointerInfo.PointerFlags = PointerFlags.INRANGE | PointerFlags.INCONTACT | PointerFlags.DOWN;
            c[1].PointerInfo.PtPixelLocation.X = x+110;
            c[1].PointerInfo.PtPixelLocation.Y = y;
            c[1].PointerInfo.PointerFlags = PointerFlags.INRANGE | PointerFlags.INCONTACT | PointerFlags.DOWN;
            InjectTouchInput(2, c);

            // Touch contact up and transition to hover
            c[0].PointerInfo.PointerFlags = PointerFlags.INRANGE | PointerFlags.UP;
            c[1].PointerInfo.PointerFlags = PointerFlags.INRANGE | PointerFlags.UP;
            InjectTouchInput(2, c);

        }
        static void Main(string[] args)
        {
            if (InitializeTouchInjection())
            {
                tap(350, 650);
            } else
            {
                Console.WriteLine("Error");
            }

            Console.WriteLine("Hello Tap Emulation!");
        }
    }
}
```

答:
Browser Touch Test

Multitouch Test

Touch events - Example - code sample

Touch events - Web API | MDN

```<code>color for touch with identifier 1 = #100
touchend
color for touch with identifier 0 = #000
touchend
touchstart:0.
color for touch with identifier 1 = #100
touchstart:0...
touchstart.
touchstart:0.
color for touch with identifier 0 = #000
touchstart:0...
touchstart.
initialized.
</code>```

Browser Test works fine.
It may not be a code issue, but an application...

Body:
Browser Touch Test

Multitouch Test

Touch events - Example - code sample

Touch events - Web API | MDN

color for touch with identifier 1 = #100
touchend
color for touch with identifier 0 = #000
touchend
touchstart:0.
color for touch with identifier 1 = #100
touchstart:0...
touchstart.
touchstart:0.
color for touch with identifier 0 = #000
touchstart:0...
touchstart.
initialized.

Browser Test works fine.
It may not be a code issue, but an application...