问:
'An attempt has been made to start' in lr_find with fast.ai
I am running this small piece of code to identify learning rate:

```<code>import cv2
from fastai.vision import *
from fastai.callbacks.hooks import *
path = untar_data(URLs.CAMVID)
path_lbl = path/'labels'
path_img = path/'images'
fnames = get_image_files(path_img)
lbl_names = get_image_files(path_lbl)
img_f = fnames[0]
img = open_image(img_f)
get_y_fn = lambda x: path_lbl/f'{x.stem}_P{x.suffix}'
mask = open_mask(get_y_fn(img_f))
src_size = np.array(mask.shape[1:])
src_size,mask.data
codes = np.loadtxt(path/'codes.txt', dtype=str); codes
size = src_size//2
bs=4
src = (SegmentationItemList.from_folder(path_img)
       .split_by_fname_file('../valid.txt')
       .label_from_func(get_y_fn, classes=codes))
data = (src.transform(get_transforms(), size=size, tfm_y=True)
        .databunch(bs=bs)
        .normalize(imagenet_stats))
name2id = {v:k for k,v in enumerate(codes)}
void_code = name2id['Void']
def acc_camvid(input, target):
    target = target.squeeze(1)
    mask = target != void_code
    return (input.argmax(dim=1)[mask]==target[mask]).float().mean()
wd=1e-2
learn = unet_learner(data, models.resnet34, metrics=acc_camvid, wd=wd)
lr_find(learn)
print("end")
</code>```

And I get this error:

```<code>RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
</code>```

and also this one:

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1664, in <module>
    main()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1658, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1068, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/steve/Project/fastai_unet/main.py", line 32, in <module>
    lr_find(learn)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\train.py", line 32, in lr_find
    learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 199, in fit
    fit(epochs, self, metrics=self.metrics, callbacks=self.callbacks+callbacks)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 99, in fit
    for xb,yb in progress_bar(learn.data.train_dl, parent=pbar):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastprogress\fastprogress.py", line 72, in __iter__
    for i,o in enumerate(self._gen):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_data.py", line 75, in __iter__
    for b in self.dl: yield self.proc_batch(b)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 193, in __iter__
    return _DataLoaderIter(self)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 469, in __init__
    w.start()
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
</code>```

how can I fix this?

答: In my case, running under Windows, I had to set the number of num_workers to 0 in the dataloaders. Here, I presume this could be set within databunch(bs=bs).</p>

Body:
I am running this small piece of code to identify learning rate:

import cv2
from fastai.vision import *
from fastai.callbacks.hooks import *
path = untar_data(URLs.CAMVID)
path_lbl = path/'labels'
path_img = path/'images'
fnames = get_image_files(path_img)
lbl_names = get_image_files(path_lbl)
img_f = fnames[0]
img = open_image(img_f)
get_y_fn = lambda x: path_lbl/f'{x.stem}_P{x.suffix}'
mask = open_mask(get_y_fn(img_f))
src_size = np.array(mask.shape[1:])
src_size,mask.data
codes = np.loadtxt(path/'codes.txt', dtype=str); codes
size = src_size//2
bs=4
src = (SegmentationItemList.from_folder(path_img)
       .split_by_fname_file('../valid.txt')
       .label_from_func(get_y_fn, classes=codes))
data = (src.transform(get_transforms(), size=size, tfm_y=True)
        .databunch(bs=bs)
        .normalize(imagenet_stats))
name2id = {v:k for k,v in enumerate(codes)}
void_code = name2id['Void']
def acc_camvid(input, target):
    target = target.squeeze(1)
    mask = target != void_code
    return (input.argmax(dim=1)[mask]==target[mask]).float().mean()
wd=1e-2
learn = unet_learner(data, models.resnet34, metrics=acc_camvid, wd=wd)
lr_find(learn)
print("end")

And I get this error:

RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

and also this one:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1664, in <module>
    main()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1658, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1068, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/steve/Project/fastai_unet/main.py", line 32, in <module>
    lr_find(learn)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\train.py", line 32, in lr_find
    learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 199, in fit
    fit(epochs, self, metrics=self.metrics, callbacks=self.callbacks+callbacks)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 99, in fit
    for xb,yb in progress_bar(learn.data.train_dl, parent=pbar):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastprogress\fastprogress.py", line 72, in __iter__
    for i,o in enumerate(self._gen):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_data.py", line 75, in __iter__
    for b in self.dl: yield self.proc_batch(b)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 193, in __iter__
    return _DataLoaderIter(self)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 469, in __init__
    w.start()
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

how can I fix this?


来源: stackexchange

问:
Error "The remote server returned an error: (501) Not Implemented." Reloading geoserver with C#.
I´m trying to reload a geoserver directory and I´m getting the following error:

The remote server returned an error: (501) Not Implemented.

This is the code

```<code>WebRequest serverRequest  =WebRequest.Create("http://xxxx:8080/geoserver/rest/workspaces");
serverRequest.Method = "RELOAD";

            serverRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(password));

            WebResponse serverResponse;
            serverResponse = serverRequest.GetResponse();
            serverResponse.Close();
</code>```

答:
serverRequest.Method is not related to a REST Webservice(?) method you want to invoke.

WebRequest.Method is either GET or POST (or any of those defined for geoserver) unless there is a HttpModule which implements a protocol method RELOAD.

According to the geoserver REST Configuration API Reference "Configuration Reloading" your call should look something like this:

```<code>WebRequest serverRequest = WebRequest.Create("http://xxxx:8080/geoserver/rest/reload");
serverRequest.Method = "POST";
// get response ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I´m trying to reload a geoserver directory and I´m getting the following error:

The remote server returned an error: (501) Not Implemented.

This is the code

WebRequest serverRequest  =WebRequest.Create("http://xxxx:8080/geoserver/rest/workspaces");
serverRequest.Method = "RELOAD";

            serverRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(password));

            WebResponse serverResponse;
            serverResponse = serverRequest.GetResponse();
            serverResponse.Close();

Body:
serverRequest.Method is not related to a REST Webservice(?) method you want to invoke.

WebRequest.Method is either GET or POST (or any of those defined for geoserver) unless there is a HttpModule which implements a protocol method RELOAD.

According to the geoserver REST Configuration API Reference "Configuration Reloading" your call should look something like this:

WebRequest serverRequest = WebRequest.Create("http://xxxx:8080/geoserver/rest/reload");
serverRequest.Method = "POST";
// get response ...


问:
Install vuex without npm or yarn?
Hey I want to install vuex in my Vue3 project. Because of several reasons I have no possibility to install it with npm or yarn. I already googled for solutions but it seems like there aren't any. Had someone of you maybe the same problem or an idea how to fix this?</p>

答:
You should be able to use with by loading it from a "CDN" as below

```<code>https://unpkg.com/vuex@4
</code>```

Unpkg.com provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like https://unpkg.com/vuex@4.0.0/dist/vuex.global.js

For more info refer to installation section of Vuex docs

ContentLicense: CC BY-SA 4.0

Title: Install vuex without npm or yarn?

Body:
You should be able to use with by loading it from a "CDN" as below

https://unpkg.com/vuex@4

Unpkg.com provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like https://unpkg.com/vuex@4.0.0/dist/vuex.global.js

For more info refer to installation section of Vuex docs


问:
How to run code after showDialog is dismissed in Flutter?
How to update the Homepage just after the showDialog() is dismissed/disposed? Doesn't seem like it has an onDispose() function.

Found another possible Answer : The WillPopScope can help detect if the back button is pressed.

The widget that will be used in the showDialog, in its build function the widget can be wrapped in return new WillPopScope(child: ______, onWillPop: _______); The code can be run in the onWillPop function. This can update the Homepage below.

答:
For me, I used Bloc state management to handle this.
The idea is:

```<code>//On Dialog
clickOKAction: () => blocCubit.emitOKActionState()
...

//On the bloc file
fun emitOKActionState(){
   emit(OKActionState());
}

//On Widget
listener: (context, state) async {
   if(state is OKActionState) {
        // HANDLE YOUR ACTION HERE
   }
}
</code>```

Because after showing Dialog, the current widget will be disposed. So you can not use anything related to context for eg, because it's unmounted. This may help solve error like:

This widget has been unmounted, so the State no longer has a context (and should be considered defunct)

Body:
For me, I used Bloc state management to handle this.
The idea is:

//On Dialog
clickOKAction: () => blocCubit.emitOKActionState()
...

//On the bloc file
fun emitOKActionState(){
   emit(OKActionState());
}

//On Widget
listener: (context, state) async {
   if(state is OKActionState) {
        // HANDLE YOUR ACTION HERE
   }
}

Because after showing Dialog, the current widget will be disposed. So you can not use anything related to context for eg, because it's unmounted. This may help solve error like:

