问:
Sphinx toctree directive: How to hide the caption from being displayed?
If I have the following in index.rst:

```<code>This Section
------------

.. toctree::
   :caption: This Section
   :maxdepth: 1

   this_section/intro
   this_section/body
   this_section/outro
</code>```

Then "This Section" would show up twice in the generated HTML file: One as a
, one as a
. How can I get rid of the latter, or make :caption: generate a
? I can't simply remove :caption: because the sidebar (I'm using ReadTheDoc theme) relies on this option to correctly generate a TOC tree.

答:
I ended up removing this with css by adding this to custom.css in the _static directory:

section#setup span.caption-text {
    display: none;
}
```
<p>And having this in my <code>conf.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>html_static_path = ['_static']
html_css_files = ['custom.css']
</code>```

Body:
If I have the following in index.rst:

This Section
------------

.. toctree::
   :caption: This Section
   :maxdepth: 1

   this_section/intro
   this_section/body
   this_section/outro

Then "This Section" would show up twice in the generated HTML file: One as a
, one as a
. How can I get rid of the latter, or make :caption: generate a
? I can't simply remove :caption: because the sidebar (I'm using ReadTheDoc theme) relies on this option to correctly generate a TOC tree.

Body:
I ended up removing this with css by adding this to custom.css in the _static directory:

section#setup span.caption-text {
    display: none;
}

And having this in my conf.py:

html_static_path = ['_static']
html_css_files = ['custom.css']


来源: stackexchange

问:
How to mat-button-toggle by default selected in angular
How can I set default selected last button in toggle group.

This is my code.

```<code><mat-button-toggle-group #group="matButtonToggleGroup">
    <mat-button-toggle value="Heritage">
        <span>Heritage</span>
    </mat-button-toggle>
    <mat-button-toggle value="Nature">
        <span>Nature</span>
    </mat-button-toggle>
    <mat-button-toggle value="People">
        <span>People</span>
    </mat-button-toggle>
    <mat-button-toggle value="All">
        <span>All</span>
    </mat-button-toggle>
</mat-button-toggle-group>
</code>```

答:
Don't forget to import MatButtonToggleModule in your module.ts

Use formControlName to link the form to the button toggle

test.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
    public form: FormGroup;

    constructor(private formBuilder: FormBuilder) {
        this.form = this.formBuilder.group({
            choices: [1] // <-- Default value 1
        });
    }

    ngOnInit(): void {}
}
</code>```

test.component.html

```<code><form [formGroup]="form">
    <mat-button-toggle-group formControlName="choices">
        <mat-button-toggle [value]="1">Choice 1</mat-button-toggle>
        <mat-button-toggle [value]="2">Choice 2</mat-button-toggle>
        <mat-button-toggle [value]="3">Choice 3</mat-button-toggle>
    </mat-button-toggle-group>
</form>
</code>```

Works fine with Angular 12

ContentLicense: CC BY-SA 4.0

Body:
How can I set default selected last button in toggle group.

This is my code.

<mat-button-toggle-group #group="matButtonToggleGroup">
    <mat-button-toggle value="Heritage">
        Heritage
    </mat-button-toggle>
    <mat-button-toggle value="Nature">
        Nature
    </mat-button-toggle>
    <mat-button-toggle value="People">
        People
    </mat-button-toggle>
    <mat-button-toggle value="All">
        All
    </mat-button-toggle>
</mat-button-toggle-group>

Body:
Don't forget to import MatButtonToggleModule in your module.ts

Use formControlName to link the form to the button toggle

test.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
    public form: FormGroup;

    constructor(private formBuilder: FormBuilder) {
        this.form = this.formBuilder.group({
            choices: [1] // <-- Default value 1
        });
    }

    ngOnInit(): void {}
}

test.component.html

<form [formGroup]="form">
    <mat-button-toggle-group formControlName="choices">
        <mat-button-toggle [value]="1">Choice 1</mat-button-toggle>
        <mat-button-toggle [value]="2">Choice 2</mat-button-toggle>
        <mat-button-toggle [value]="3">Choice 3</mat-button-toggle>
    </mat-button-toggle-group>
</form>

Works fine with Angular 12


问:
How can I create a plugin in guidewire?
I can't find de main steps to create a plugin in guidewire.
¿Is there any simple way to understand that?
Until now I did this steps

Modify the messaging-config.xml
Create a class in gosu to use the plugin
Create the plugin

答:
It's not clear whether you want to create a new plugin like a new custom functionality plugin or utilize Transport/Reply Plugin for a message destination.

If you want to implement a new custom plugin, then there are several steps as listed below.

Create Plugin class

Implement the interfaces

Implement code for the methods

Create plugin registry file.

Configure registry file

Deploy.

If you just want to learn how to do it, there is a detailed video available if you have access to a GW learning account.

Title: How can I create a plugin in guidewire?


问:
How to POST multiple images to FastAPI server using Python requests?
I would like to send multiple images to FastAPI backend using Python requests.

Server side

```<code>from fastapi import FastAPI, UploadFile, File
from typing import List
app = FastAPI()

@app.post("/")
def index(file: List[UploadFile] = File(...)):
    list_image = []
    for i in file:
        list_image.append(i.filename)
    return {"list_image": list_image}
</code>```

Client side

Currently, I can only send a request with a single image. However, I would like to be able to send multiple images.

```<code>import requests
import cv2

frame = cv2.imread("../image/3.png")
imencoded = cv2.imencode(".jpg", frame)[1]
file = {'file': ('image.jpg', imencoded.tostring(),
                    'image/jpeg', {'Expires': '0'})}

response = requests.post("http://127.0.0.1:8000/", files=file)
</code>```

答:
Use as below:

```<code>import requests

url = 'http://127.0.0.1:8000/'
files = [('file', open('images/1.png', 'rb')), ('file', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files=files)
</code>```

or, you could also use:

```<code>import requests
import glob

path = glob.glob("images/*", recursive=True) # images' path
files = [('file', open(img, 'rb')) for img in path]
url = 'http://127.0.0.1:8000/'
resp = requests.post(url=url, files=files)
</code>```

Body:
I would like to send multiple images to FastAPI backend using Python requests.

Server side

from fastapi import FastAPI, UploadFile, File
from typing import List
app = FastAPI()

@app.post("/")
def index(file: List[UploadFile] = File(...)):
    list_image = []
    for i in file:
        list_image.append(i.filename)
    return {"list_image": list_image}

Client side

Currently, I can only send a request with a single image. However, I would like to be able to send multiple images.

import requests
import cv2

frame = cv2.imread("../image/3.png")
imencoded = cv2.imencode(".jpg", frame)[1]
file = {'file': ('image.jpg', imencoded.tostring(),
                    'image/jpeg', {'Expires': '0'})}

response = requests.post("http://127.0.0.1:8000/", files=file)

Body:
Use as below:

import requests

url = 'http://127.0.0.1:8000/'
files = [('file', open('images/1.png', 'rb')), ('file', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files=files)

or, you could also use:

import requests
import glob

path = glob.glob("images/*", recursive=True) # images' path
files = [('file', open(img, 'rb')) for img in path]
url = 'http://127.0.0.1:8000/'
resp = requests.post(url=url, files=files)


问:
How do I break a sentence using CSS?
I'm trying to break a sentence using CSS. I don't want to break the words, but break the sentence. So for example if there's a sentence like Hello world it's test. It should not break any of the words in that sentence and put it in a new line. It should only put new words in a new line. Here's the CSS that I have so far:

See attached image. Notice our some words break apart? I want a new word in a new line, not the characters in a single word to break.

.Main_Topics {
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.546) 0%, rgba(0, 0, 0, 0.539) 23.54%, rgba(0, 0, 0, 0.469) 46.07%, rgba(0, 0, 0, 0) 58.09%), url(/assets/jerry.jpg);
  border-radius: 18px;
  min-height: 424px;
  width: 100%;
  color: white;
  padding: 47px 34px;
  margin: 120px auto;
  text-align: left;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: right top;
}

.Main_Topics h2 {
  font-size: 40px;
  margin-bottom: 30px;
}

.Main_Topics p {
  max-width: 552px;
  margin-bottom: 40px;
}

.Main_Topics .topic {
  background: #FFFFFF;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
  padding: 34px;
  height: 150px;
  text-align: center;
  font-size: 14px;
  color: #000000;
  ;
}

.category-wrapper {
  position: relative;
  max-width: 100%;
  height: 150px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: hidden;
}

.category-wrapper ul {
  height: 150px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.category-wrapper .topic {
  display: inline-block;
  width: 140px;
  height: 150px;
  margin-right: 26px;
  overflow-wrap: normal;
  vertical-align: top;
}

.category-wrapper .topic div {
  word-wrap: break-word;
  /* IE 5.5-7 */
  white-space: -moz-pre-wrap;
  /* Firefox 1.0-2.0 */
  white-space: pre-wrap;
  /* current browsers */
  font-size: 14px;
  height: 150px;
}

.paddle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3em;
  background: transparent;
  border: none;
}

.left-paddle {
  left: 0;
  background: transparent;
  border: none;
}

.right-paddle {
  right: 0;
  background: transparent;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row Main_Topics">
  <h2>What do you need help with?</h2>
  <p>Our experts are one Zoom call area. They'll give you honest advice. No BS. Straightforward and to the point.</p>
  <div class="category-wrapper">
    <ul>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
    </ul>
    <div class="paddles">
      <button class="left-paddle paddle hidden">
                                <img src="/assets/paddle-left.svg" />
                            </button>
      <button class="right-paddle paddle">
                                <img src="/assets/paddle-right.svg" />
                            </button>
    </div>
  </div>
</div></code>```

答: You defined white-space: nowrap;for your .category-wrapper ul which apparently also applies this setting to its li children. To avoid that, add white-space: normal; to the children ( .category-wrapper .topic)

Title: How do I break a sentence using CSS?

Body:
I'm trying to break a sentence using CSS. I don't want to break the words, but break the sentence. So for example if there's a sentence like Hello world it's test. It should not break any of the words in that sentence and put it in a new line. It should only put new words in a new line. Here's the CSS that I have so far:

See attached image. Notice our some words break apart? I want a new word in a new line, not the characters in a single word to break.

.Main_Topics {
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.546) 0%, rgba(0, 0, 0, 0.539) 23.54%, rgba(0, 0, 0, 0.469) 46.07%, rgba(0, 0, 0, 0) 58.09%), url(/assets/jerry.jpg);
  border-radius: 18px;
  min-height: 424px;
  width: 100%;
  color: white;
  padding: 47px 34px;
  margin: 120px auto;
  text-align: left;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: right top;
}

.Main_Topics h2 {
  font-size: 40px;
  margin-bottom: 30px;
}

.Main_Topics p {
  max-width: 552px;
  margin-bottom: 40px;
}

.Main_Topics .topic {
  background: #FFFFFF;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
  padding: 34px;
  height: 150px;
  text-align: center;
  font-size: 14px;
  color: #000000;
  ;
}

.category-wrapper {
  position: relative;
  max-width: 100%;
  height: 150px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: hidden;
}

.category-wrapper ul {
  height: 150px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.category-wrapper .topic {
  display: inline-block;
  width: 140px;
  height: 150px;
  margin-right: 26px;
  overflow-wrap: normal;
  vertical-align: top;
}

.category-wrapper .topic div {
  word-wrap: break-word;
  /* IE 5.5-7 */
  white-space: -moz-pre-wrap;
  /* Firefox 1.0-2.0 */
  white-space: pre-wrap;
  /* current browsers */
  font-size: 14px;
  height: 150px;
}

.paddle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3em;
  background: transparent;
  border: none;
}

.left-paddle {
  left: 0;
  background: transparent;
  border: none;
}

.right-paddle {
  right: 0;
  background: transparent;
  border: none;
}

What do you need help with?

Our experts are one Zoom call area. They'll give you honest advice. No BS. Straightforward and to the point.

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

      <button class="left-paddle paddle hidden">

                            </button>
      <button class="right-paddle paddle">

                            </button>


问:
Remove Gitlab docker containers
Recently i tried to install Gitlab on Ubuntu machine using docker and docker-compose. This was only done for testing so i can later install it on other machine.

However, i have a problem with removing/deleting gitlab containers.

I tried docker-compose down and killing all processes related to gitlab containers but they keep restarting even if i somehow manage to delete images.

This is my docker-compose.yml file

```<code>version: "3.6"
    services:
      gitlab:
        image: gitlab/gitlab-ee:latest
        ports:
          - "2222:22"
          - "8080:80"
          - "8081:443"
        volumes:
          - $GITLAB_HOME/data:/var/opt/gitlab
          - $GITLAB_HOME/logs:/var/log/gitlab
          - $GITLAB_HOME/config:/etc/gitlab
        shm_size: '256m'
        environment:
          GITLAB_OMNIBUS_CONFIG: "from_file('/omnibus_config.rb')"
        configs:
          - source: gitlab
            target: /omnibus_config.rb
        secrets:
          - gitlab_root_password
      gitlab-runner:
        image: gitlab/gitlab-runner:alpine
        deploy:
          mode: replicated
          replicas: 4
    configs:
      gitlab:
        file: ./gitlab.rb
    secrets:
      gitlab_root_password:
        file: ./root_password.txt
</code>```

Some of the commands i tried to kill processes:

```<code>kill -9 $(ps aux | grep gitlab | awk '{print $2}')
docker rm -f $(docker ps -aqf name="gitlab") && docker rmi --force $(docker images | grep gitlab | awk '{print $3}')
</code>```

I also tried to update containers with no restart policy:

```<code>docker update --restart=no container-id
</code>```

But nothing of this seems to work.

This is docker ps response:

```<code>591e43a3a8f8   gitlab/gitlab-ee:latest       "/assets/wrapper"        4 minutes ago    Up 4 minutes (health: starting)   22/tcp, 80/tcp, 443/tcp                           mystack_gitlab.1.0r77ff84c9iksmdg6apakq9yr
6f0887a8c4b1   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.3.639u8ht9vt01r08fegclfyrr8
73febb9bb8ce   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.4.m1z1ntoewtf3ipa6hap01mn0n
53f63187dae4   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.2.9vo9pojtwveyaqo166ndp1wja
0bc954c9b761   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.1.pq0njz94v272s8if3iypvtdqo
</code>```

Any ideas of what i should be looking for?

答:
I found the solution. Problem was that i didn't use

```<code>docker-compose up -d
</code>```

to start my containers. Instead i used

```<code>docker stack deploy --compose-file docker-compose.yml mystack
</code>```

as it is written in documentation.

Since i didn't know much about docker stack, i did a quick internet search.
This is the article that i found:
https://vsupalov.com/difference-docker-compose-and-docker-stack/

The Difference Docker stack is ignoring “build” instructions. You
can’t build new images using the stack commands. It need pre-built
images to exist. So docker-compose is better suited for development
scenarios.

There are also parts of the compose-file specification which are
ignored by docker-compose or the stack commands.

As i understand, the problem is that stack only uses pre-built images and ignores some of the docker-compose commands such as restart policy.
That's why

```<code>docker update --restart=no container-id
</code>```

didn't work.

I still don't understand why killing all the processes and removing containers/images didn't work. I guess there must be some parent process that i didn't found.

Title: Remove Gitlab docker containers

Body:
Recently i tried to install Gitlab on Ubuntu machine using docker and docker-compose. This was only done for testing so i can later install it on other machine.

However, i have a problem with removing/deleting gitlab containers.

I tried docker-compose down and killing all processes related to gitlab containers but they keep restarting even if i somehow manage to delete images.

This is my docker-compose.yml file

version: "3.6"
    services:
      gitlab:
        image: gitlab/gitlab-ee:latest
        ports:
          - "2222:22"
          - "8080:80"
          - "8081:443"
        volumes:
          - $GITLAB_HOME/data:/var/opt/gitlab
          - $GITLAB_HOME/logs:/var/log/gitlab
          - $GITLAB_HOME/config:/etc/gitlab
        shm_size: '256m'
        environment:
          GITLAB_OMNIBUS_CONFIG: "from_file('/omnibus_config.rb')"
        configs:
          - source: gitlab
            target: /omnibus_config.rb
        secrets:
          - gitlab_root_password
      gitlab-runner:
        image: gitlab/gitlab-runner:alpine
        deploy:
          mode: replicated
          replicas: 4
    configs:
      gitlab:
        file: ./gitlab.rb
    secrets:
      gitlab_root_password:
        file: ./root_password.txt

Some of the commands i tried to kill processes:

kill -9 $(ps aux | grep gitlab | awk '{print $2}')
docker rm -f $(docker ps -aqf name="gitlab") && docker rmi --force $(docker images | grep gitlab | awk '{print $3}')

I also tried to update containers with no restart policy:

docker update --restart=no container-id

But nothing of this seems to work.

This is docker ps response:

591e43a3a8f8   gitlab/gitlab-ee:latest       "/assets/wrapper"        4 minutes ago    Up 4 minutes (health: starting)   22/tcp, 80/tcp, 443/tcp                           mystack_gitlab.1.0r77ff84c9iksmdg6apakq9yr
6f0887a8c4b1   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.3.639u8ht9vt01r08fegclfyrr8
73febb9bb8ce   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.4.m1z1ntoewtf3ipa6hap01mn0n
53f63187dae4   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.2.9vo9pojtwveyaqo166ndp1wja
0bc954c9b761   gitlab/gitlab-runner:alpine   "/usr/bin/dumb-init …"   16 minutes ago   Up 16 minutes                                                                       mystack_gitlab-runner.1.pq0njz94v272s8if3iypvtdqo

Any ideas of what i should be looking for?

Body:
I found the solution. Problem was that i didn't use

docker-compose up -d

to start my containers. Instead i used

docker stack deploy --compose-file docker-compose.yml mystack

as it is written in documentation.

Since i didn't know much about docker stack, i did a quick internet search.
This is the article that i found:
https://vsupalov.com/difference-docker-compose-and-docker-stack/

The Difference Docker stack is ignoring “build” instructions. You
can’t build new images using the stack commands. It need pre-built
images to exist. So docker-compose is better suited for development
scenarios.

There are also parts of the compose-file specification which are
ignored by docker-compose or the stack commands.

As i understand, the problem is that stack only uses pre-built images and ignores some of the docker-compose commands such as restart policy.
That's why

docker update --restart=no container-id

didn't work.

I still don't understand why killing all the processes and removing containers/images didn't work. I guess there must be some parent process that i didn't found.


问:
The item you tried to buy is no longer available?
I have implemented In-App-Purchase on iPad and updated application with new code.

It's approved by apple but some of mine customer not able to download our application after that I have tried to purchase application on my own iPad but I have got same error why?.

I think it's an problem with updates but I am not able to figure it out please, give me some idea how I can avoid this?

I think this problems comes to customer who have already applications on there devices but they are not able to update there application with new update and getting error.

答: Unless you provide some kind of log files, just check through your code to make sure that the product IDs are correct and that your entitlements file works. If you build the app for development, does the in-app purchase work?</p>

ContentLicense: CC BY-SA 3.0


问:
Dropping down a colum in Excel with xlsxwriter
I'm looking to be able to run the script everytime I get home from work and just add in how much hours I worked and the pay and have it save in a new line each time in Excel but it just keeps writing over the last value I put in. I'm using xlsxwriter.

```<code>import xlsxwriter

hours = input('|         Hours worked >>')
HWadge = input('|          Hourly pay >> £')

hours = int(hours)
Hwadge = int(HWadge)
total = hours * Hwadge

print('Money for shift = ','*', total, '*')

workbook = xlsxwriter.Workbook('Pay.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

my_list = [hours, Hwadge, total,]

# How do I make it so I can add a value each day and it just drop down a column?
</code>```

I'm looking for this output:

答:
You can use openpyxl to edit an excel sheet:

```<code>from openpyxl import load_workbook, Workbook

hours = input('|         Hours worked >>')
HWadge = input('|          Hourly pay >> £')

hours = int(hours)
Hwadge = int(HWadge)
total = hours * Hwadge
try:
    wb = load_workbook("possible_answer.xlsx") # loading existing workbook
except FileNotFoundError: # of if the excel file is doesn't exist
    wb = Workbook()
ws = wb.active
date = ("date", "08/02/2022")
hours_col = ("hours", f"${hours}")
Hwadge_col = ("Hwadge", f"${Hwadge}")
total_col = ("total", f"${total}")
my_list = [date, hours_col, Hwadge_col, total_col, ]
for row in my_list:
    ws.append(row)
ws.append([" "])

wb.save("possible_answer.xlsx")
</code>```

Body:
I'm looking to be able to run the script everytime I get home from work and just add in how much hours I worked and the pay and have it save in a new line each time in Excel but it just keeps writing over the last value I put in. I'm using xlsxwriter.

import xlsxwriter

hours = input('|         Hours worked >>')
HWadge = input('|          Hourly pay >> £')

hours = int(hours)
Hwadge = int(HWadge)
total = hours * Hwadge

print('Money for shift = ','*', total, '*')