This widget has been unmounted, so the State no longer has a context (and should be considered defunct)


问:
pandas finding duplicate rows with different label
I have the case where I want to sanity check labeled data. I have hundreds of features and want to find points which have the same features but different label. These found cluster of disagreeing labels should then be numbered and put into a new dataframe.
This isn't hard but I am wondering what the most elegant solution for this is.
Here an example:</p>
```<code>import pandas as pd

df = pd.DataFrame({
    "feature_1" : [0,0,0,4,4,2],
    "feature_2" : [0,5,5,1,1,3],
    "label" : ["A","A","B","B","D","A"]
})

result_df = pd.DataFrame({
    "cluster_index" : [0,0,1,1],
    "feature_1" : [0,0,4,4],
    "feature_2" : [5,5,1,1],
    "label" : ["A","B","B","D"]
})
</code>```

答:
First get all duplicated values per feature columns and then if necessary remove duplciated by all columns (here in sample data not necessary), last add GroupBy.ngroup for groups indices:

```<code>df = df[df.duplicated(['feature_1','feature_2'],keep=False)].drop_duplicates()

df['cluster_index'] = df.groupby(['feature_1', 'feature_2'])['label'].ngroup()
print (df)
   feature_1  feature_2 label  cluster_index
1          0          5     A              0
2          0          5     B              0
3          4          1     B              1
4          4          1     D              1
</code>```

Body:
I have the case where I want to sanity check labeled data. I have hundreds of features and want to find points which have the same features but different label. These found cluster of disagreeing labels should then be numbered and put into a new dataframe.
This isn't hard but I am wondering what the most elegant solution for this is.
Here an example:

import pandas as pd

df = pd.DataFrame({
    "feature_1" : [0,0,0,4,4,2],
    "feature_2" : [0,5,5,1,1,3],
    "label" : ["A","A","B","B","D","A"]
})

result_df = pd.DataFrame({
    "cluster_index" : [0,0,1,1],
    "feature_1" : [0,0,4,4],
    "feature_2" : [5,5,1,1],
    "label" : ["A","B","B","D"]
})

Body:
First get all duplicated values per feature columns and then if necessary remove duplciated by all columns (here in sample data not necessary), last add GroupBy.ngroup for groups indices:

df = df[df.duplicated(['feature_1','feature_2'],keep=False)].drop_duplicates()

df['cluster_index'] = df.groupby(['feature_1', 'feature_2'])['label'].ngroup()
print (df)
   feature_1  feature_2 label  cluster_index
1          0          5     A              0
2          0          5     B              0
3          4          1     B              1
4          4          1     D              1


问:
Conditional fill a value in Data frame based on ranges
I want to make groups according to age ranges in a data frame.
I tried:

```<code>DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", NA)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", NA)
...
</code>```

but the next line replaces data assigned by the previous code.
I could manage the groupings into separate columns and then merge them but there must be a simple and straightforward way to do so. Can anyone help?

Body:
I want to make groups according to age ranges in a data frame.
I tried:

DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", NA)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", NA)
...

but the next line replaces data assigned by the previous code.
I could manage the groupings into separate columns and then merge them but there must be a simple and straightforward way to do so. Can anyone help?

Body:
DF <- data.frame(Age = sample(1:100, 25))

cuts <- c(0, 20, 30, 40, 50, 100)
groups <- c("G1", "G2", "G3", "G4", "G5")

DF$AgeGroup <- cut(DF$Age, breaks = cuts, labels = groups, right = FALSE)

DF

#    Age AgeGroup
# 1   87       G5
# 2   88       G5
# 3   61       G5
# 4    8       G1
# 5   29       G2
# 6   25       G2
# 7   55       G5
# 8   44       G4
# 9   76       G5
# 10  86       G5
# 11  30       G3
# 12  99       G5
# 13  95       G5
# 14  62       G5
# 15  70       G5
# 16  82       G5
# 17  97       G5
# 18  50       G5
# 19  84       G5
# 20  35       G3
# 21  60       G5
# 22  20       G2
# 23   2       G1
# 24  19       G1
# 25  33       G3


问:
Avatar background color not changing dynamically in material-ui v5
I'm trying to change each avatar background color on the basis of categories, for example if the category is "work" then the avatar color must be yellow if the category is "todos" then the avatar color must be pink and so on. But the code is displaying the default grey background-color of each avatar. I'm unable to change the background-color.

```<code>import React from "react";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardContent from "@mui/material/CardContent";
import { IconButton, Typography } from "@mui/material";
import { DeleteOutlined } from "@mui/icons-material";
import { makeStyles } from "@mui/styles";
import { blue, green, pink, yellow } from "@mui/material/colors";
import Avatar from "@mui/material/Avatar";

const useStyles = makeStyles({
  avatar: {
    backgroundColor: (note) => {
      if (note.category == "work") {
        return yellow[700];
      }
      if (note.category == "money") {
        return green[500];
      }
      if (note.category == "todos") {
        return pink[500];
      }
      return blue[500];
    },
  },
});

const NoteCard = ({ note, handleDelete }) => {
  const classes = useStyles(note);

  return (
    <div>
      <Card elevation={1}>
        <CardHeader
          avatar={
            <Avatar className={classes.avatar}>
              {note.category[0].toUpperCase()}
            </Avatar>
          }
          action={
            <IconButton onClick={() => handleDelete(note.id)}>
              <DeleteOutlined />
            </IconButton>
          }
          title={note.title}
          subheader={note.category}
        />
        <CardContent>
          <Typography variant="body2" color="textSecondary">
            {note.details}
          </Typography>
        </CardContent>
      </Card>
    </div>
  );
};

export default NoteCard;
</code>```

video reference

答:
The sx prop is a shortcut for defining custom style.

1.Create a function:

```<code> const avatarBgColor = (note) => {
      if (note.category === "work") {
        return yellow[700];
      }
      if (note.category === "money") {
        return green[700];
      }
      if (note.category === "todos") {
        return pink[500];
      } else {
        return blue[500];
      }
    };
</code>```

2.Use the function inside the sx prop

```<code><Avatar sx={{ bgcolor: avatarBgColor(note) }}>
              {note.category[0].toUpperCase()}
</Avatar>
</code>```

Body:
I'm trying to change each avatar background color on the basis of categories, for example if the category is "work" then the avatar color must be yellow if the category is "todos" then the avatar color must be pink and so on. But the code is displaying the default grey background-color of each avatar. I'm unable to change the background-color.

import React from "react";
import Card from "@mui/material/Card";
import CardHeader from "@mui/material/CardHeader";
import CardContent from "@mui/material/CardContent";
import { IconButton, Typography } from "@mui/material";
import { DeleteOutlined } from "@mui/icons-material";
import { makeStyles } from "@mui/styles";
import { blue, green, pink, yellow } from "@mui/material/colors";
import Avatar from "@mui/material/Avatar";

const useStyles = makeStyles({
  avatar: {
    backgroundColor: (note) => {
      if (note.category == "work") {
        return yellow[700];
      }
      if (note.category == "money") {
        return green[500];
      }
      if (note.category == "todos") {
        return pink[500];
      }
      return blue[500];
    },
  },
});

const NoteCard = ({ note, handleDelete }) => {
  const classes = useStyles(note);

  return (

      <Card elevation={1}>
        <CardHeader
          avatar={
            <Avatar className={classes.avatar}>
              {note.category[0].toUpperCase()}
            </Avatar>
          }
          action={
            <IconButton onClick={() => handleDelete(note.id)}>
              <DeleteOutlined />
            </IconButton>
          }
          title={note.title}
          subheader={note.category}
        />
        <CardContent>
          <Typography variant="body2" color="textSecondary">
            {note.details}
          </Typography>
        </CardContent>
      </Card>

  );
};

export default NoteCard;

video reference

Body:
The sx prop is a shortcut for defining custom style.

1.Create a function:

 const avatarBgColor = (note) => {
      if (note.category === "work") {
        return yellow[700];
      }
      if (note.category === "money") {
        return green[700];
      }
      if (note.category === "todos") {
        return pink[500];
      } else {
        return blue[500];
      }
    };

2.Use the function inside the sx prop

<Avatar sx={{ bgcolor: avatarBgColor(note) }}>
              {note.category[0].toUpperCase()}
</Avatar>


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答:
You always neet to initialize your variables. To catch this sort of error, you should probably compile with -Wall to give you all warnings that g++ can provide. I also prefer to use -Werror to make all warnings errors, since it's almost always the case that a warning indicates an error or a potential error and that cleaning up the code is better than leaving it as is.

Also, in your second printf, you used %s which is for printing strings, not integers.

```<code>int i = 0;
printf("%d\n", i);
// or
printf("%i\n", i);
</code>```

Is what you want.

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

ContentLicense: CC BY-SA 2.5

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

Body:
You always neet to initialize your variables. To catch this sort of error, you should probably compile with -Wall to give you all warnings that g++ can provide. I also prefer to use -Werror to make all warnings errors, since it's almost always the case that a warning indicates an error or a potential error and that cleaning up the code is better than leaving it as is.

Also, in your second printf, you used %s which is for printing strings, not integers.

int i = 0;
printf("%d\n", i);
// or
printf("%i\n", i);

Is what you want.

OwnerDisplayName: Brian Campbell


问:
Type mismatch: cannot convert from element type Object to int
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

```<code>for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}
</code>```

答:
It must be: for (Integer key : ht.keySet())...

LinkedHashMap<K, V> where K and V are Objects, not primitiv (int, short ...)

Body:
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}


问:
Why is "Assembliess" missing in Reference Manager and only 3 target frameworks are shown?
I am using VS2019.
I have created a new VB.NET WinForms project.
It is set to use the .NET framework 5.0.

Now I wanted to add the following references:

System.Xaml, PresentationCore, PresentationFramework, WindowsBase,  WindowsFormsIntegration

However, "Assemblies" is not visible in the Reference Manager.

Also, in this project I can only chose between 3 frameworks, but I have many more installed:

As one can see, when I open up a project that I have created earlier, I can see and select all of my frameworks:

What is going on here?

Thank you!

答:
I got it:

There were 2 VB.NET WinForms app templates in the Create New Project window.

Microsoft devs did a great job naming them almost exactely the same.
Only when I selected

```<code>Windown Forms App (.NET Framework)
A project for creating an application with a Windows Forms (WinForms) user interface
</code>```

instead of

```<code>Windows Forms App
A project template for creatinng a .NET Windows Forms (WinForms) app
</code>```

... it would work.

Body:
I got it:

There were 2 VB.NET WinForms app templates in the Create New Project window.

Microsoft devs did a great job naming them almost exactely the same.
Only when I selected

Windown Forms App (.NET Framework)
A project for creating an application with a Windows Forms (WinForms) user interface

instead of

Windows Forms App
A project template for creatinng a .NET Windows Forms (WinForms) app

... it would work.


问:
Why the Asset Images are not displaying on the phone, but it works on web browser?
All the images works on the web browser

I have tried to load the images in the phone and emulator, but the asset images are not loading, and the network images are displaying.

Also, the asset images get displayed on the web browser.

like this Image not loading on phone or emulator

Here is my code:

HomeScreen

```<code>import 'package:flutter/material.dart';
import 'package:road_sign/models/category_model.dart';
import 'package:road_sign/models/news_model.dart';
import 'package:road_sign/models/quize_model.dart';
import 'package:road_sign/screen/category/category_screen.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('The Home Page'),
        //backgroundColor: Colors.black,
      ),
      backgroundColor: Colors.white,
      //!body
      body: Column(
        children: [
          Expanded(
            flex: 2,
            //! it's category List
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView.separated(
                itemCount: categoris.length,
                scrollDirection: Axis.horizontal,
                itemBuilder: (context, index) => GridTile(
                  child: InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CategoryScreen(
                            selectedCategory: categoris[index],
                          ),
                        ),
                      );
                    },
                    child: Container(
                      margin: EdgeInsets.all(5),
                      height: 100,
                      width: 200,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(categoris[index].categoryImg),
                            fit: BoxFit.contain,
                          ),
                          borderRadius: BorderRadius.circular(20),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black38,
                              blurRadius: 2,
                              spreadRadius: 3,
                              offset: Offset(
                                3.0, // Move to right 10  horizontally
                                2.0, // Move to bottom 10 Vertically
                              ),
                            )
                          ]),
                    ),
                  ),
                ),
                separatorBuilder: (BuildContext context, int index) {
                  return SizedBox(
                    width: 25,
                  );
                },
              ),
            ),
          ),

          //!Second Column Part

          Flexible(
            flex: 4,
            //! it's category Random Item list.
            child: ListView.separated(
              itemCount: news_list.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: 200,
                  decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: BorderRadius.circular(20)),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        Expanded(
                          child: Image(
                            image: NetworkImage(
                                'https://images.hindustantimes.com/img/2021/10/06/1600x900/08065ecc-26df-11ec-97ad-def1feb12b09_1633550216966.jpg'),
                            fit: BoxFit.cover,
                          ),
                        ),
                        Text(
                          "For 2016 specifically, National Highway Traffic Safety Administration (NHTSA) data shows 37,461 people were killed in 34,436 motor vehicle crashes, an average of 102 per day.",
                        ),
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 10,
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Category_Screen:

```<code>class CategoryModel {
  final String categoryName;
  final String categoryImg;

  CategoryModel({required this.categoryName, required this.categoryImg});
}

List<CategoryModel> categoris = [
  CategoryModel(
    categoryName: 'Traffic Lights',
    categoryImg: 'assets/images/all_lights.png',
  ),
  CategoryModel(
    categoryName: 'Types of Car',
    categoryImg: 'assets/images/car_types.png',
  ),
  CategoryModel(
    categoryName: 'Road Symbols',
    categoryImg: 'assets/images/traffic_stops.png',
  ),
  CategoryModel(
    categoryName: 'Traffic Signals',
    categoryImg: 'assets/images/tarffic signals.png',
  ),
  CategoryModel(
    categoryName: 'Notice',
    categoryImg: 'assets/images/road_blocked.jpg',
  ),
];
</code>```

答:
```<code>///Please post your code here I am not getting your question If you using an asset image then you have to specify the path of the assets in the pubsec.yml file like this

    flutter:

      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true
      assets:
        - assets/
        - assets/Vector-2.png

    ////Inside a code
    Container(
                                              height: 120,
                                              width: 120,
                                              decoration: BoxDecoration(
                                                color: Colors.white,
                                                shape: BoxShape.circle,
                                                image:DecorationImage(
                                                    fit: BoxFit.cover,
                                                    image: AssetImage('assets/managerPicture.jpeg')),
                                                border: Border.all(
                                                    color: AppColors.white, width: 2.0),
                                              ),
                                            ),
    ////If you want to show a network image

    Container(
                                              height: 120,
                                              width: 120,
                                              decoration: BoxDecoration(
                                                color: Colors.white,
                                                shape: BoxShape.circle,
                                                image:DecorationImage(
                                                    fit: BoxFit.cover,
                                                    image: NetWorkImage("")),
                                                border: Border.all(
                                                    color: AppColors.white, width: 2.0),
                                              ),
                                            ),