workbook = xlsxwriter.Workbook('Pay.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

my_list = [hours, Hwadge, total,]

# How do I make it so I can add a value each day and it just drop down a column?

I'm looking for this output:

Body:
You can use openpyxl to edit an excel sheet:

from openpyxl import load_workbook, Workbook

hours = input('|         Hours worked >>')
HWadge = input('|          Hourly pay >> £')

hours = int(hours)
Hwadge = int(HWadge)
total = hours * Hwadge
try:
    wb = load_workbook("possible_answer.xlsx") # loading existing workbook
except FileNotFoundError: # of if the excel file is doesn't exist
    wb = Workbook()
ws = wb.active
date = ("date", "08/02/2022")
hours_col = ("hours", f"${hours}")
Hwadge_col = ("Hwadge", f"${Hwadge}")
total_col = ("total", f"${total}")
my_list = [date, hours_col, Hwadge_col, total_col, ]
for row in my_list:
    ws.append(row)
ws.append([" "])

wb.save("possible_answer.xlsx")


问:
Authenticate AWS Opensearch dashboard using LDAP via keycloak
Requirement

I am working on a client project where we need to setup our AWS managed OpenSearch dashboard (Kibana). As per the requirement, we should use keycloak for SAML configurations. Also need to use LDAP as user federation.

Current Setup

AWS OpenSearch setup is completed and able to login with the master user credentials.

Integration of Keycloak with OpenSearch dashboard is done. I am able to login to the OpenSearch dashboard using keycloak local user by adding it in the all_access group in Dashboard (kibana).

LDAP integration with Keycloak is also completed. I can sync all LDAP users within Keycloak and able to login with individual LDAP users when adding them in the all_access group in Dashboard (Kibana).

Issue/Open tasks

How can I add the entire keycloak group to the OpenSearch Dashboard so I do not have to add individual users. I tried adding the group name in the dashboard under backend role section but it does not work. Also tried a few mappings (not sure if they were correct) but got no luck. Every time it gives "missing role-contact your administrator"

Same issue with LDAP groups as well, I can sync all LDAP groups within my Keycloak but not sure how to map them with OpenSearch Dashboard to login.

Ultimate Goal

Create two groups, one as admin and other as limitedaccess so that users who are part of admin group can login with the assigned permissions and users in limitedaccess group can login with their permissions.

I do not want to add individual users in the Dashboard rather they should be able to login directly based on role/group mapping.

答:
The issue is resolved.

Following are the things I did, which may be useful for others looking for similar setup.

Created two groups in my Keycloak. "admin" and "limited".

Created two roles "admin_role" and "limited_role".

Made the limited group as default group and the limited_role as default role so the new users will directly get the limited permissions.

Next, which i was missing all the time (and thanks to other stack overflow answers) was to enable the Single Role mapping. For this, Go to Client scope role_list -->  mappers --> role list --> enable "Single Role attribute"

Added the "Role" keyword in OpenSearch in the role key section (under additional settings in AWS OpenSearch SAML configs.). Also mentioned a generic user in the SAML master user section (generic user which I created in Keycloak) so that I can gain admin privileges to add backend roles in OpenSearch Dashboard.

Finally, logged in to my OpenSearch with this generic user. Go to the security -->  Roles --> Manage mapping --> backend roles --> added my admin_role to the all_access and  limited_role to the read roles.

Now I am able to login with all the users who are part of the respective groups in Keycloak.


问:
The above error occurred in the <Provider> component
can't find way how to resolve this problem.

Errors in browser:

Uncaught Error: Invalid hook call. Hooks can only be called inside
of the body of a function component. This could happen for one of
the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.

The above error occurred in the  component:

Provider@http://localhost:3000/static/js/bundle.js:49534:15

Consider adding an error boundary to your tree to customize error
handling behavior. Visit https://reactjs.org/link/error-boundaries
to learn more about error boundaries.

INDEX.JS

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Router from './Router';

import { createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import { Provider } from 'react-redux'
import rootReducer from './Redux/Reducers/index.js'

const store = createStore( rootReducer, composeWithDevTools() )

ReactDOM.render(
  <Provider store={ store }>
    <Router />
  </Provider >,
  document.getElementById( 'root' ) );
</code>```

Reducers/index.js

```<code>import loginPageReducer from './LoginPage.js'
import { combineReducers } from 'redux'

const rootReducer = combineReducers( {
   loginPageReducer
} )

export default rootReducer
</code>```

Reducers/LoginPage.js

```<code>const INIT_STATE = {
   view: 'login',
   msg: '',
   loader: false,
}

const loginPageReducer = ( state = INIT_STATE, action ) =>
{

   switch ( action.type )
   {
      case "LOADER_OFF":
         return state.loader = false

      case "LOADER_ON":
         return state.loader = true

      case "MSG_SET":
         return state.msg = action.msg

      case "MSG_CLEAR":
         return state.msg = ''

      case "VIEW_CHANGE":
         return state.view = action.view

      default:
         return state;
   }
}

export default loginPageReducer
</code>```

loginPage component

```<code>import React, { useState } from 'react'
import '../Styles/loginPage.scss'
import axios from 'axios'
import { useDispatch, useSelector } from 'react-redux'
import loginPageActions from '../Redux/actions/LoginPage'

export default function LoginPage ()
{
   const { msg_clear, msg_set, loader_off, loader_on, view_change } = loginPageActions
   const msg = useSelector( state => state.LoginPageReducer.msg )
   const view = useSelector( state => state.LoginPageReducer.view )
   const loader = useSelector( state => state.LoginPageReducer.loader )
   const dispatch = useDispatch()

   const [inputs, setInputs] = useState( {
      username: '',
      password: '',
      password2: '',
      email: ''
   } )

   const handleInputs = function ( e )
   {
      const { name, value } = e.target
      setInputs( { ...inputs, [name]: value } )
   }

   const handleSubmit = async ( e ) =>
   {
      try
      {
         e.preventDefault();
         dispatch( msg_clear() )
         dispatch( loader_on() )

         if ( view === login)
         {
            // logowanie
            const query = await axios( {
               method: 'post',
               url: '/api/users/login',
               data: {
                  username: inputs.username,
                  password: inputs.password
               }
            } )

            const token = query.data.token
            localStorage.setItem( "token", token );
            return window.location.href = "/kalkulator"

         }
         else
         {
            //rejestracja
            const query = await axios( {
               method: 'post',
               url: '/api/users/register',
               data: {
                  username: inputs.username,
                  password: inputs.password,
                  password2: inputs.password2,
                  email: inputs.email
               }
            } )

            if ( query.status === 200 )
            {
               dispatch( msg_set( 'Zarejestrowano, możesz się zalogować' ) )
               dispatch( view_change( true ) )
            }
         }
      }
      catch ( err )
      {
         if ( err ) return dispatch( msg_set( err.response.data.msg ) )
      }
      finally
      {
         dispatch( loader_off() )
      }
   }

   /////////////
   /// Renderowanie widoku
   /////////////

   return (
      <main>
         <div id="MainContainerStyle">
            <span id="thatWhitePartOnBottom"></span>
            <header>
               <h1 id="HeaderH1" >Kalkulator mas</h1>
            </header>

            <button className="Buttons" onClick={ () => dispatch( view_change( !view ) ) }>
               { view ?
                  `Already have account? Click to log in!`
                  :
                  `Doesn't have account? Click me if you want to register new one` }
            </button>

            <form onSubmit={ handleSubmit } id="Form">
               <input type="text"
                  value={ inputs.username }
                  placeholder={ view ? 'username' : 'Login or E-mail' }
                  name="username" required onChange={ handleInputs }
               />

               { view ?
                  <input type="email"
                     placeholder="email"
                     name="email"
                     value={ inputs.email }
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="password"
                  value={ inputs.password }
                  placeholder="Password:"
                  name="password"
                  required
                  onChange={ handleInputs }
               />

               { view ?
                  <input type="password"
                     value={ inputs.password2 }
                     placeholder="Password again:"
                     name="password2"
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="submit" className="Buttons" />

               { loader ? <span className="loader"></span> : null }
               { msg !== '' ? <p className="msg">{ msg }</p> : null }
            </form>
         </div>
      </main>
   )
}
</code>```

Router

```<code>import { BrowserRouter, Routes, Route } from "react-router-dom";
import './Styles/global.scss'

import LoginPage from "./Pages/LoginPage";
import Kalkulator from "./Pages/Kalkulator";

function App ()
{
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={ <LoginPage /> } />
          <Route path="/kalkulator" element={ <Kalkulator /> } />
        </Routes>
      </BrowserRouter>
    </>
  )
}

export default App;
</code>```

答:
might be this problem: https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.

..or maybe "react-redux" is not installed, check package.json

Body:
can't find way how to resolve this problem.

Errors in browser:

Uncaught Error: Invalid hook call. Hooks can only be called inside
of the body of a function component. This could happen for one of
the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.

The above error occurred in the  component:

Provider@http://localhost:3000/static/js/bundle.js:49534:15

Consider adding an error boundary to your tree to customize error
handling behavior. Visit https://reactjs.org/link/error-boundaries
to learn more about error boundaries.

INDEX.JS

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './Router';

import { createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import { Provider } from 'react-redux'
import rootReducer from './Redux/Reducers/index.js'

const store = createStore( rootReducer, composeWithDevTools() )

ReactDOM.render(
  <Provider store={ store }>
    <Router />
  </Provider >,
  document.getElementById( 'root' ) );

Reducers/index.js

import loginPageReducer from './LoginPage.js'
import { combineReducers } from 'redux'

const rootReducer = combineReducers( {
   loginPageReducer
} )

export default rootReducer

Reducers/LoginPage.js

const INIT_STATE = {
   view: 'login',
   msg: '',
   loader: false,
}

const loginPageReducer = ( state = INIT_STATE, action ) =>
{

   switch ( action.type )
   {
      case "LOADER_OFF":
         return state.loader = false

      case "LOADER_ON":
         return state.loader = true

      case "MSG_SET":
         return state.msg = action.msg

      case "MSG_CLEAR":
         return state.msg = ''

      case "VIEW_CHANGE":
         return state.view = action.view

      default:
         return state;
   }
}

export default loginPageReducer

loginPage component

import React, { useState } from 'react'
import '../Styles/loginPage.scss'
import axios from 'axios'
import { useDispatch, useSelector } from 'react-redux'
import loginPageActions from '../Redux/actions/LoginPage'

export default function LoginPage ()
{
   const { msg_clear, msg_set, loader_off, loader_on, view_change } = loginPageActions
   const msg = useSelector( state => state.LoginPageReducer.msg )
   const view = useSelector( state => state.LoginPageReducer.view )
   const loader = useSelector( state => state.LoginPageReducer.loader )
   const dispatch = useDispatch()

   const [inputs, setInputs] = useState( {
      username: '',
      password: '',
      password2: '',
      email: ''
   } )

   const handleInputs = function ( e )
   {
      const { name, value } = e.target
      setInputs( { ...inputs, [name]: value } )
   }

   const handleSubmit = async ( e ) =>
   {
      try
      {
         e.preventDefault();
         dispatch( msg_clear() )
         dispatch( loader_on() )

         if ( view === login)
         {
            // logowanie
            const query = await axios( {
               method: 'post',
               url: '/api/users/login',
               data: {
                  username: inputs.username,
                  password: inputs.password
               }
            } )

            const token = query.data.token
            localStorage.setItem( "token", token );
            return window.location.href = "/kalkulator"

         }
         else
         {
            //rejestracja
            const query = await axios( {
               method: 'post',
               url: '/api/users/register',
               data: {
                  username: inputs.username,
                  password: inputs.password,
                  password2: inputs.password2,
                  email: inputs.email
               }
            } )

            if ( query.status === 200 )
            {
               dispatch( msg_set( 'Zarejestrowano, możesz się zalogować' ) )
               dispatch( view_change( true ) )
            }
         }
      }
      catch ( err )
      {
         if ( err ) return dispatch( msg_set( err.response.data.msg ) )
      }
      finally
      {
         dispatch( loader_off() )
      }
   }

   /////////////
   /// Renderowanie widoku
   /////////////

   return (

Kalkulator mas

            <button className="Buttons" onClick={ () => dispatch( view_change( !view ) ) }>
               { view ?
                  `Already have account? Click to log in!`
                  :
                  `Doesn't have account? Click me if you want to register new one` }
            </button>

            <form onSubmit={ handleSubmit } id="Form">
               <input type="text"
                  value={ inputs.username }
                  placeholder={ view ? 'username' : 'Login or E-mail' }
                  name="username" required onChange={ handleInputs }
               />

               { view ?
                  <input type="email"
                     placeholder="email"
                     name="email"
                     value={ inputs.email }
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="password"
                  value={ inputs.password }
                  placeholder="Password:"
                  name="password"
                  required
                  onChange={ handleInputs }
               />

               { view ?
                  <input type="password"
                     value={ inputs.password2 }
                     placeholder="Password again:"
                     name="password2"
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="submit" className="Buttons" />

               { loader ?  : null }
               { msg !== '' ?
{ msg }
 : null }
            </form>

   )
}

Router

import { BrowserRouter, Routes, Route } from "react-router-dom";
import './Styles/global.scss'

import LoginPage from "./Pages/LoginPage";
import Kalkulator from "./Pages/Kalkulator";

function App ()
{
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={ <LoginPage /> } />
          <Route path="/kalkulator" element={ <Kalkulator /> } />
        </Routes>
      </BrowserRouter>
    </>
  )
}

export default App;


问:
How to create a OneNote section template
How do you create a template that includes multiple section groups and pages? My use case is:

I take daily notes on how my day went, progress, ways to improve, goals for tomorrow etc. These notes are summarised within a weekly reflection which, in turn, are summarised within monthly and yearly segments. These are bundled up into the Section Group for that year (e.g. 2017) with Month section groups, week section groups, and then days as pages within.

I'd like to create a template which I can import/copy/insert into OneNote whenever I require a new year. The question is, how?

答: Really low tech. Create a template section or section group with unnamed titles and save a blank version in a notebook somewhere. Then just copy and paste it to the section you want your template to be.</p>


问:
Postgres duplicate column based on value in column
I've the following table in postgresql

id
product
customer
price
amount

1
Television
Alfred
12.00
1

2
Radio
Richard
20.00
3

3
Mobile
Richard
40.00
5

Is there some way via SQL to duplicate the line n-times in case the amount is greater than one?

This is how the table should look like after running the query:

id
product
customer
price
amount

1
Television
Alfred
12.00
1

2
Radio
Richard
20.00
3

3
Mobile
Richard
40.00
5

4
Radio
Richard
20.00
3

5
Radio
Richard
20.00
3

6
Mobile
Richard
40.00
5

7
Mobile
Richard
40.00
5

8
Mobile
Richard
40.00
5

9
Mobile
Richard
40.00
5

f.e. we now have 3 Radios that do match with the amount 3. Unfortunately, I do not even find a correct Google search term.

答:
You can do a cross join using generate_series()

```<code>select row_number() over () as id,
       t.product, t.customer, t.price,
       t.amount
from the_table t
   cross join generate_series(1, t.amount) as x
</code>```

Body:
You can do a cross join using generate_series()

select row_number() over () as id,
       t.product, t.customer, t.price,
       t.amount
from the_table t
   cross join generate_series(1, t.amount) as x


问:
im trying to count returned documents in mongodb with facet and got issue
im trying to count the results with $facet and when im adding count its counting but not showing the $project results, if I remove the count then i see the results, im new to mongoDb and still learning , any help will be apprecieted , thanks
the code im using right now

```<code>db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        },
         {
            $count: "documents"
          }

      ]
    }
  }
])
</code>```

playground

答:
To count the documents you can use $size after the $facet stage.

The main problem in your query is you want to access the documents field into the $facet but the documents are available after $facet is completed.

```<code>db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        }
        ]
      }
    },
    {
      "$addFields": {
        "nDocuments": {
          "$size": "$documents"
        }
      }
    }
  ])
</code>```

Example here

Body:
im trying to count the results with $facet and when im adding count its counting but not showing the $project results, if I remove the count then i see the results, im new to mongoDb and still learning , any help will be apprecieted , thanks
the code im using right now

db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        },
         {
            $count: "documents"
          }

      ]
    }
  }
])

playground

Body:
To count the documents you can use $size after the $facet stage.

The main problem in your query is you want to access the documents field into the $facet but the documents are available after $facet is completed.

db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        }
        ]
      }
    },
    {
      "$addFields": {
        "nDocuments": {
          "$size": "$documents"
        }
      }
    }
  ])

Example here


问:
How to detect the language of text using qt?
I have a lot of txt files containing product description written in English or other languages. I'm only interested in the txt files containing English. I do not know all the languages the txt may be written in. Those non-English description may also contain English characters such as a url. Is there any algorithm to calculate the ratio of English characters (excluding punctuation) so that if there are more than 50% non-English characters in the txt file, the file will be discarded.</p>

答:
Here is a Wikipedia help page that gives hints on analyzing languages based on the character set used. One would still need to convert that to code, but it is a hint. There's probably no foul-proof way of detecting english. There are other languages as well that do not use diacritics, or a particular text may not. Just from the character set, Dutch and Afrikaans are very close to english, for instance.

So you can use the table to give an estimate on the probability of a piece of text being english, but getting it 100% is hard.


问:
Pass Python bytes to C/C++ function using swig?
How do you pass a bytes value from Python (like data loaded from a file with open('my file.dat', 'rb').read()) to a C/C++ function using swig?

When I try using char * or uint8_t * and then a size parameter it gives me an error like this:

```<code>TypeError: in method 'processData', argument 3 of type 'char *'
</code>```

I've tried using %pybuffer_mutable_binary and %pybuffer_binary but they don't seem to change the definition of the wrapper and I still get the same error.

答:
I think the best way to do this is a type map using the Python buffer interface. This passes a pointer to your data to the C/C++ function without any copying of data. For example:</p>
```<code>%typemap(in, numinputs=1) (const char *data, unsigned long int size) {
  Py_buffer view;
  if (PyObject_CheckBuffer($input) != 1) {
    PyErr_SetString(
      PyExc_TypeError,
      "in method '$symname', argument $argnum does not support the buffer interface");
    SWIG_fail;
  }
  if (PyObject_GetBuffer($input, &view, PyBUF_SIMPLE) != 0) {
    PyErr_SetString(
      PyExc_TypeError,
      "in method '$symname', argument $argnum does not export a simple buffer");
    SWIG_fail;
  }
  $1 = view.buf;
  $2 = view.len;
  PyBuffer_Release(&view);
}
%typemap(doc) const char *data, unsigned long int size "$1_name: readable buffer (e.g. bytes)"
</code>```

Body:
How do you pass a bytes value from Python (like data loaded from a file with open('my file.dat', 'rb').read()) to a C/C++ function using swig?

When I try using char * or uint8_t * and then a size parameter it gives me an error like this:

TypeError: in method 'processData', argument 3 of type 'char *'

I've tried using %pybuffer_mutable_binary and %pybuffer_binary but they don't seem to change the definition of the wrapper and I still get the same error.

Body:
I think the best way to do this is a type map using the Python buffer interface. This passes a pointer to your data to the C/C++ function without any copying of data. For example:

%typemap(in, numinputs=1) (const char *data, unsigned long int size) {
  Py_buffer view;
  if (PyObject_CheckBuffer($input) != 1) {
    PyErr_SetString(
      PyExc_TypeError,
      "in method '$symname', argument $argnum does not support the buffer interface");
    SWIG_fail;
  }
  if (PyObject_GetBuffer($input, &view, PyBUF_SIMPLE) != 0) {
    PyErr_SetString(
      PyExc_TypeError,
      "in method '$symname', argument $argnum does not export a simple buffer");
    SWIG_fail;
  }
  $1 = view.buf;
  $2 = view.len;
  PyBuffer_Release(&view);
}
%typemap(doc) const char *data, unsigned long int size "$1_name: readable buffer (e.g. bytes)"


问:
Im trying to create an array of user Objects in local Storage using vanilla JS
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead</p>
```<code>//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);
</code>```

答:
Correct reference should solve it, the arguments passed to function(usersName, usersScore) will not be accessible outside the function, thats why your code doesn't work. You're passing parameter to the storeUsers function so that should be used whereever needed.