</code>```

Body:
All the images works on the web browser

I have tried to load the images in the phone and emulator, but the asset images are not loading, and the network images are displaying.

Also, the asset images get displayed on the web browser.

like this Image not loading on phone or emulator

Here is my code:

HomeScreen

import 'package:flutter/material.dart';
import 'package:road_sign/models/category_model.dart';
import 'package:road_sign/models/news_model.dart';
import 'package:road_sign/models/quize_model.dart';
import 'package:road_sign/screen/category/category_screen.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('The Home Page'),
        //backgroundColor: Colors.black,
      ),
      backgroundColor: Colors.white,
      //!body
      body: Column(
        children: [
          Expanded(
            flex: 2,
            //! it's category List
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView.separated(
                itemCount: categoris.length,
                scrollDirection: Axis.horizontal,
                itemBuilder: (context, index) => GridTile(
                  child: InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CategoryScreen(
                            selectedCategory: categoris[index],
                          ),
                        ),
                      );
                    },
                    child: Container(
                      margin: EdgeInsets.all(5),
                      height: 100,
                      width: 200,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(categoris[index].categoryImg),
                            fit: BoxFit.contain,
                          ),
                          borderRadius: BorderRadius.circular(20),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black38,
                              blurRadius: 2,
                              spreadRadius: 3,
                              offset: Offset(
                                3.0, // Move to right 10  horizontally
                                2.0, // Move to bottom 10 Vertically
                              ),
                            )
                          ]),
                    ),
                  ),
                ),
                separatorBuilder: (BuildContext context, int index) {
                  return SizedBox(
                    width: 25,
                  );
                },
              ),
            ),
          ),

          //!Second Column Part

          Flexible(
            flex: 4,
            //! it's category Random Item list.
            child: ListView.separated(
              itemCount: news_list.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: 200,
                  decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: BorderRadius.circular(20)),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        Expanded(
                          child: Image(
                            image: NetworkImage(
                                'https://images.hindustantimes.com/img/2021/10/06/1600x900/08065ecc-26df-11ec-97ad-def1feb12b09_1633550216966.jpg'),
                            fit: BoxFit.cover,
                          ),
                        ),
                        Text(
                          "For 2016 specifically, National Highway Traffic Safety Administration (NHTSA) data shows 37,461 people were killed in 34,436 motor vehicle crashes, an average of 102 per day.",
                        ),
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 10,
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Category_Screen:

class CategoryModel {
  final String categoryName;
  final String categoryImg;

  CategoryModel({required this.categoryName, required this.categoryImg});
}

List<CategoryModel> categoris = [
  CategoryModel(
    categoryName: 'Traffic Lights',
    categoryImg: 'assets/images/all_lights.png',
  ),
  CategoryModel(
    categoryName: 'Types of Car',
    categoryImg: 'assets/images/car_types.png',
  ),
  CategoryModel(
    categoryName: 'Road Symbols',
    categoryImg: 'assets/images/traffic_stops.png',
  ),
  CategoryModel(
    categoryName: 'Traffic Signals',
    categoryImg: 'assets/images/tarffic signals.png',
  ),
  CategoryModel(
    categoryName: 'Notice',
    categoryImg: 'assets/images/road_blocked.jpg',
  ),
];


问:
How to run Flutter commands on Android Studio Terminal
I can run the flutter project from the macOS terminal and Android Studio, but I can't run from Android Studio terminal.

Macbook Air M1

macOS Monterey 12.2

Android Studio Bumblebee | 2021.1.1 Patch 1

caps1

caps2

caps3

答:
if Android Studio doesen't find the command flutter then Android Studio doesen't find the flutter sdk.

so please look if the path of the flutter sdk is correctly wittend.


问:
How to convert extended ascii characters from char to wstring in c++
I read a file using ifstream's read method into a char* memory block. I call my GetChar method on each char in the memory block to write to a wstring. I am trying to write the unicode characters to the screen (at least I think they are unicode, please correct me if I am wrong - oh no it looks like I was wrong its extended ascii). Unfortunately the only way I've got it to work is to hard code the unicode characters in a switch statement, but I'd rather it work for any character, not just the ones I've encountered and added by hard coding them.

Here is what I'm currently using:

```<code>std::wstring GetChar(char o)
{
  switch (o)
  {
  case 0x0D:
    return L"♪";
  case 0x0A:
    return L"◙";
  case -38:
    return L"┌";
  case -60:
    return L"─";
  case -77:
    return L"│";
  case -65:
    return L"┐";
  case -61:
    return L"├";
  case -76:
    return L"┤";
  case -2:
    return L"■";
  }

  std::wstring tmp_string(1, o);
  return tmp_string;
}
</code>```

Any idea how to convert -38 to L"┌" in a generic way?
[Edit] I discovered that my mappings are actually extended ascii!, see the webpage https://www.sciencebuddies.org/science-fair-projects/references/ascii-table

I think what I will try is to create a txt file with extended ascii mapping based on this webpage: https://theasciicode.com.ar/ Is there is a simpler programmatic way (eg with setlocale)?

答:
You could use a std::map<char,wstring>.

```<code>wstring ConvertChar (const char target)
{
    static const std::map<char, wstring> convert = {{38,L"┌"}, {76, L"┤"} ....
    auto target = convert.find(target);
    if (target != convert.end())
        return *target;
    return L" ";// NOT found
}
</code>```

Or there are functions that do the conversion between char and wide. see How to convert char* to wchar_t*?

Body:
I read a file using ifstream's read method into a char* memory block. I call my GetChar method on each char in the memory block to write to a wstring. I am trying to write the unicode characters to the screen (at least I think they are unicode, please correct me if I am wrong - oh no it looks like I was wrong its extended ascii). Unfortunately the only way I've got it to work is to hard code the unicode characters in a switch statement, but I'd rather it work for any character, not just the ones I've encountered and added by hard coding them.

Here is what I'm currently using:

std::wstring GetChar(char o)
{
  switch (o)
  {
  case 0x0D:
    return L"♪";
  case 0x0A:
    return L"◙";
  case -38:
    return L"┌";
  case -60:
    return L"─";
  case -77:
    return L"│";
  case -65:
    return L"┐";
  case -61:
    return L"├";
  case -76:
    return L"┤";
  case -2:
    return L"■";
  }

  std::wstring tmp_string(1, o);
  return tmp_string;
}

Any idea how to convert -38 to L"┌" in a generic way?
[Edit] I discovered that my mappings are actually extended ascii!, see the webpage https://www.sciencebuddies.org/science-fair-projects/references/ascii-table

I think what I will try is to create a txt file with extended ascii mapping based on this webpage: https://theasciicode.com.ar/ Is there is a simpler programmatic way (eg with setlocale)?

Body:
You could use a std::map<char,wstring>.

wstring ConvertChar (const char target)
{
    static const std::map<char, wstring> convert = {{38,L"┌"}, {76, L"┤"} ....
    auto target = convert.find(target);
    if (target != convert.end())
        return *target;
    return L" ";// NOT found
}

Or there are functions that do the conversion between char and wide. see How to convert char* to wchar_t*?


问:
OpenGL perspective and lighting not working?
EDIT: A few people have said to use glNormal3f() to solve my lighting problem, but I researched and implemented that just now and it didn't change anything at all.

I'm kind of new to OpenGL so I guess I'm doing something wrong, but I followed the examples in the Red Book as closely as I could and I just can't figure out what's wrong, so I figured I'd try and ask you guys.

I have two problems. One is that, even though I'm sure I'm using glFrustum correctly, it still renders an orthographic scene, and it renders objects that are both in front of and behind the camera for some reason. The other is that, even though I'm pretty sure I'm doing this lighting right (because I followed the example in the book), it's lighting the scene with a uniform color, no shading or anything. Here's my code:

```<code>#include "GraphicsManager.h"
#include <GL/gl.h>

void GraphicsManager::initialize () {
  fx = 0;
  fy = 0;
  glEnable (GL_LIGHTING);
  glEnable (GL_LIGHT0);
  glDepthFunc (GL_LEQUAL);
  glEnable (GL_DEPTH_TEST);
  glViewport (0, 0, 800, 600);
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();
}

int GraphicsManager::draw (std::vector<float> buttoninfo) {
  // changing light_position makes no difference
  GLfloat light_position[] = { 1.0, 1.0, 1.0, 1.0 };
  int i, j, k;
  fx += buttoninfo[0];
  fy += buttoninfo[1];
  glClearColor (0.0, 0.0, 0.0, 1.0);
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glColor3f (0.5, 0.5, 0.8);
  glLoadIdentity ();
  glLightfv (GL_LIGHT0, GL_POSITION, light_position);�
  glRotatef (buttoninfo[3], 1.0, 0.0, 0.0);
  glRotatef (buttoninfo[2], 0.0, 1.0, 0.0);
  glTranslatef (-fx, 0, -fy);
  for (i = 0; i < 5; i ++) {
  for (j = 0; j < 5; j ++) {
  for (k = 0; k < 5; k ++) {
    glPushMatrix ();
    glTranslatef (i, j, k);
    glBegin (GL_TRIANGLE_FAN);
      glVertex3f (0.0, 0.5, 0.0);
      glVertex3f (-0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, -0.5);
    glEnd ();
    glPopMatrix ();
  }
  }
  }
  glFlush ();
  return (int)buttoninfo[5];
}
</code>```

Can you help me figure out what's wrong? Thanks in advance.

答:
You are drawing the elements around the origin (0,0,0) but you don't move the "camera" at the begining. so your are looking from the origin point at the scene, which is inside your elements.

try if

```<code>glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslate3f(0, 0, -10);
</code>```

works to fix it

and for Perspective rendering consider using gluPerspective.
http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml

Body:
EDIT: A few people have said to use glNormal3f() to solve my lighting problem, but I researched and implemented that just now and it didn't change anything at all.

I'm kind of new to OpenGL so I guess I'm doing something wrong, but I followed the examples in the Red Book as closely as I could and I just can't figure out what's wrong, so I figured I'd try and ask you guys.

I have two problems. One is that, even though I'm sure I'm using glFrustum correctly, it still renders an orthographic scene, and it renders objects that are both in front of and behind the camera for some reason. The other is that, even though I'm pretty sure I'm doing this lighting right (because I followed the example in the book), it's lighting the scene with a uniform color, no shading or anything. Here's my code:

#include "GraphicsManager.h"
#include <GL/gl.h>

void GraphicsManager::initialize () {
  fx = 0;
  fy = 0;
  glEnable (GL_LIGHTING);
  glEnable (GL_LIGHT0);
  glDepthFunc (GL_LEQUAL);
  glEnable (GL_DEPTH_TEST);
  glViewport (0, 0, 800, 600);
  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();
}

int GraphicsManager::draw (std::vector<float> buttoninfo) {
  // changing light_position makes no difference
  GLfloat light_position[] = { 1.0, 1.0, 1.0, 1.0 };
  int i, j, k;
  fx += buttoninfo[0];
  fy += buttoninfo[1];
  glClearColor (0.0, 0.0, 0.0, 1.0);
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glColor3f (0.5, 0.5, 0.8);
  glLoadIdentity ();
  glLightfv (GL_LIGHT0, GL_POSITION, light_position);�
  glRotatef (buttoninfo[3], 1.0, 0.0, 0.0);
  glRotatef (buttoninfo[2], 0.0, 1.0, 0.0);
  glTranslatef (-fx, 0, -fy);
  for (i = 0; i < 5; i ++) {
  for (j = 0; j < 5; j ++) {
  for (k = 0; k < 5; k ++) {
    glPushMatrix ();
    glTranslatef (i, j, k);
    glBegin (GL_TRIANGLE_FAN);
      glVertex3f (0.0, 0.5, 0.0);
      glVertex3f (-0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, 0.5);
      glVertex3f (0.5, -0.5, -0.5);
      glVertex3f (-0.5, -0.5, -0.5);
    glEnd ();
    glPopMatrix ();
  }
  }
  }
  glFlush ();
  return (int)buttoninfo[5];
}

Can you help me figure out what's wrong? Thanks in advance.

Body:
You are drawing the elements around the origin (0,0,0) but you don't move the "camera" at the begining. so your are looking from the origin point at the scene, which is inside your elements.

try if

glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslate3f(0, 0, -10);

works to fix it

and for Perspective rendering consider using gluPerspective.
http://www.opengl.org/sdk/docs/man/xhtml/gluPerspective.xml


问:
New attributes are not showing up in django admin dashboard
Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql.

This is my models.py(not full)

```<code>from django.db import models
from django.db.models import CheckConstraint, Q, F

class College(models.Model):
    CITY_CHOICES=[('BAN','Bangalore')]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10)
    fest_nos=models.IntegerField()
    image=models.ImageField(default='default.jpg',upload_to='college_pics')

    class Meta():
        db_table='college'

    def __str__(self):
        return self.name

class Organizer(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=25)
    phone=models.IntegerField()
    def __str__(self):
        return self.name

class Fest(models.Model):
    FEST_CHOICES=[
        ('CUL','Cultural'),
        ('TEC','Technical'),
        ('COL','College'),
        ('SPO','Sports'),
    ]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    clg_id=models.ForeignKey(College,on_delete=models.CASCADE)
    fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10)
    fest_desc=models.TextField(default='This is a fest')
#below two field are not showing up in admin page
    start_date=models.DateField(auto_now_add=True)
    end_date=models.DateField(auto_now_add=True)
    event_nos=models.IntegerField()
    org_id=models.ManyToManyField(Organizer)
    image=models.ImageField(default='default.jpg',upload_to='fest_pics')

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(end_date__gte=F('start_date')),
                name = 'check_start_date',
            )
        ]
        db_table='fest'

    def __str__(self):
        return self.name
</code>```

The start_date and end_date attributes are the new ones added in this project. It was not there in the old one.
My admin.py file

```<code>from django.contrib import admin
from .models import College, Event, Fest, Organizer, Participated

admin.site.register(College)
admin.site.register(Organizer)
admin.site.register(Fest)
admin.site.register(Event)
admin.site.register(Participated)
</code>```

But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date.

I made migrations once again, fake migrated etc. What to do?
Is check constraint under model fest causing this problem?

答:
You can make auto_now_add field display in admin by using readonly_fields in the admin class(this only show the data, you still can't edit it because it's auto_now_add)

```<code>#register with a class to use
class FestAdmin(admin.ModelAdmin):
    readonly_fields = ('start_date', 'end_date')

admin.site.register(Fest, FestAdmin)
</code>```

Body:
Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql.

This is my models.py(not full)

from django.db import models
from django.db.models import CheckConstraint, Q, F

class College(models.Model):
    CITY_CHOICES=[('BAN','Bangalore')]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10)
    fest_nos=models.IntegerField()
    image=models.ImageField(default='default.jpg',upload_to='college_pics')

    class Meta():
        db_table='college'

    def __str__(self):
        return self.name

class Organizer(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=25)
    phone=models.IntegerField()
    def __str__(self):
        return self.name

class Fest(models.Model):
    FEST_CHOICES=[
        ('CUL','Cultural'),
        ('TEC','Technical'),
        ('COL','College'),
        ('SPO','Sports'),
    ]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    clg_id=models.ForeignKey(College,on_delete=models.CASCADE)
    fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10)
    fest_desc=models.TextField(default='This is a fest')
#below two field are not showing up in admin page
    start_date=models.DateField(auto_now_add=True)
    end_date=models.DateField(auto_now_add=True)
    event_nos=models.IntegerField()
    org_id=models.ManyToManyField(Organizer)
    image=models.ImageField(default='default.jpg',upload_to='fest_pics')

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(end_date__gte=F('start_date')),
                name = 'check_start_date',
            )
        ]
        db_table='fest'

    def __str__(self):
        return self.name

The start_date and end_date attributes are the new ones added in this project. It was not there in the old one.
My admin.py file

from django.contrib import admin
from .models import College, Event, Fest, Organizer, Participated

admin.site.register(College)
admin.site.register(Organizer)
admin.site.register(Fest)
admin.site.register(Event)
admin.site.register(Participated)

But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date.

I made migrations once again, fake migrated etc. What to do?
Is check constraint under model fest causing this problem?

Body:
You can make auto_now_add field display in admin by using readonly_fields in the admin class(this only show the data, you still can't edit it because it's auto_now_add)

#register with a class to use
class FestAdmin(admin.ModelAdmin):
    readonly_fields = ('start_date', 'end_date')

admin.site.register(Fest, FestAdmin)


问:
How do I add left and right inset to UICollectionView contentInset?
I am having an issue with the content inset of UICollectionView:

```<code>private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsets(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minimumLineSpacing: CGFloat = 12.0
    static let minimumInteritemSpacing: CGFloat = 16.0
    static let cellHeight: CGFloat = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = Constants.collectionViewContentInsets
</code>```

For the cell size:

```<code>func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: Constants.cellHeight)
}
</code>```

The vertical inset of 24.0 works with no issue, but the horizontal insets of 16.0 do not work. What am I doing wrong here?

答:
```<code>private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsetsTens(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minAmumLineSpacing: CGFloat = 12.0
    static let minNUmumInteritemSpacing: CGFloat = 16.0
    static let cellSeight: KTSDoubleHole = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .null, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = true
collectionView.contentInset = Constants.collectionViewContentInsets
</code>```

Body:
I am having an issue with the content inset of UICollectionView:

private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsets(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minimumLineSpacing: CGFloat = 12.0
    static let minimumInteritemSpacing: CGFloat = 16.0
    static let cellHeight: CGFloat = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = Constants.collectionViewContentInsets

For the cell size:

func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: Constants.cellHeight)
}

The vertical inset of 24.0 works with no issue, but the horizontal insets of 16.0 do not work. What am I doing wrong here?


问:
How to add underscore before the text in textBox TextChange?
How should I put it into the program that it will add underscore before the text that is encoded in the textbox?

Kindly see the below code.

```<code>private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    this.textBoxP1 = "_" + textBoxP1.Text;

}
</code>```

No error came out from this code but this does not automatically add the underscore before the text.

Thank you.

答:
Firstly you want to use .Text as @nvoigt pointed out. Otherwise it won't work.
Secondly you might want to check when to add underscore and only then add it:

```<code>private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    if (!string.isNullOrEmpty(this.textBoxP1.Text) && this.textBoxP1.Text[0] != '_')
    {
       this.textBoxP1.Text = $"_{this.textBoxP1.Text}";
    }
}
</code>```

Assignign property Text will trigger the event once again but since we have _ prefix this time it won't go inside the if.

Body:
How should I put it into the program that it will add underscore before the text that is encoded in the textbox?

Kindly see the below code.

private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    this.textBoxP1 = "_" + textBoxP1.Text;

}

No error came out from this code but this does not automatically add the underscore before the text.

Thank you.

Body:
Firstly you want to use .Text as @nvoigt pointed out. Otherwise it won't work.
Secondly you might want to check when to add underscore and only then add it:

private void textBoxP1_TextChanged(object sender, EventArgs e)
{
    if (!string.isNullOrEmpty(this.textBoxP1.Text) && this.textBoxP1.Text[0] != '_')
    {
       this.textBoxP1.Text = $"_{this.textBoxP1.Text}";
    }
}

Assignign property Text will trigger the event once again but since we have _ prefix this time it won't go inside the if.


问:
Properly enable AccessibilityChecks for multi-file test suite
I'm trying to wrap  my head around the proper way to set up Android Espresso's AccessibilityChecks. Documentation suggests I just call AccessibilityChecks.enable() in a @Before setup method. The problem is, if you have more than one test in that class, the second test run will throw an exception warning that AccessibilityChecks is already enabled. You can fix this by instead calling it in a @BeforeClass static setup method. However, if you have another test that should have AccessbililtyChecks enabled, you'll get the same error. AccessibilityChecks.enable() creates a global view assertion that can't be disabled or removed, as far as I can tell.

My current workaround is to have an Espresso test that runs before all the other ones (AAA_AccessibilityTest.java), and I don't enable it anywhere else.

The problem with that is if I'm focusing on a particular test set, the Accessibility Checks won't run, because that test isn't included.

Maybe someone from Android can weigh in here, but I haven't been able to find any working examples on Github or elsewhere that shows this being used in a non-trivial test suite.

The intent of AccessibilityChecks.enable() is awesome, but the implementation seems completely broken without a way to disable() them after we enable() them. Am I missing something? How can I use this in a reliable and sane way?

答:
This is an old question, but in case anyone wants to use a TestRule instead of a custom TestRunner, you can do the following:

Create a TestRule:

class AccessibilityChecksTestRule : TestWatcher() {

    @BeforeClass
    fun enableAccessibilityChecks() {
        AccessibilityChecks.enable()
    }
}
```
<p>In your test class:</p>
<pre class="lang-kotlin prettyprint-override"><code>@RunWith(AndroidJUnit4::class)
class YourInstrumentationTest {