```<code>newUser = new userScoreTemplate(userObject.userName, userObject.score);
</code>```

Body:
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead

//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);

Body:
Correct reference should solve it, the arguments passed to function(usersName, usersScore) will not be accessible outside the function, thats why your code doesn't work. You're passing parameter to the storeUsers function so that should be used whereever needed.

newUser = new userScoreTemplate(userObject.userName, userObject.score);


问:
SequelizeValidationError "userId cannot be null"
I am working on a social network project. I am testing my requests on postman but I have a problem with my createPost request when I test it on postman I get an error.

My postman request :

```<code>{
    "title": "Un titre",
    "content": "un contenu",
    "picture": "une image",
    "usersId": 1
}
</code>```

Error on postman :

```<code>{
    "error": {
        "name": "SequelizeValidationError",
        "errors": [
            {
                "message": "Post.UserId cannot be null",
                "type": "notNull Violation",
                "path": "UserId",
                "value": null,
                "origin": "CORE",
                "instance": {
                    "id": null,
                    "title": "Un titre",
                    "content": "un contenu",
                    "picture": "une image",
                    "updatedAt": "2022-02-08T14:28:08.444Z",
                    "createdAt": "2022-02-08T14:28:08.444Z"
                },
                "validatorKey": "is_null",
                "validatorName": null,
                "validatorArgs": []
            }
        ]
    }
}
</code>```

Here is my code:

models:

```<code>'use strict';
module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    picture: DataTypes.STRING,
    usersId: DataTypes.INTEGER
  }, {});
  Post.associate = function(models) {
    models.Post.belongsTo(models.User, {
      foreignKey: { //application clé étrangère posée sur la table
        allowNull: false
      }
    });
  };
  return Post;
};
</code>```

controllers :

```<code>const models = require('../models');

exports.createPost = (req, res, next) => {
    let title = req.body.title;
    let content = req.body.content;
    let picture = req.body.picture;
    let usersId = req.body.usersId;

    models.Post.create({ title: title, content: content, picture: picture, usersId: usersId})
    .then((response) =>{
        res.status(201).json(JSON.stringify(response));
    })
    .catch((error) =>{
        console.error(error);
        res.status(400).json({ error })
    })
    .catch(error => res.status(500).json(error))
};
</code>```