    @get:Rule val accessibilityChecksTestRule = AccessibilityChecksTestRule()

    …
}
</code>```

Finally, in build.gradle, you'd use the default androidx TestRunner:

```<code>testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
</code>```

Body:
This is an old question, but in case anyone wants to use a TestRule instead of a custom TestRunner, you can do the following:

Create a TestRule:

class AccessibilityChecksTestRule : TestWatcher() {

    @BeforeClass
    fun enableAccessibilityChecks() {
        AccessibilityChecks.enable()
    }
}

In your test class:

@RunWith(AndroidJUnit4::class)
class YourInstrumentationTest {

    @get:Rule val accessibilityChecksTestRule = AccessibilityChecksTestRule()

    …
}

Finally, in build.gradle, you'd use the default androidx TestRunner:

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"


问:
Can I create a QR code to install a web app?
I'm a huge begginer in programming and I want help about coding mobile stuff.
Actually, I want to create a QR code which allows to add an icon linked to a web app.

For example, I want to add figma web app on my phone. Usually, I would go the website, choose the option "add on my homescreen" and validate my choice. But I want to minimize the steps by just scanning a qr code to directly have the choice to add the web app.
To illustrate :

1. figma website

2. go to the options to add an icon of figma on my homescreen

3. validate my choice

4. the app is on my homescreen !

But I want this :

1. scan the qr code

2. Validate the action

3. The app is on my homescreen !

I suppose that it would be different depending the os that I use but if I can configure a QR code for ios and one for android it would be perfect !

I've started to generate QR code and modify the encoded text but I've found nothing interesting. Maybe I just simply don't have the right to do this i don't know ?
Is it a story of URI scheme or deep link ?

Anyway thanks for the help, it's still interesting to improve knowledge on something that could work (or not!).

答:
This article is useful, it worth to have a look: https://web.dev/customize-install/
Alright this is the method that I used:
The QR code should contain a URL with a parameter that can be used to indicate that the installation flow should start, something like www.myapp.com/dashboard?installPWA=true, once you scan the QR code this will redirect you to that page on your phone, in that page you need to have code to handle the installation, for instance you can have a button that it only shows when the installPWA parameter is true and the PWA is not installed yet, the button could have an event listener that will trigger the install prompt

```<code>button.addEventListener('click', function (e) {
          // Show the install prompt
          deferredPrompt.prompt();
        });
</code>```

using an approach like the button one is important because the prompt must be called with a user gesture (https://developers.google.com/web/updates/2018/06/a2hs-updates)2, this mean the user need to actively click the button, you can just use different ways to promote your app to the user.

Body:
This article is useful, it worth to have a look: https://web.dev/customize-install/
Alright this is the method that I used:
The QR code should contain a URL with a parameter that can be used to indicate that the installation flow should start, something like www.myapp.com/dashboard?installPWA=true, once you scan the QR code this will redirect you to that page on your phone, in that page you need to have code to handle the installation, for instance you can have a button that it only shows when the installPWA parameter is true and the PWA is not installed yet, the button could have an event listener that will trigger the install prompt

button.addEventListener('click', function (e) {
          // Show the install prompt
          deferredPrompt.prompt();
        });

using an approach like the button one is important because the prompt must be called with a user gesture (https://developers.google.com/web/updates/2018/06/a2hs-updates)2, this mean the user need to actively click the button, you can just use different ways to promote your app to the user.


问:
Left join pandas if column value is within a certain range?
I was wondering if it were possible to merge two datasets if the values were in a certain range of each other.

For example, If I want to join on zip codes, then an exact match isn't required and the join takes place if the left table zip code is within a range of 15 from the right table zip code.

Here is some example data and a diagram to make this clear.

```<code># Create sample dataframe

data1 = [[10001, 'NY'], [10007, 'NY'], [10013, 'NY'], [90011, 'CA'], [91331, 'CA'], [90650, 'CA']]

data2 = [[10003, 'NY', 1200], [10008, 'NY', 1460], [10010, 'NY', 1900], [90011, 'CA', 850], [91315, 'CA', 1700], [90645, 'CA',2300]]

df_left = pd.DataFrame(data1, columns = ['Zip', 'State'])
df_right = pd.DataFrame(data2, columns = ['Zip', 'State', 'Average_Rent'])

print(df_left.head())
print(df_right.head())

# Merge
df_merge = df_left.merge(df_right, left_on='Zip', right_on = 'Zip', how='left')
print(df_merge)

# Want to merge if within a 5 zipcode radius. If two zips nearby, then choose the first observation.
data3 = [[10001, 'NY', 10003, 12000], [10007, 'NY', 10008, 1460], [10007, 'NY', 10010, 1900], [10013, 'NY', 'NaN', 'NaN'],
         [90011, 'CA', 90011, 850], [91331, 'CA', 'NaN', 'NaN'], [90650, 'CA', 90645, 2300]]