thank you very much for your help (I'm still a beginner, there will surely be some mistakes).

答:
If you have an explicit foreign key field described in the model then you need to indicate it in the association:

models.Post.belongsTo(models.User, {
      foreignKey: { //application clé étrangère posée sur la table
        allowNull: false,
        name: 'usersId'
      }
    })
```

Body:
I am working on a social network project. I am testing my requests on postman but I have a problem with my createPost request when I test it on postman I get an error.

My postman request :

{
    "title": "Un titre",
    "content": "un contenu",
    "picture": "une image",
    "usersId": 1
}

Error on postman :

{
    "error": {
        "name": "SequelizeValidationError",
        "errors": [
            {
                "message": "Post.UserId cannot be null",
                "type": "notNull Violation",
                "path": "UserId",
                "value": null,
                "origin": "CORE",
                "instance": {
                    "id": null,
                    "title": "Un titre",
                    "content": "un contenu",
                    "picture": "une image",
                    "updatedAt": "2022-02-08T14:28:08.444Z",
                    "createdAt": "2022-02-08T14:28:08.444Z"
                },
                "validatorKey": "is_null",
                "validatorName": null,
                "validatorArgs": []
            }
        ]
    }
}

Here is my code:

models:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    picture: DataTypes.STRING,
    usersId: DataTypes.INTEGER
  }, {});
  Post.associate = function(models) {
    models.Post.belongsTo(models.User, {
      foreignKey: { //application clé étrangère posée sur la table
        allowNull: false
      }
    });
  };
  return Post;
};

controllers :

const models = require('../models');

exports.createPost = (req, res, next) => {
    let title = req.body.title;
    let content = req.body.content;
    let picture = req.body.picture;
    let usersId = req.body.usersId;

    models.Post.create({ title: title, content: content, picture: picture, usersId: usersId})
    .then((response) =>{
        res.status(201).json(JSON.stringify(response));
    })
    .catch((error) =>{
        console.error(error);
        res.status(400).json({ error })
    })
    .catch(error => res.status(500).json(error))
};

thank you very much for your help (I'm still a beginner, there will surely be some mistakes).


问:
Hex sum algorithm
Could you please advise if there is any effective way to calculate sum of two numbers in hex without conversion them to base10? I know how to calculate sum manually (actually the same as in the base10), but maybe there is more effective way? I am going to implement the algorithm in ABAP which is able to calculate sum of hex maximum 4 bytes length.</p>

答:
Summing two number base 16 represented with the digits 0123456789ABCDEF is no different than summing the usual base-10 representation, except of course the summing table is different.  As usual, you need to carry as may be necessary.  The summing table is a symmetric matrix, for which this is the upper representation (no ABAP here, sorry!  I hope you can read Kotlin)

```<code>private const val CARRY = '1'
private val ST = arrayOf( // summation table base 16
                    /*       0              1             2             3              4              5              6              7              8                9              A               B               C               D               E                F      */
    /*  0 */ arrayOf(Pair(null,'0'),Pair(null,'1'),Pair(null,'2'),Pair(null,'3'),Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),  Pair(null,'9'),Pair(null,'A'), Pair(null,'B'), Pair(null,'C'), Pair(null,'D'), Pair(null,'E'),  Pair(null,'F')),
    /*  1 */ arrayOf(               Pair(null,'2'),Pair(null,'3'),Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null, '9'), Pair(null,'A'),Pair(null,'B'), Pair(null,'C'), Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0')),
    /*  2 */ arrayOf(                              Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null,'9'),Pair(null, 'A'), Pair(null,'B'),Pair(null,'C'), Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1')),
    /*  3 */ arrayOf(                                             Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null,'9'),Pair(null,'A'),Pair(null, 'B'), Pair(null,'C'),Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2')),
    /*  4 */ arrayOf(                                                            Pair(null,'8'),Pair(null,'9'),Pair(null,'A'),Pair(null,'B'),Pair(null, 'C'), Pair(null,'D'),Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3')),
    /*  5 */ arrayOf(                                                                           Pair(null,'A'),Pair(null,'B'),Pair(null,'C'),Pair(null, 'D'), Pair(null,'E'),Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4')),
    /*  6 */ arrayOf(                                                                                Pair(null,'C'),Pair(null,'D'),Pair(null, 'E'), Pair(null,'F'),Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5')),
    /*  7 */ arrayOf(                                                                                Pair(null,'E'),Pair(null, 'F'),Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6')),
    /*  8 */ arrayOf(                                                                                Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7')),
    /*  9 */ arrayOf(                                                                                Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8')),
    /*  A */ arrayOf(                                                                                Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8'),Pair(CARRY,'9')),
    /*  B */ arrayOf(                                                                                Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8'),Pair(CARRY,'9'),Pair(CARRY,'A')),
    /*  C */ arrayOf(                                                                                Pair(CARRY,'8'),Pair(CARRY,'9'),Pair(CARRY,'A'),Pair(CARRY,'B')),
    /*  D */ arrayOf(                                                                                Pair(CARRY,'A'),Pair(CARRY,'B'),Pair(CARRY,'C')),
    /*  E */ arrayOf(                                                                                Pair(CARRY,'C'),Pair(CARRY,'D')),
    /*  F */ arrayOf(                                                                                Pair(CARRY,'E')),
)
</code>```

Sum is commutative; the sum of, say, 'A' and '7' is at the intersection of the same row/col above, in this case Pair(CARRY,'1') namely '1' and there is a carry.  This is the core of a possible implementation in Kotlin:

```<code>fun hexCharSum(a: Char, b: Char): Pair<Char?, Char> {
    check(a in hexSymbolSet && b in hexSymbolSet) { "$a, $b should be in $hexSymbolSet" }
    val i = a.hex2dec()
    val j = b.hex2dec()
    return when {
        i < j -> ST[i][j-i]
        j < i -> ST[j][i-j]
        else -> ST[i][0]
    }
}
</code>```

To sum two multiple digit numbers, the algorithm is intuitively immediate and is O(n) in the number of digits: just sum each digit from the least significant to the most significant, remembering the carry.  Implementation is, as usual, fraught with the additional complication of the details.
This is the core of a possible implementation in Kotlin:

```<code>fun hexStringSum(a: String, b: String): String {

    check(regex09AF.matches(a) && regex09AF.matches(b)) { "$a, $b must be unsigned hexadecimal numbers" }
    val al = a.length
    val bl = b.length

    fun zipAssemble(zipLength: Int, ar: String, br: String, sb: StringBuilder): Pair<Char?, StringBuilder> {

        var lastCarry: Char? = null
        for (ix in (0 until zipLength)) {
            val aux = hexCharSum(ar[ix], br[ix])
            val res = if (0 == ix) aux else lastCarry?.let { lastCy ->
                aux.first?.let {
                    /* keep track of aux's known carry */ Pair(aux.first, hexCharSum(aux.second, lastCy).second)
                } ?: hexCharSum(aux.second, lastCy)
            } ?: aux
            lastCarry = res.first
            sb.append(res.second)
        }
        return Pair(lastCarry, sb)
    }

    fun complete(startIx: Int, endIx: Int, srcr: String, sb: StringBuilder, lastCarry: Char?): StringBuilder {
        var thisCarry: Char? = lastCarry
        for (ix in (startIx until endIx)) {
            val res = thisCarry?.let {
                hexCharSum(srcr[ix], it)
            } ?: Pair(null, srcr[ix])
            thisCarry = res.first
            sb.append(res.second)
        }
        return thisCarry?.let { sb.append(CARRY) } ?: sb
    }

    return when {
        0 == al -> b
        0 == bl -> a
        else -> {
            val ar = a.reversed()
            val br = b.reversed()
            val sb = StringBuilder()
            when {
                al < bl -> {
                    val (lastCarry, sbAlias) = zipAssemble(al, ar, br, sb)
                    complete(al, bl, br.uppercase(), sbAlias, lastCarry).reverse().toString()
                }
                bl < al -> {
                    val (lastCarry, sbAlias) = zipAssemble(bl, ar, br, sb)
                    complete(bl, al, ar.uppercase(), sbAlias, lastCarry).reverse().toString()
                }
                else -> {
                    val (lastCarry, sbAlias) = zipAssemble(al, ar, br, sb)
                    lastCarry?.let { sbAlias.append(CARRY) }
                    sbAlias.reverse().toString()
                }
            }
        }
    }
}
</code>```

Title: Hex sum algorithm

Body:
Summing two number base 16 represented with the digits 0123456789ABCDEF is no different than summing the usual base-10 representation, except of course the summing table is different.  As usual, you need to carry as may be necessary.  The summing table is a symmetric matrix, for which this is the upper representation (no ABAP here, sorry!  I hope you can read Kotlin)

private const val CARRY = '1'
private val ST = arrayOf( // summation table base 16
                    /*       0              1             2             3              4              5              6              7              8                9              A               B               C               D               E                F      */
    /*  0 */ arrayOf(Pair(null,'0'),Pair(null,'1'),Pair(null,'2'),Pair(null,'3'),Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),  Pair(null,'9'),Pair(null,'A'), Pair(null,'B'), Pair(null,'C'), Pair(null,'D'), Pair(null,'E'),  Pair(null,'F')),
    /*  1 */ arrayOf(               Pair(null,'2'),Pair(null,'3'),Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null, '9'), Pair(null,'A'),Pair(null,'B'), Pair(null,'C'), Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0')),
    /*  2 */ arrayOf(                              Pair(null,'4'),Pair(null,'5'),Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null,'9'),Pair(null, 'A'), Pair(null,'B'),Pair(null,'C'), Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1')),
    /*  3 */ arrayOf(                                             Pair(null,'6'),Pair(null,'7'),Pair(null,'8'),Pair(null,'9'),Pair(null,'A'),Pair(null, 'B'), Pair(null,'C'),Pair(null,'D'), Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2')),
    /*  4 */ arrayOf(                                                            Pair(null,'8'),Pair(null,'9'),Pair(null,'A'),Pair(null,'B'),Pair(null, 'C'), Pair(null,'D'),Pair(null,'E'), Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3')),
    /*  5 */ arrayOf(                                                                           Pair(null,'A'),Pair(null,'B'),Pair(null,'C'),Pair(null, 'D'), Pair(null,'E'),Pair(null,'F'), Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4')),
    /*  6 */ arrayOf(                                                                                Pair(null,'C'),Pair(null,'D'),Pair(null, 'E'), Pair(null,'F'),Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5')),
    /*  7 */ arrayOf(                                                                                Pair(null,'E'),Pair(null, 'F'),Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6')),
    /*  8 */ arrayOf(                                                                                Pair(CARRY,'0'),Pair(CARRY,'1'),Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7')),
    /*  9 */ arrayOf(                                                                                Pair(CARRY,'2'),Pair(CARRY,'3'),Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8')),
    /*  A */ arrayOf(                                                                                Pair(CARRY,'4'),Pair(CARRY,'5'),Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8'),Pair(CARRY,'9')),
    /*  B */ arrayOf(                                                                                Pair(CARRY,'6'),Pair(CARRY,'7'),Pair(CARRY,'8'),Pair(CARRY,'9'),Pair(CARRY,'A')),
    /*  C */ arrayOf(                                                                                Pair(CARRY,'8'),Pair(CARRY,'9'),Pair(CARRY,'A'),Pair(CARRY,'B')),
    /*  D */ arrayOf(                                                                                Pair(CARRY,'A'),Pair(CARRY,'B'),Pair(CARRY,'C')),
    /*  E */ arrayOf(                                                                                Pair(CARRY,'C'),Pair(CARRY,'D')),
    /*  F */ arrayOf(                                                                                Pair(CARRY,'E')),
)

Sum is commutative; the sum of, say, 'A' and '7' is at the intersection of the same row/col above, in this case Pair(CARRY,'1') namely '1' and there is a carry.  This is the core of a possible implementation in Kotlin:

fun hexCharSum(a: Char, b: Char): Pair<Char?, Char> {
    check(a in hexSymbolSet && b in hexSymbolSet) { "$a, $b should be in $hexSymbolSet" }
    val i = a.hex2dec()
    val j = b.hex2dec()
    return when {
        i < j -> ST[i][j-i]
        j < i -> ST[j][i-j]
        else -> ST[i][0]
    }
}

To sum two multiple digit numbers, the algorithm is intuitively immediate and is O(n) in the number of digits: just sum each digit from the least significant to the most significant, remembering the carry.  Implementation is, as usual, fraught with the additional complication of the details.
This is the core of a possible implementation in Kotlin:

fun hexStringSum(a: String, b: String): String {

    check(regex09AF.matches(a) && regex09AF.matches(b)) { "$a, $b must be unsigned hexadecimal numbers" }
    val al = a.length
    val bl = b.length

    fun zipAssemble(zipLength: Int, ar: String, br: String, sb: StringBuilder): Pair<Char?, StringBuilder> {

        var lastCarry: Char? = null
        for (ix in (0 until zipLength)) {
            val aux = hexCharSum(ar[ix], br[ix])
            val res = if (0 == ix) aux else lastCarry?.let { lastCy ->
                aux.first?.let {
                    /* keep track of aux's known carry */ Pair(aux.first, hexCharSum(aux.second, lastCy).second)
                } ?: hexCharSum(aux.second, lastCy)
            } ?: aux
            lastCarry = res.first
            sb.append(res.second)
        }
        return Pair(lastCarry, sb)
    }

    fun complete(startIx: Int, endIx: Int, srcr: String, sb: StringBuilder, lastCarry: Char?): StringBuilder {
        var thisCarry: Char? = lastCarry
        for (ix in (startIx until endIx)) {
            val res = thisCarry?.let {
                hexCharSum(srcr[ix], it)
            } ?: Pair(null, srcr[ix])
            thisCarry = res.first
            sb.append(res.second)
        }
        return thisCarry?.let { sb.append(CARRY) } ?: sb
    }

    return when {
        0 == al -> b
        0 == bl -> a
        else -> {
            val ar = a.reversed()
            val br = b.reversed()
            val sb = StringBuilder()
            when {
                al < bl -> {
                    val (lastCarry, sbAlias) = zipAssemble(al, ar, br, sb)
                    complete(al, bl, br.uppercase(), sbAlias, lastCarry).reverse().toString()
                }
                bl < al -> {
                    val (lastCarry, sbAlias) = zipAssemble(bl, ar, br, sb)
                    complete(bl, al, ar.uppercase(), sbAlias, lastCarry).reverse().toString()
                }
                else -> {
                    val (lastCarry, sbAlias) = zipAssemble(al, ar, br, sb)
                    lastCarry?.let { sbAlias.append(CARRY) }
                    sbAlias.reverse().toString()
                }
            }
        }
    }
}


问:
cypress reporter with multiple spec files
I have multiple spec files for running tests related to each other and to run them easier separately. When I run my cypress test with a junit reporter only test suites of the last spec files are present. We use the junit reporter for jenkins.

Is these some config I need to add to make sure all test suites are present in the junit report file?

答: I was hunting for an answer to this question and just learned that if you use Mochawesome as your test reporter, you can use Mochawesome Merge to combine the output of multiple specs and then use Mochawesome Report Generator to create a single HTML report from your specs.</p>


问:
Form.Close() doesn't close window immediately
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

```<code>public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }
</code>```

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

答: If the main form is created in the standard way in WinForms via Application.Run(new MainForm()); then when it closes, the application will exit, closing all other forms.  So I don't think you need to worry about manually closing all child forms.

Body:
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?


问:
How to add default in every case in c++
how do i add default in every case?
it does not allow me to do it like this and will error in the second default,

```<code>switch (select)
{

    case 1:
        here1:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here1;

        break;

    case 2:
        here2:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here2;

        break;

</code>```

i need default inside every case, how am i gonna do that?

答: well you really cant do this because "default" considered as a case itself so you cant make two cases in one.  but instead if you want so mimic it you can use an "if statement " with the condition you want.</p>

Title: How to add default in every case in c++

Body:
how do i add default in every case?
it does not allow me to do it like this and will error in the second default,

switch (select)
{

    case 1:
        here1:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here1;

        break;

    case 2:
        here2:
        cout<<"statement"<<endl;

    default:
        cout<<"statement"<<endl;
        goto here2;

        break;

i need default inside every case, how am i gonna do that?


问:
This form is not secure Autofill has been turned off only in chrome
I get this error when trying to fill the form from chrome in my website.

And this after I submit the form.

This doesn't happen in any other browser, what do I've to do to make the form secure.

答:
My website is https, but I got the same problem.
And I saw

in the form tag I wrote:

```<code><form action="http://mywebsite.com/sendMail.php">
</code>```

my endPoint I wrote:

```<code>    post = {
        endPoint: 'http://mywebsite.com/sendMail.php',
    }
</code>```

No. They should all be https.
I've changed them and now everything works fine.

Body:
My website is https, but I got the same problem.
And I saw

in the form tag I wrote:

<form action="http://mywebsite.com/sendMail.php">

my endPoint I wrote:

    post = {
        endPoint: 'http://mywebsite.com/sendMail.php',
    }

No. They should all be https.
I've changed them and now everything works fine.


问:
Using Cow in a generic struct
The following code:

use std::borrow::Cow;

struct Hip<'a> {
    hip: Cow<'a, [u8]>
}

struct Hop<'a, T: ?Sized + 'a> {
    hop: Cow<'a, T>
}

fn main() {
    let it_be: Hop<[u8]> = [1, 2, 3];
}
```
<p>Fails to build because "the trait <code>Clone</code> is not implemented for <code>T</code>".</p>
<p>Whereas expecting <code>T</code> to implement <code>Clone</code> (as follows):</p>
<pre class="lang-rust prettyprint-override"><code>struct Hop<'a, T: Clone + ?Sized + 'a> {
    hop: Cow<'a, T>
}
</code>```

Fails to build because "the trait Clone is not implemented for [u8]".

How come Hip, which is using a [u8], compiles, but not Hop?

Why does the compiler request Clone to be implemented for Hop's T, but not for Hip's [u8]?

On the Rust Playground

答:
The documentation says the type should implement ToOwned.
The following works:

struct Hop<'a, T: ?Sized + ToOwned> {
    hop: Cow<'a, T>
}

fn main() {
    let it_be: Hop<[u8]> = Hop { hop: Cow::Owned(vec![1, 2, 3]) };
}
```

About the error message: the compiler generates the implementation of ToOwned for every type implementing Clone. So when the trait ToOwned is missing, it suggests to implement Clone.

This is a mistake because some types have good reasons to implement ToOwnedwithout implementing Clone. [u8] is one of them, hence Hip compiles. Whereas Hop's T was not bound to ToOwned, so it fails.

Title: Using Cow in a generic struct

Body:
The following code:

use std::borrow::Cow;

struct Hip<'a> {
    hip: Cow<'a, [u8]>
}

struct Hop<'a, T: ?Sized + 'a> {
    hop: Cow<'a, T>
}

fn main() {
    let it_be: Hop<[u8]> = [1, 2, 3];
}

Fails to build because "the trait Clone is not implemented for T".

Whereas expecting T to implement Clone (as follows):

struct Hop<'a, T: Clone + ?Sized + 'a> {
    hop: Cow<'a, T>
}

Fails to build because "the trait Clone is not implemented for [u8]".

How come Hip, which is using a [u8], compiles, but not Hop?

Why does the compiler request Clone to be implemented for Hop's T, but not for Hip's [u8]?

On the Rust Playground

Body:
The documentation says the type should implement ToOwned.
The following works:

struct Hop<'a, T: ?Sized + ToOwned> {
    hop: Cow<'a, T>
}

fn main() {
    let it_be: Hop<[u8]> = Hop { hop: Cow::Owned(vec![1, 2, 3]) };
}

About the error message: the compiler generates the implementation of ToOwned for every type implementing Clone. So when the trait ToOwned is missing, it suggests to implement Clone.

This is a mistake because some types have good reasons to implement ToOwnedwithout implementing Clone. [u8] is one of them, hence Hip compiles. Whereas Hop's T was not bound to ToOwned, so it fails.


问:
How to add custom pylint warning?
I want to add a warning message to my pylint for all print statements reminding myself I have them in case I print sensitive information. Is this possible? I can only find answers about disabling pylint errors, not enabling new ones.</p>

答:
You can add print to the bad builtin in your pylintrc:

[DEPRECATED_BUILTINS]

# List of builtins function names that should not be used, separated by a comma
bad-functions=print

load-plugins=
    pylint.extensions.bad_builtin,
```
<p>Creating a custom checker like Code-Apprentice suggested should also be relatively easy, something like that:</p>
<pre class="lang-py prettyprint-override"><code>
from typing import TYPE_CHECKING

from astroid import nodes

from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
from pylint.interfaces import IAstroidChecker

if TYPE_CHECKING:
    from pylint.lint import PyLinter

class PrintUsedChecker(BaseChecker):

    name = "no_print_allowed"
    msgs = {
        "W5001": (
            "Used builtin function %s",
            "print-used",
            "a warning message reminding myself I have them in case I "
            "print sensitive information",
        )
    }

    @check_messages("print-used")
    def visit_call(self, node: nodes.Call) -> None:
        if isinstance(node.func, nodes.Name):
            if node.func.name == "print":
                self.add_message("print-used", node=node)

def register(linter: "PyLinter") -> None:
    linter.register_checker(PrintUsedChecker(linter))
</code>```

Then you add it in load-plugin in the pylintrc:

load-plugins=
    your.code.namespace.print_used,
```

Title: How to add custom pylint warning?

Body:
You can add print to the bad builtin in your pylintrc:

[DEPRECATED_BUILTINS]

# List of builtins function names that should not be used, separated by a comma
bad-functions=print

load-plugins=
    pylint.extensions.bad_builtin,

Creating a custom checker like Code-Apprentice suggested should also be relatively easy, something like that:

from typing import TYPE_CHECKING

from astroid import nodes

from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
from pylint.interfaces import IAstroidChecker

if TYPE_CHECKING:
    from pylint.lint import PyLinter

class PrintUsedChecker(BaseChecker):

    name = "no_print_allowed"
    msgs = {
        "W5001": (
            "Used builtin function %s",
            "print-used",
            "a warning message reminding myself I have them in case I "
            "print sensitive information",
        )
    }

    @check_messages("print-used")
    def visit_call(self, node: nodes.Call) -> None:
        if isinstance(node.func, nodes.Name):
            if node.func.name == "print":
                self.add_message("print-used", node=node)

def register(linter: "PyLinter") -> None:
    linter.register_checker(PrintUsedChecker(linter))

Then you add it in load-plugin in the pylintrc:

load-plugins=
    your.code.namespace.print_used,