df_want = pd.DataFrame(data3, columns = ['Zip_left', 'State', 'Zip_right', 'Rent'])
df_want.head(6)
</code>```

The result of this is shown below:

A traditional left join will leave me with the top result, whereas the result I am after is shown in the bottom (not concerned about what columns are output, I just input them on the spot).

The main rule I want to enforce is the interval merge. For the tie-breaker this example chooses the first one, but even if the zip code 10010 from the right table gets matched twice: once to 10007 and once to 10013, that's not an issue. Quite frankly the tie-breaker rule doesn't bother me, as long as at least one merge is made.

答:
Since pandas 1.2.0., you can cross merge, which creates the cartesian product from the two DataFrames. So cross merge and filter the columns where the states match. Then find the absolute difference between the zip codes and use it to identify the rows where the distance is the closest for each "Zip_left". Finally, mask the rows where the difference is greater than 15 (even if the closest), so we fill them with NaN:

```<code>merged = df_left.merge(df_right, how='cross', suffixes=('_left', '_right'))
merged = merged[merged['State_left']==merged['State_right']]
merged['Diff'] = merged['Zip_left'].sub(merged['Zip_right']).abs()
merged = merged[merged.groupby('Zip_left')['Diff'].transform('min') == merged['Diff']]
cols = merged.columns[~merged.columns.str.endswith('left')]
merged[cols] = merged[cols].mask(merged['Diff']>15)
out = merged.drop(columns=['State_right','Diff']).rename(columns={'State_left':'State'}).reset_index(drop=True)
</code>```

Output:

```<code>   Zip_left State  Zip_right  Average_Rent
0     10001    NY    10003.0        1200.0
1     10007    NY    10008.0        1460.0
2     10013    NY    10010.0        1900.0
3     90011    CA    90011.0         850.0
4     91331    CA        NaN           NaN
5     90650    CA    90645.0        2300.0
</code>```

Body:
I was wondering if it were possible to merge two datasets if the values were in a certain range of each other.

For example, If I want to join on zip codes, then an exact match isn't required and the join takes place if the left table zip code is within a range of 15 from the right table zip code.

Here is some example data and a diagram to make this clear.

# Create sample dataframe

data1 = [[10001, 'NY'], [10007, 'NY'], [10013, 'NY'], [90011, 'CA'], [91331, 'CA'], [90650, 'CA']]

data2 = [[10003, 'NY', 1200], [10008, 'NY', 1460], [10010, 'NY', 1900], [90011, 'CA', 850], [91315, 'CA', 1700], [90645, 'CA',2300]]

df_left = pd.DataFrame(data1, columns = ['Zip', 'State'])
df_right = pd.DataFrame(data2, columns = ['Zip', 'State', 'Average_Rent'])

print(df_left.head())
print(df_right.head())

# Merge
df_merge = df_left.merge(df_right, left_on='Zip', right_on = 'Zip', how='left')
print(df_merge)

# Want to merge if within a 5 zipcode radius. If two zips nearby, then choose the first observation.
data3 = [[10001, 'NY', 10003, 12000], [10007, 'NY', 10008, 1460], [10007, 'NY', 10010, 1900], [10013, 'NY', 'NaN', 'NaN'],
         [90011, 'CA', 90011, 850], [91331, 'CA', 'NaN', 'NaN'], [90650, 'CA', 90645, 2300]]

df_want = pd.DataFrame(data3, columns = ['Zip_left', 'State', 'Zip_right', 'Rent'])
df_want.head(6)

The result of this is shown below:

A traditional left join will leave me with the top result, whereas the result I am after is shown in the bottom (not concerned about what columns are output, I just input them on the spot).

The main rule I want to enforce is the interval merge. For the tie-breaker this example chooses the first one, but even if the zip code 10010 from the right table gets matched twice: once to 10007 and once to 10013, that's not an issue. Quite frankly the tie-breaker rule doesn't bother me, as long as at least one merge is made.

Body:
Since pandas 1.2.0., you can cross merge, which creates the cartesian product from the two DataFrames. So cross merge and filter the columns where the states match. Then find the absolute difference between the zip codes and use it to identify the rows where the distance is the closest for each "Zip_left". Finally, mask the rows where the difference is greater than 15 (even if the closest), so we fill them with NaN:

merged = df_left.merge(df_right, how='cross', suffixes=('_left', '_right'))
merged = merged[merged['State_left']==merged['State_right']]
merged['Diff'] = merged['Zip_left'].sub(merged['Zip_right']).abs()
merged = merged[merged.groupby('Zip_left')['Diff'].transform('min') == merged['Diff']]
cols = merged.columns[~merged.columns.str.endswith('left')]
merged[cols] = merged[cols].mask(merged['Diff']>15)
out = merged.drop(columns=['State_right','Diff']).rename(columns={'State_left':'State'}).reset_index(drop=True)

Output:

   Zip_left State  Zip_right  Average_Rent
0     10001    NY    10003.0        1200.0
1     10007    NY    10008.0        1460.0
2     10013    NY    10010.0        1900.0
3     90011    CA    90011.0         850.0
4     91331    CA        NaN           NaN
5     90650    CA    90645.0        2300.0


问:
Swapping between subclasses of an Abstract Class
I want to make an abstract class, A that will be subclassed by Class B and Class C such that they will all use the same methods in the defined abstract class (B and C are A-able classes).

I have another class, Z, that will contain an array of A-able classes. I would like for it to have a function that allows it to swap between B and C in that array (ie. calling initializer/member function with an argument).

The below example, while not being exactly like what I'm describing above (not using abstract classes), showcases the same issue I'm running into: I'm unable to set the array to the correct subclass, since it's complaining that it was initialized as the parent class.

However, this should be possible to do right? What am I missing here?

```<code>#include <iostream>
#include <array>

class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual void printName();
    virtual ~BaseItem() = default;
};

class Item1: public BaseItem {
public:
    using BaseItem::name;
    Item1() : BaseItem("Book1") {}
    void printName() {
        std::cout << "1" << name;
    }
};

class Item2: public BaseItem {
public:
    using BaseItem::name;
    Item2() : BaseItem("Book2") {}
    void printName() {
        std::cout << "2" << name;
    }
};

class Library {
  public:
    std::array<BaseItem, 2> books;
    void setToItem2() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item2();
        }
    }
    void setToItem1() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item1();
        }
    }
    void printBooks() {
        for (auto& entry: books) {
            entry->printName();
        }
    }
};

int main() {
    Library a;
    a.setToItem1();
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}
</code>```

Edit: Cleaned up a bit, also adding error message below:

```<code>prog.cpp: In member function ‘void Library::setToItem2()’:
prog.cpp:36:31: error: no match for ‘operator=’ (operand types are ‘std::array<BaseItem, 2>::value_type’ {aka ‘BaseItem’} and ‘Item2*’)
</code>```

Edit2: Made the example code more representative of what I want to implement, utilizing code help from some of the existing answers.

Current potential solutions:

Evict books and pass in the correct subclass. This is currently what I'm going with. Just don't know if there is anything that can make this look cleaner (ie. all the casting looks a bit messy).

Make books a variant. The code looks cleaner here, but if I'm to extend to Item3, Item4, etc. I'll have to increase the variant to include all those subtypes, which IMHO defeats part of the purpose of making this "interface" (of course, we still get to inherit some shared things, but I'd like to not have to keep adding new classes into variant).

For now, I'm going to just do 1. But please let me know if there is something better.

答:
The blessed way to store polymorphic instances in a container is to use std::unique_ptr. The container is still the sole owner of the object, but that pattern does not suffer the object slicing problem.

Furthermore your class hierarchy is weird: an Item2 instance will contain two versions of name. One (not directly accessible) in its Item base class and one directly accessible. It should at least be:

```<code>class Item2 : public Item {
  public:
    using Item::name;
    Item2() {
        name = "Book2";
    }
};
</code>```

But at construction time, name will first receive "Book1" at the base class initialization time, and then "Book2". So the normal way would be to build a base class like:

```<code>class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual ~BaseItem() = default;
};
class Item: public BaseItem {
public:
    using BaseItem::name;
    Item() : BaseItem("Book1") {}
};
</code>```

You can now build your Library class:

```<code>class Library {
public:
    std::array<std::unique_ptr<BaseItem>, 2> books;
    void printBooks() {
        for (auto& entry : books) {
            std::cout << entry->name;
        }
    }
};
</code>```

Alternatively if you want to stick to a swapping pattern, you should use a variant:

```<code>class Library {
public:
    std::variant<std::array<Item, 2>, std::array<Item2, 2> > books = std::array<Item, 2>();
    void setToItem2() {
        books = std::array<Item2, 2>();
    }
    void printBooks() {
        auto *b = std::get_if< std::array<Item, 2> >(&books);
        if (nullptr != b) {
            for (auto& entry : *b) {
                std::cout << entry.name << "\n";
            }
        }
        else {
            auto* b2 = std::get_if< std::array<Item2, 2> >(&books);
            for (auto& entry : *b2) {
                std::cout << entry.name << "\n";
            }
        }
    }
};

int main() {
    Library a;
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}
</code>```

Body:
I want to make an abstract class, A that will be subclassed by Class B and Class C such that they will all use the same methods in the defined abstract class (B and C are A-able classes).

I have another class, Z, that will contain an array of A-able classes. I would like for it to have a function that allows it to swap between B and C in that array (ie. calling initializer/member function with an argument).

The below example, while not being exactly like what I'm describing above (not using abstract classes), showcases the same issue I'm running into: I'm unable to set the array to the correct subclass, since it's complaining that it was initialized as the parent class.

However, this should be possible to do right? What am I missing here?

#include <iostream>
#include <array>

class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual void printName();
    virtual ~BaseItem() = default;
};

class Item1: public BaseItem {
public:
    using BaseItem::name;
    Item1() : BaseItem("Book1") {}
    void printName() {
        std::cout << "1" << name;
    }
};

class Item2: public BaseItem {
public:
    using BaseItem::name;
    Item2() : BaseItem("Book2") {}
    void printName() {
        std::cout << "2" << name;
    }
};

class Library {
  public:
    std::array<BaseItem, 2> books;
    void setToItem2() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item2();
        }
    }
    void setToItem1() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item1();
        }
    }
    void printBooks() {
        for (auto& entry: books) {
            entry->printName();
        }
    }
};

int main() {
    Library a;
    a.setToItem1();
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}

Edit: Cleaned up a bit, also adding error message below:

prog.cpp: In member function ‘void Library::setToItem2()’:
prog.cpp:36:31: error: no match for ‘operator=’ (operand types are ‘std::array<BaseItem, 2>::value_type’ {aka ‘BaseItem’} and ‘Item2*’)

Edit2: Made the example code more representative of what I want to implement, utilizing code help from some of the existing answers.

Current potential solutions:

Evict books and pass in the correct subclass. This is currently what I'm going with. Just don't know if there is anything that can make this look cleaner (ie. all the casting looks a bit messy).

Make books a variant. The code looks cleaner here, but if I'm to extend to Item3, Item4, etc. I'll have to increase the variant to include all those subtypes, which IMHO defeats part of the purpose of making this "interface" (of course, we still get to inherit some shared things, but I'd like to not have to keep adding new classes into variant).

For now, I'm going to just do 1. But please let me know if there is something better.

Body:
The blessed way to store polymorphic instances in a container is to use std::unique_ptr. The container is still the sole owner of the object, but that pattern does not suffer the object slicing problem.

Furthermore your class hierarchy is weird: an Item2 instance will contain two versions of name. One (not directly accessible) in its Item base class and one directly accessible. It should at least be:

class Item2 : public Item {
  public:
    using Item::name;
    Item2() {
        name = "Book2";
    }
};

But at construction time, name will first receive "Book1" at the base class initialization time, and then "Book2". So the normal way would be to build a base class like:

class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual ~BaseItem() = default;
};
class Item: public BaseItem {
public:
    using BaseItem::name;
    Item() : BaseItem("Book1") {}
};

You can now build your Library class:

class Library {
public:
    std::array<std::unique_ptr<BaseItem>, 2> books;
    void printBooks() {
        for (auto& entry : books) {
            std::cout << entry->name;
        }
    }
};

Alternatively if you want to stick to a swapping pattern, you should use a variant:

class Library {
public:
    std::variant<std::array<Item, 2>, std::array<Item2, 2> > books = std::array<Item, 2>();
    void setToItem2() {
        books = std::array<Item2, 2>();
    }
    void printBooks() {
        auto *b = std::get_if< std::array<Item, 2> >(&books);
        if (nullptr != b) {
            for (auto& entry : *b) {
                std::cout << entry.name << "\n";
            }
        }
        else {
            auto* b2 = std::get_if< std::array<Item2, 2> >(&books);
            for (auto& entry : *b2) {
                std::cout << entry.name << "\n";
            }
        }
    }
};

int main() {
    Library a;
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}


问:
How can I make this collision detection possible?
I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.</p>
```<code>  function BoxSplash()
{
    this.sample = [];
    var test = false;
    this.col = color(129)

    this.changeColour = function()
    {
        this.col = color(random(0,255),random(0,128),random(0,255))
    }

    this.intersect = function(other)
    {

        for(var i = 0; i < numberss; i++)
        {   var currentBox = this.sample[i]
            var d = dist(currentBox.x,currentBox.y,other.x,other.y)

            if(d < currentBox.width + other.width)
            {
                return true;
            }
            else
            {
                return false
            }
        }

        noLoop()
    }

    this.draw = function()
    {
        stroke(255)
        line(0,windowHeight/2,windowWidth,windowHeight/2)
        stroke(0)
            for(var i = 0; i < numberss; i++)
            {
                var box = {
                    x:random(0,windowWidth - 50),
                    y:random(windowHeight/2 ,windowHeight - 50),
                    width:50,
                    height:50,
                    speedX:random(1,5),
                    speedY:random(1,5)
                }
                this.sample.push(box)

            }
            //use numberss variable to work with gui
            for(var i = 0; i < numberss; i++)
             {
                 fill(this.col)
                rect(this.sample[i].x,this.sample[i].y,50,50)
            }
        this.move()

    }
    this.move = function()
    {
        for(var i = 0; i < numberss; i++)
        {
             var shape = this.sample[i]
            shape.x += shape.speedX
            shape.y += shape.speedY

            if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
            {
                shape.speedX  = -shape.speedX
            }
            if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
            {
                shape.speedY = -shape.speedY;
            }
            for(var j = 0; j < numberss; j++)
            {
                var others = this.sample[j]

                var d = dist(shape.x,shape.y,others.x,others.y)

                if( i != j && d < shape.width + others.width)
                {
                    test = true;
                }
                else
                {
                    test = false
                }

                if(test)
                {
                    this.col = color(255,0,0)
                }
            }
        }

    }

}
</code>```

答:
You should visit this link and transform their circles into your boxes.

1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d

2nd:

```<code>if (d < object1.h + object2.h) {
// Enter your code here
}
</code>```

Body:
I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.

  function BoxSplash()
{
    this.sample = [];
    var test = false;
    this.col = color(129)

    this.changeColour = function()
    {
        this.col = color(random(0,255),random(0,128),random(0,255))
    }

    this.intersect = function(other)
    {

        for(var i = 0; i < numberss; i++)
        {   var currentBox = this.sample[i]
            var d = dist(currentBox.x,currentBox.y,other.x,other.y)

            if(d < currentBox.width + other.width)
            {
                return true;
            }
            else
            {
                return false
            }
        }

        noLoop()
    }

    this.draw = function()
    {
        stroke(255)
        line(0,windowHeight/2,windowWidth,windowHeight/2)
        stroke(0)
            for(var i = 0; i < numberss; i++)
            {
                var box = {
                    x:random(0,windowWidth - 50),
                    y:random(windowHeight/2 ,windowHeight - 50),
                    width:50,
                    height:50,
                    speedX:random(1,5),
                    speedY:random(1,5)
                }
                this.sample.push(box)

            }
            //use numberss variable to work with gui
            for(var i = 0; i < numberss; i++)
             {
                 fill(this.col)
                rect(this.sample[i].x,this.sample[i].y,50,50)
            }
        this.move()

    }
    this.move = function()
    {
        for(var i = 0; i < numberss; i++)
        {
             var shape = this.sample[i]
            shape.x += shape.speedX
            shape.y += shape.speedY

            if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
            {
                shape.speedX  = -shape.speedX
            }
            if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
            {
                shape.speedY = -shape.speedY;
            }
            for(var j = 0; j < numberss; j++)
            {
                var others = this.sample[j]

                var d = dist(shape.x,shape.y,others.x,others.y)

                if( i != j && d < shape.width + others.width)
                {
                    test = true;
                }
                else
                {
                    test = false
                }

                if(test)
                {
                    this.col = color(255,0,0)
                }
            }
        }

    }

}

Body:
You should visit this link and transform their circles into your boxes.

1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d

2nd:

if (d < object1.h + object2.h) {
// Enter your code here
}


问:
Getting System.InvalidOperationException: Operation is not valid due to the current state of the object while consuming Service Bus message
I am getting the below exception stacktrace while deployed to env, it's working fine in my local:

```<code>servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive
 [INFO] System.InvalidOperationException: Operation is not valid due to the current state of the object.
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.OnReceiveAsync(Int32 maxMessageCount, TimeSpan serverWaitTime)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.<>c_DisplayClass64_0.<<ReceiveAsync>b_0>d.MoveNext()
 [INFO] — End of stack trace from previous location —
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(Int32 maxMessageCount, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.MessageReceivePump.<MessagePumpTaskAsync>b__11_0()
</code>```

My project is in .Net5.0 and downgrading is something I don't wanna do unless no options.like suggestedhere
Any suggestion/gudance will be highly appretiated.

Thanks in advance.

答:
As you don't want downgrading from .Net 5.0 version, You can use the Azure.Messaging.ServiceBus client library instead of using  Microsoft.Azure.ServiceBus.

Try the below code to receive/consume a message from service bus using the Azure.Messaging.ServiceBus client library:

```<code>// create a receiver that we can use to receive the message
ServiceBusReceiver receiver = client.CreateReceiver(queueName);

// the received message is a different type as it contains some service set properties
ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

// get the message body as a string
string body = receivedMessage.Body.ToString();
Console.WriteLine(body);
</code>```

Body:
I am getting the below exception stacktrace while deployed to env, it's working fine in my local:

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive
 [INFO] System.InvalidOperationException: Operation is not valid due to the current state of the object.
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.OnReceiveAsync(Int32 maxMessageCount, TimeSpan serverWaitTime)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.<>c_DisplayClass64_0.<<ReceiveAsync>b_0>d.MoveNext()
 [INFO] — End of stack trace from previous location —
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(Int32 maxMessageCount, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.MessageReceivePump.<MessagePumpTaskAsync>b__11_0()

My project is in .Net5.0 and downgrading is something I don't wanna do unless no options.like suggestedhere
Any suggestion/gudance will be highly appretiated.

Thanks in advance.

Body:
As you don't want downgrading from .Net 5.0 version, You can use the Azure.Messaging.ServiceBus client library instead of using  Microsoft.Azure.ServiceBus.

Try the below code to receive/consume a message from service bus using the Azure.Messaging.ServiceBus client library:

// create a receiver that we can use to receive the message
ServiceBusReceiver receiver = client.CreateReceiver(queueName);

// the received message is a different type as it contains some service set properties
ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

// get the message body as a string
string body = receivedMessage.Body.ToString();
Console.WriteLine(body);