问:
I need to delete an element in an array everytime a user press , but when is being output after deletion I got long number like ; 124352919
```<code>int main ()
{
    int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75};

    char ans;
    int i = 0;
    int pos = 0;

    cout<<"Press y to generate number"<<"\n";
    cin >> ans;

    while(ans=='y'||ans=='Y')
    {
        cout<<"\n\nEnter position to Delete number :: ";
        cin>>pos;

        --pos;

        for(i=pos;i<=size-1;i++)
        {
            a[i]=a[i+1];
            cout<<" "<<a[i]<<" ";
        }
        cout<<"\nNew Array is :: \n\n";

        for(i=0;i<size-1;i++)
        {

        }

        cout<<"Press y to generate number"<<"\n";
        cin >> ans;

    }

    cout << "\n\n";
</code>```
<p>//I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end</p>

答:
You can't delete an element from an array, but you can delete a vector element like this:</p>
```<code>#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 };

    char ans;
    int pos = 0;

    cout << "Press y to generate number: ";
    cin >> ans;

    while (ans == 'y' || ans == 'Y')
    {
        cout << "\n\nEnter position to Delete number: ";
        cin >> pos;

        --pos;

        nums.erase(nums.begin() + pos);
        cout << "\nNew Array is:\n\n";

        for (const auto& element : nums)
        {
            std::cout << element << '\n';
        }

        cout << "Press y to generate number" << "\n";
        cin >> ans;
    }
}
</code>```

Body:
int main ()
{
    int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75};

    char ans;
    int i = 0;
    int pos = 0;

    cout<<"Press y to generate number"<<"\n";
    cin >> ans;

    while(ans=='y'||ans=='Y')
    {
        cout<<"\n\nEnter position to Delete number :: ";
        cin>>pos;

        --pos;

        for(i=pos;i<=size-1;i++)
        {
            a[i]=a[i+1];
            cout<<" "<<a[i]<<" ";
        }
        cout<<"\nNew Array is :: \n\n";

        for(i=0;i<size-1;i++)
        {

        }

        cout<<"Press y to generate number"<<"\n";
        cin >> ans;

    }

    cout << "\n\n";

//I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end

Body:
You can't delete an element from an array, but you can delete a vector element like this:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75 };

    char ans;
    int pos = 0;

    cout << "Press y to generate number: ";
    cin >> ans;

    while (ans == 'y' || ans == 'Y')
    {
        cout << "\n\nEnter position to Delete number: ";
        cin >> pos;

        --pos;

        nums.erase(nums.begin() + pos);
        cout << "\nNew Array is:\n\n";

        for (const auto& element : nums)
        {
            std::cout << element << '\n';
        }

        cout << "Press y to generate number" << "\n";
        cin >> ans;
    }
}


来源: stackexchange

问:
Uninstall php 7 in ubuntu 18.04
I have a server that has an application that runs with PHP 5.6. But I upgraded the server from Ubuntu 14.04 to 18.04 and in the process I also upgraded PHP to 7.2.
Now I'm trying to uninstall it but I'm finding difficult.

I have run the command:

sudo apt-get remove php

and

sudo apt-get remove --purge php

Its says that PHP it's not installed, but running
php --version
I'm still seeing the version 7 of PHP.

PHP 7.2.19-0ubuntu0.18.04.2 (cli) (built: Aug 12 2019 19:34:28) ( NTS )
  Copyright (c) 1997-2018 The PHP Group
  Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
      with Zend OPcache v7.2.19-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

答:
Just run

sudo apt-get purge 'php*'

ContentLicense: CC BY-SA 4.0

Title: Uninstall php 7 in ubuntu 18.04

Body:
Just run

sudo apt-get purge 'php*'


问:
stop processes in batch files with python
I am new to programming and I want to make a python tool to automate a process. I want to end a running batch file without killing it, is this even possible?
I don't want to kill it, because it scans for IP packages in running time and when stopped, creates a file with the data, and I want to work with this file.
Thanks for your help</p>

答:
In your batch file, at an appropriate point, try

```<code>if not exist stop.txt goto continue
del stop.txt
:wait
timeout /t 1 >nul
if not exist start.txt goto wait
del start.txt
:continue
</code>```

Use python to create stop.txt. Wait until stop.txt is deleted and read your log file. Then create start.txt to restart.

I'm assuming that your log file is actually closed - that us your logging is

```<code>echo .... >>logfile
</code>```

not

```<code>(
 command-sequence
)>logfile
</code>```

where the logfile is not closed until the command-sequence block is terminated.

Body:
In your batch file, at an appropriate point, try

if not exist stop.txt goto continue
del stop.txt
:wait
timeout /t 1 >nul
if not exist start.txt goto wait
del start.txt
:continue

Use python to create stop.txt. Wait until stop.txt is deleted and read your log file. Then create start.txt to restart.

I'm assuming that your log file is actually closed - that us your logging is

echo .... >>logfile

not

(
 command-sequence
)>logfile

where the logfile is not closed until the command-sequence block is terminated.


问:
Sweep Algorithm
Who can recommend me a good sweep algorithm which would have good results for double data?
Some documentation, methods, anything.

This is a sweep algorithm for detecting the intersection points of a graph in the 2-dimensional space. The graph is always closed.

答:
I have implemented 3 variants so far for the sweep algorithm for detecting the intersection of a planar closed graph. I have big data that represent the graph (like 200 edges or more. The vertices are pairs of points in 2D the edges are a pair of two vertices- one being the source the other being the destination) which is read from another function implemented in a C++ library for some other purpose.

The problem is that the 3 implementation work fine on integers or doubles data that are not as long, but when I tried anyone of these 3 implementations on my data representing the graph I got different result each time and not even the good ones.

Whether I have all the intersections that I want but some other points from the graph (which are not intersection)

Whether I have some points from the graph as result but some intersections that I need are missing from the computed result

Whether I have just the intersections needed

This all depends on the sort function that I had I saw and maybe on something else but I cannot figure it out. The sort function orders the edges of the graph as follows:

Given two edges as E1(Vstart,Vend), E2(Vstart,Vend):

```<code>x.E1.Vstart<x.E2.Vstart or
x.E1.Vstart==x.E2.Vstart and y.E1.Vstart<y.E2.Vstart or
x.E1.Vstart==x.E2.Vstart and y.E1.Vstart==y.E2.Vstart and slope(E1)<slope(E2)
</code>```

I thought this sort function is good for monoticity and other cases but apparently it is working only for some cases when besides the regular intersections it detects some other intersections also; for some cases it does work at all in that it does not computes all the intersections but just some point from the graph.

OwnerDisplayName: madalina

ContentLicense: CC BY-SA 2.5

Title: Sweep Algorithm

LastEditorDisplayName: mmyers

Body:
I have implemented 3 variants so far for the sweep algorithm for detecting the intersection of a planar closed graph. I have big data that represent the graph (like 200 edges or more. The vertices are pairs of points in 2D the edges are a pair of two vertices- one being the source the other being the destination) which is read from another function implemented in a C++ library for some other purpose.

The problem is that the 3 implementation work fine on integers or doubles data that are not as long, but when I tried anyone of these 3 implementations on my data representing the graph I got different result each time and not even the good ones.

Whether I have all the intersections that I want but some other points from the graph (which are not intersection)

Whether I have some points from the graph as result but some intersections that I need are missing from the computed result

Whether I have just the intersections needed

This all depends on the sort function that I had I saw and maybe on something else but I cannot figure it out. The sort function orders the edges of the graph as follows:

Given two edges as E1(Vstart,Vend), E2(Vstart,Vend):

x.E1.Vstart<x.E2.Vstart or
x.E1.Vstart==x.E2.Vstart and y.E1.Vstart<y.E2.Vstart or
x.E1.Vstart==x.E2.Vstart and y.E1.Vstart==y.E2.Vstart and slope(E1)<slope(E2)

I thought this sort function is good for monoticity and other cases but apparently it is working only for some cases when besides the regular intersections it detects some other intersections also; for some cases it does work at all in that it does not computes all the intersections but just some point from the graph.

ContentLicense: CC BY-SA 3.0


问:
weights with glm() versus weights_column with h2o.glm()
I want to make sure the weights_column arguments in h2o.glm() is the same as the weights argument in glm(). To compare, I am looking at the rmse of both models using the Seatbelts dataset in R. I don't think a weight is needed in this model, but for the sake of demonstration I added one.

```<code>head(Seatbelts)

Seatbelts<-Seatbelts[complete.cases(Seatbelts),]

## 75% of the sample size
smp_size <- floor(0.75 * nrow(Seatbelts))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Seatbelts)), size = smp_size)

train <- Seatbelts[train_ind, ]
test <- Seatbelts[-train_ind, ]

# glm()
m1 <- glm(DriversKilled  ~  front + rear + kms + PetrolPrice + VanKilled + law,
          family=poisson(link = "log"),
          weights = drivers,
          data=train)

pred <- predict(m1, test)
RMSE(pred = pred, obs = test$DriversKilled)
</code>```

The rmse is 120.5797.

```<code># h2o.glm()
library(h2o)
h2o.init()

train <- as.h2o(train)
test <- as.h2o(test)
m2 <- h2o.glm(x = c("front", "rear", "kms", "PetrolPrice", "VanKilled", "law"),
                 y = "DriversKilled",
                 training_frame = train,
                 family = 'poisson',
                 link = 'log',
                 lambda = 0,
                 weights_column = "drivers")

# performance metrics on test data
h2o.performance(m2, test)
</code>```

The rmse is 18.65627. Why do these models have such different rmse? Am I using the weights_column argument in h2o.glm() incorrectly?

答:
With the glm your predictions are in log form. To compare them you need to use the exponential of the predictions.

```<code>Metrics::rmse(exp(pred), test$DriversKilled)
[1] 18.09796
</code>```

If you make a prediction with h2o you will see that it has already taken care of the exponential operation.

Note that the models differ slightly in the rmse. h2o.glm has a lot more going on in the background.

Body:
I want to make sure the weights_column arguments in h2o.glm() is the same as the weights argument in glm(). To compare, I am looking at the rmse of both models using the Seatbelts dataset in R. I don't think a weight is needed in this model, but for the sake of demonstration I added one.

head(Seatbelts)

Seatbelts<-Seatbelts[complete.cases(Seatbelts),]

## 75% of the sample size
smp_size <- floor(0.75 * nrow(Seatbelts))

## set the seed to make your partition reproducible
set.seed(123)
train_ind <- sample(seq_len(nrow(Seatbelts)), size = smp_size)

train <- Seatbelts[train_ind, ]
test <- Seatbelts[-train_ind, ]

# glm()
m1 <- glm(DriversKilled  ~  front + rear + kms + PetrolPrice + VanKilled + law,
          family=poisson(link = "log"),
          weights = drivers,
          data=train)

pred <- predict(m1, test)
RMSE(pred = pred, obs = test$DriversKilled)

The rmse is 120.5797.

# h2o.glm()
library(h2o)
h2o.init()

train <- as.h2o(train)
test <- as.h2o(test)
m2 <- h2o.glm(x = c("front", "rear", "kms", "PetrolPrice", "VanKilled", "law"),
                 y = "DriversKilled",
                 training_frame = train,
                 family = 'poisson',
                 link = 'log',
                 lambda = 0,
                 weights_column = "drivers")

# performance metrics on test data
h2o.performance(m2, test)

The rmse is 18.65627. Why do these models have such different rmse? Am I using the weights_column argument in h2o.glm() incorrectly?

Body:
With the glm your predictions are in log form. To compare them you need to use the exponential of the predictions.

Metrics::rmse(exp(pred), test$DriversKilled)
[1] 18.09796

If you make a prediction with h2o you will see that it has already taken care of the exponential operation.

Note that the models differ slightly in the rmse. h2o.glm has a lot more going on in the background.


问:
React router v6 useNavigate does not work with redux dispatch
In my React app, I am trying to navigate to a new page after I dispatch an redux action. This needs to happen on my form onSubmit.

The submit works as intended and the redux action is dispatched successfully, but the react router does not navigate to the given page after the redux action is dispatched. If I remove the redux dispatch, it navigates successfully. I'm using the useNavigate hook from react-router-dom.

My form is used as per my UI library Mantine. https://mantine.dev/hooks/use-form/

What is wrong here?

The useNavigate hook definition:

```<code>const navigate = useNavigate();
</code>```

The onSubmit function:

```<code>const handlerAddShipping = (values: any) => {

      dispatch(saveShippingAddress(values)); //if removed, navigate works.

      navigate("/payment"); //does not navigate with the previous line.

};
</code>```

How routes are defined in my index.tsx

```<code> <Provider store={store}>
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<App />} />
              <Route path="/shipping" element={<Shipping />} />
              <Route path="/payment" element={<Payment />} />
            </Routes>
          </BrowserRouter>
    </Provider>
</code>```

The useForm hook from my UI library Mantine:

```<code>  const form = useForm({
    initialValues: {
      address: "",
      city: "",
      postalCode: "",
      country: "",
    },
    validationRules: {
      address: (value) => value.trim().length >= 2,
      city: (value) => value.trim().length >= 2,
      postalCode: (value) => value.trim().length >= 2,
      country: (value) => value.trim().length >= 2,
    },
    errorMessages: {
      address: "Address is not valid",
      city: "City is not valid",
      postalCode: "Postal Code is not valid",
      country: "Country is not valid",
    },
  });
</code>```

The form:

```<code><form onSubmit={form.onSubmit((values) =>
      handlerAddShipping(values))}>
      <Grid sx={{ marginTop: "2rem" }}>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Address"
            {...form.getInputProps("address")}
            error={form.errors.address}
            label="Address"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your City"
            {...form.getInputProps("city")}
            error={form.errors.city}
            label="City"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Postal Code"
            {...form.getInputProps("postalCode")}
            error={form.errors.postalCode}
            label="Postal Code"
          />
        </Col>
        <Col span={12}>
          <TextInput
            placeholder="Your Country"
            {...form.getInputProps("country")}
            error={form.errors.country}
            label="Country"
          />
        </Col>
        <Col span={12}>
          <Button
            type="submit">
            Continue
          </Button>
        </Col>
      </Grid>
    </form>
</code>```

React router version :
"react-router-dom": "^6.2.1"

答:
// check your flows something else is happening after the navigate method, if not then try just with a return.
const handlerAddShipping = (values: any) => {
  dispatch(saveShippingAddress(values));
  navigate("/payment");
  return;
};

// send your callback through the action and execute it there
const handlerAddShipping = (values: any) => {
  dispatch(saveShippingAddress(values, () => navigate("/payment")));
};

//if that doesnt work try this
const handlerAddShipping = (values: any) => {
  dispatch(saveShippingAddress(values));
  setTimeout(() => navigate("/payment"), 400);
};```

Body:
In my React app, I am trying to navigate to a new page after I dispatch an redux action. This needs to happen on my form onSubmit.

The submit works as intended and the redux action is dispatched successfully, but the react router does not navigate to the given page after the redux action is dispatched. If I remove the redux dispatch, it navigates successfully. I'm using the useNavigate hook from react-router-dom.

My form is used as per my UI library Mantine. https://mantine.dev/hooks/use-form/

What is wrong here?

The useNavigate hook definition:

const navigate = useNavigate();

The onSubmit function:

const handlerAddShipping = (values: any) => {

      dispatch(saveShippingAddress(values)); //if removed, navigate works.

      navigate("/payment"); //does not navigate with the previous line.

};

How routes are defined in my index.tsx

 <Provider store={store}>
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<App />} />
              <Route path="/shipping" element={<Shipping />} />
              <Route path="/payment" element={<Payment />} />
            </Routes>
          </BrowserRouter>
    </Provider>

The useForm hook from my UI library Mantine:

  const form = useForm({
    initialValues: {
      address: "",
      city: "",
      postalCode: "",
      country: "",
    },
    validationRules: {
      address: (value) => value.trim().length >= 2,
      city: (value) => value.trim().length >= 2,
      postalCode: (value) => value.trim().length >= 2,
      country: (value) => value.trim().length >= 2,
    },
    errorMessages: {
      address: "Address is not valid",
      city: "City is not valid",
      postalCode: "Postal Code is not valid",
      country: "Country is not valid",
    },
  });

The form:

<form onSubmit={form.onSubmit((values) =>
      handlerAddShipping(values))}>
      <Grid sx={{ marginTop: "2rem" }}>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Address"
            {...form.getInputProps("address")}
            error={form.errors.address}
            label="Address"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your City"
            {...form.getInputProps("city")}
            error={form.errors.city}
            label="City"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Postal Code"
            {...form.getInputProps("postalCode")}
            error={form.errors.postalCode}
            label="Postal Code"
          />
        </Col>
        <Col span={12}>
          <TextInput
            placeholder="Your Country"
            {...form.getInputProps("country")}
            error={form.errors.country}
            label="Country"
          />
        </Col>
        <Col span={12}>
          <Button
            type="submit">
            Continue
          </Button>
        </Col>
      </Grid>
    </form>

React router version :
"react-router-dom": "^6.2.1"


问:
Disable Schema Validation for Cosmos DB?
I'm using Cosmos DB in Azure. I recently changed the schema to add more information. However, I'm confused because Cosmos uses SQL to query the database. Further, it seems I can't query based on the new schema because I receive the following error messsage:

```<code> Message: {"errors":[{"severity":"Error","location":{"start":22,"end":29},"code":"SC2001","message":"Identifier 'comment' could not be resolved."}]}
</code>```

So I'm wondering is it possible to disable schema validation so I can query on the new comment attribute, without getting this error message.

Further, I'm confused how Cosmos DB can be considered a NoSQL database if it behaves much the same as MySQL.

Edit: The query I am using is

```<code>SELECT * FROM c
WHERE comment = ""
</code>```

答:
The error is not related to the schema, the error is saying your query is incorrectly written.

Following the official documentation (for example, https://learn.microsoft.com/azure/cosmos-db/sql/sql-query-getting-started#query-the-json-items)

The query should be:

```<code>SELECT * FROM c
WHERE c.comment = ""
</code>```

Keep in mind that that query is not checking for documents that do not have the comment property, it's basically filtering documents that do have the comment property with an empty string value.

Body:
I'm using Cosmos DB in Azure. I recently changed the schema to add more information. However, I'm confused because Cosmos uses SQL to query the database. Further, it seems I can't query based on the new schema because I receive the following error messsage:

 Message: {"errors":[{"severity":"Error","location":{"start":22,"end":29},"code":"SC2001","message":"Identifier 'comment' could not be resolved."}]}

So I'm wondering is it possible to disable schema validation so I can query on the new comment attribute, without getting this error message.

Further, I'm confused how Cosmos DB can be considered a NoSQL database if it behaves much the same as MySQL.

Edit: The query I am using is

SELECT * FROM c
WHERE comment = ""

Body:
The error is not related to the schema, the error is saying your query is incorrectly written.

Following the official documentation (for example, https://learn.microsoft.com/azure/cosmos-db/sql/sql-query-getting-started#query-the-json-items)

The query should be:

SELECT * FROM c
WHERE c.comment = ""

Keep in mind that that query is not checking for documents that do not have the comment property, it's basically filtering documents that do have the comment property with an empty string value.


问:
Can anyone explain what am i doing wrong
Question:-Write a Python function transpose(m) that takes as input a two dimensional matrix m and returns the transpose of m. The argument m should remain undisturbed by the function.

```<code>def transpose(l):
m=l[:]
lst=[[] for x in range(len(m[0)]
for i in range(0,len(m)):
    for j in range(0,len(m[i])):
        lst[j].append(m[i][j])
return lst
l=[[1,2,3,4,5],[4,5,6,7,8,9]]
</code>```

ERROR

lst[j].append(m[i][j])

IndexError: list index out of range

答:
Your List l has two lists with 5 and 6 elements.

So, the range of j in range(len(m[1])) is 0 - 5 (6 numbers), which results in index out of range for lst (which only have 5 elements).

def transpose(l):
    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst
l = [[1,2,3,4,5],[4,5,6,7,8]]
```
<p>But I would add a checking part at the beginning of the function</p>
<pre class="lang-py prettyprint-override"><code>def transpose(l):
    iterator = iter(l)
    lists_len = len(next(iterator))
    if not all(len(a) == lists_len for a in iterator):
        # Do something here

    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst
</code>```

Body:
Question:-Write a Python function transpose(m) that takes as input a two dimensional matrix m and returns the transpose of m. The argument m should remain undisturbed by the function.

def transpose(l):
m=l[:]
lst=[[] for x in range(len(m[0)]
for i in range(0,len(m)):
    for j in range(0,len(m[i])):
        lst[j].append(m[i][j])
return lst
l=[[1,2,3,4,5],[4,5,6,7,8,9]]

ERROR

lst[j].append(m[i][j])

IndexError: list index out of range

Body:
Your List l has two lists with 5 and 6 elements.

So, the range of j in range(len(m[1])) is 0 - 5 (6 numbers), which results in index out of range for lst (which only have 5 elements).

def transpose(l):
    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst
l = [[1,2,3,4,5],[4,5,6,7,8]]

But I would add a checking part at the beginning of the function

def transpose(l):
    iterator = iter(l)
    lists_len = len(next(iterator))
    if not all(len(a) == lists_len for a in iterator):
        # Do something here

    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst


问:
How to make a div with rounded corners
How do you make a div so that its border corners are rounded?</p>

答:
Here it is:</p>
```<code><style type="text/css">
div.test
{
    width: 115px;
    padding: 10px;
    border: 2px solid #000;
    border-radius: 15px;
    -moz-border-radius: 15px;
}
</style>
<div class="test">This is some text!</div>
</code>```

Title: How to make a div with rounded corners

Body:
Here it is:

<style type="text/css">
div.test
{
    width: 115px;
    padding: 10px;
    border: 2px solid #000;
    border-radius: 15px;
    -moz-border-radius: 15px;
}
</style>
<div class="test">This is some text!</div>


问:
Running a script on all .ai files in a directory
I'm a graphic designer and a beginner at coding. So please dumb down for me :)

I have a script that I run through Illustrator. It embeds an image and removes a clipping mask on the file. I need this script to run on multiple .ai files in a folder.

The thing is, I cannot create a batch action (in Illustrator) to run the script. Our IT guy doesn't want to add the script to our Illustrator settings on multiple accounts. Is there a way to add code to my script to do this?

I need it to open all the files, run the script and save. The files can be left open on Illustrator, no need to close.

What code do I need to add to my script?

I am on a Mac not PC.

答:
It can be done this way:</p>
```<code>function my_script() {

    // copy a full text of your script here

    // or include the jsx file this way:
    # include '~/Desktop/script/my_script.jsx'

}

function main() {

    var folder = Folder.selectDialog('Please, select the folder');
    if (!(folder instanceof Folder)) return;

    var files = folder.getFiles('*.ai');
    if (files.length == 0) {
        alert('Folder doesn\'t content AI files');
        return;
    }

    var i = files.length;
    while (i--) {
        var doc = app.open(files[i]);
        my_script();             // <------- here your script is running
        doc.save();
        doc.close();
    }

    alert(files.length + ' files were processed');
}

main();
</code>```

Body:
It can be done this way:

function my_script() {

    // copy a full text of your script here

    // or include the jsx file this way:
    # include '~/Desktop/script/my_script.jsx'

}

function main() {

    var folder = Folder.selectDialog('Please, select the folder');
    if (!(folder instanceof Folder)) return;

    var files = folder.getFiles('*.ai');
    if (files.length == 0) {
        alert('Folder doesn\'t content AI files');
        return;
    }

    var i = files.length;
    while (i--) {
        var doc = app.open(files[i]);
        my_script();             // <------- here your script is running
        doc.save();
        doc.close();
    }

    alert(files.length + ' files were processed');
}

main();


问:
Communication RSU/OBU in veins framework
I need to implement a communication between the RSU and the OBU (the OBU sends a message to the RSU and the RSU does some checks then it will answer the OBU), for that I implemented the handleMessage function in the two . cc files (one for the OBU and the other for the RSU), but when I run it, for the moment, the OBU doesn't send the message to the RSUs, only the OBUs receive the message (same for the RSUs). My question is how to send the message so that the RSU of the same region receives the message? and without the other OBUs receiving the message? I have also implemented the onWSM function in the two files but it does not run, in which case the onWSM function is used?

```<code>#include <veins/modules/application/traci/OBU.h>
#include "veins/modules/application/traci/ReqObu_m.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"
#include "veins/modules/application/traci/MyVeinsApp.h"

using namespace OBU;
using namespace omnetpp;

Define_Module(OBU::OBUMessage);

using namespace veins;

Define_Module(veins::MyVeinsApp);

void OBU::OBUMessage::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);
    EV << "on est dans la fonction initilize_obu:\n";
    char msgName[30];
   sprintf(msgName, "Req_depuis_lOBU_index_%d", findHost()->getIndex());
     ReqObu * req= new ReqObu(msgName);
    findHost()->getDisplayString().setTagArg("i", 1, "green");

    EV << "message forme :"<< req->getName()<< "\n";
    if(findHost()->getIndex()==0)
    {
        req->setDestination(1);
    } else req->setDestination(0);

    scheduleAt(25.2, req);

}

void MyVeinsApp::onWSM(BaseFrame1609_4* frame)
{
    // Your application has received a data message from another car or RSU
    // code for handling the message goes here, see TraciDemo11p.cc for examples
    veins::ReqObu* wsm = check_and_cast<veins::ReqObu*>(frame);

   findHost()->getDisplayString().setTagArg("i", 1, "red");
   EV << "we are in onWSM____OBU\n";
   scheduleAt(simTime() + 2 + uniform(0.01, 0.2), wsm);
}

void OBU::OBUMessage::handleMessage(cMessage *msg )
{
    EV << "we are in handleMessage_OBU:\n";

   ReqObu *ttmsg =dynamic_cast<ReqObu*>(msg);
   if(ttmsg->getDestination()!=findHost()->getIndex())
   {  EV << "I am : " << findHost()->getIndex()<< " destination : "<< ttmsg->getDestination()<<" and the msg :"<< ttmsg->getName()<<"\n";
   }
}
</code>```

RSU.cc :

```<code>#include <veins/modules/application/traci/FN.h>
#include "veins/modules/application/traci/ReqObu_m.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"

using namespace FN;
using namespace omnetpp;

Define_Module(FN::FogMessage);

void FN::FogMessage::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);

    EV << "on est dans la fonction initilize_fn:\n";
    char msgName[30];
    sprintf(msgName, "Req_depuis_RSU_index_%d", findHost()->getIndex());
    veins::ReqObu * req= new veins::ReqObu(msgName);

    EV << "RSU____ :"<< req->getName()<< "\n";
    if(findHost()->getIndex()==0)
    {
        req->setDestination(1);
    } else req->setDestination(0);

    scheduleAt(35.2, req);
}

void FN::FogMessage::handleMessage(cMessage *msg)
{
    EV << "on est dans la fonction handleMessage_RSU:\n";
    veins::ReqObu *ttmsg =check_and_cast<veins::ReqObu*>(msg);
       EV << "RSU : destination : " << ttmsg->getDestination()<< " and le msg :"<< ttmsg->getName()<<"\n";
}
void FN::FogMessage::onWSM(veins::BaseFrame1609_4* msg)
{
    veins::ReqObu *ttmsg =check_and_cast<veins::ReqObu*>(msg);
    EV << "on est dans la fonction onWSM____RSU:\n";
    }
</code>```

ReqOBU.msg :

```<code>cplusplus {{
#include "veins/modules/messages/BaseFrame1609_4_m.h"
}}
namespace veins;

class BaseFrame1609_4;

message Cert
{
    int pIDfN=-1;
    long tmpFN =-1;
    int pIDOBU=-1;

}
message BlockchainMsg
{
    int pFN;
    long tmpFN;
    int pOBU;
    long tmpOBU;
    }
message ReqObu extends BaseFrame1609_4
{
    int pID=-1;
    long tMP=-1 ;
    int destination=-1;
}

</code>```

答:
The methods sendDown( ) and sendDelayedDown( ) are used to send the messages to other nodes in omnet++. May be you are calling handleSelfMessage( ). Including code here may help.

update:
My Guess went right. There is no handleSelfMessage() definition. scheduleAt() invokes handleSelfMessage() and its not there.

upvote if I am correct

Body:
I need to implement a communication between the RSU and the OBU (the OBU sends a message to the RSU and the RSU does some checks then it will answer the OBU), for that I implemented the handleMessage function in the two . cc files (one for the OBU and the other for the RSU), but when I run it, for the moment, the OBU doesn't send the message to the RSUs, only the OBUs receive the message (same for the RSUs). My question is how to send the message so that the RSU of the same region receives the message? and without the other OBUs receiving the message? I have also implemented the onWSM function in the two files but it does not run, in which case the onWSM function is used?

#include <veins/modules/application/traci/OBU.h>
#include "veins/modules/application/traci/ReqObu_m.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"
#include "veins/modules/application/traci/MyVeinsApp.h"

using namespace OBU;
using namespace omnetpp;

Define_Module(OBU::OBUMessage);

using namespace veins;

Define_Module(veins::MyVeinsApp);

void OBU::OBUMessage::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);
    EV << "on est dans la fonction initilize_obu:\n";
    char msgName[30];
   sprintf(msgName, "Req_depuis_lOBU_index_%d", findHost()->getIndex());
     ReqObu * req= new ReqObu(msgName);
    findHost()->getDisplayString().setTagArg("i", 1, "green");

    EV << "message forme :"<< req->getName()<< "\n";
    if(findHost()->getIndex()==0)
    {
        req->setDestination(1);
    } else req->setDestination(0);

    scheduleAt(25.2, req);

}

void MyVeinsApp::onWSM(BaseFrame1609_4* frame)
{
    // Your application has received a data message from another car or RSU
    // code for handling the message goes here, see TraciDemo11p.cc for examples
    veins::ReqObu* wsm = check_and_cast<veins::ReqObu*>(frame);

   findHost()->getDisplayString().setTagArg("i", 1, "red");
   EV << "we are in onWSM____OBU\n";
   scheduleAt(simTime() + 2 + uniform(0.01, 0.2), wsm);
}

void OBU::OBUMessage::handleMessage(cMessage *msg )
{
    EV << "we are in handleMessage_OBU:\n";

   ReqObu *ttmsg =dynamic_cast<ReqObu*>(msg);
   if(ttmsg->getDestination()!=findHost()->getIndex())
   {  EV << "I am : " << findHost()->getIndex()<< " destination : "<< ttmsg->getDestination()<<" and the msg :"<< ttmsg->getName()<<"\n";
   }
}

RSU.cc :

#include <veins/modules/application/traci/FN.h>
#include "veins/modules/application/traci/ReqObu_m.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"

using namespace FN;
using namespace omnetpp;

Define_Module(FN::FogMessage);

void FN::FogMessage::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);

    EV << "on est dans la fonction initilize_fn:\n";
    char msgName[30];
    sprintf(msgName, "Req_depuis_RSU_index_%d", findHost()->getIndex());
    veins::ReqObu * req= new veins::ReqObu(msgName);

    EV << "RSU____ :"<< req->getName()<< "\n";
    if(findHost()->getIndex()==0)
    {
        req->setDestination(1);
    } else req->setDestination(0);

    scheduleAt(35.2, req);
}

void FN::FogMessage::handleMessage(cMessage *msg)
{
    EV << "on est dans la fonction handleMessage_RSU:\n";
    veins::ReqObu *ttmsg =check_and_cast<veins::ReqObu*>(msg);
       EV << "RSU : destination : " << ttmsg->getDestination()<< " and le msg :"<< ttmsg->getName()<<"\n";
}
void FN::FogMessage::onWSM(veins::BaseFrame1609_4* msg)
{
    veins::ReqObu *ttmsg =check_and_cast<veins::ReqObu*>(msg);
    EV << "on est dans la fonction onWSM____RSU:\n";
    }

ReqOBU.msg :

cplusplus {{
#include "veins/modules/messages/BaseFrame1609_4_m.h"
}}
namespace veins;

class BaseFrame1609_4;

message Cert
{
    int pIDfN=-1;
    long tmpFN =-1;
    int pIDOBU=-1;

}
message BlockchainMsg
{
    int pFN;
    long tmpFN;
    int pOBU;
    long tmpOBU;
    }
message ReqObu extends BaseFrame1609_4
{
    int pID=-1;
    long tMP=-1 ;
    int destination=-1;
}


问:
Multiple headers in Rest Assured does not work and respond with a 401 Unauthorized code
Need to know if I am making some mistake in passing the headers in the below code (Is this the right way of passing multiple headers in rest assured?)  I get an exception as followed in Rest Assured . The header values passed works well in Jmeter and postman.

Exception:

java.lang.AssertionError: 1 expectation failed.
Expected status code <200> doesn't match actual status code <401>.

Code:

```<code>    import org.junit.Test;
    import com.jayway.restassured.*;
    import com.jayway.restassured.http.ContentType;
    import static org.hamcrest.Matchers.*;
    import static com.jayway.restassured.RestAssured.*;

    public class APIresponse

    {

    @Test
        public void response ()
        {
            given().
                header("Id", "abc").
                header("Key", "NuDVhdsfYmNkDLOZQ").
                header("ConId", "xyz").
            when().
                get("testme/api/uk?Id=DT44FR100731").
            then().
                //contentType(ContentType.JSON).
                body("response.code", equalTo("200"));
        }

    }
</code>```

答:
Below code will be worked with io.rest-assured:rest-assured:4.2.1

```<code>    public void response ()
        {
           Header idHeader = new Header("Id", "abc");
           Header keyHeader = new Header("Key", "NuDVhdsfYmNkDLOZQ");
           Header conIdHeader = new Header("ConId", "xyz");
           Headers headers = new Headers(idHeader, keyHeader, conIdHeader);
            given().
                headers(headers).
            when().
                get("testme/api/uk?Id=DT44FR100731").
            then().
                //contentType(ContentType.JSON).
                body("response.code", equalTo("200"));
        }
</code>```

Body:
Need to know if I am making some mistake in passing the headers in the below code (Is this the right way of passing multiple headers in rest assured?)  I get an exception as followed in Rest Assured . The header values passed works well in Jmeter and postman.

Exception:

java.lang.AssertionError: 1 expectation failed.
Expected status code <200> doesn't match actual status code <401>.

Code:

    import org.junit.Test;
    import com.jayway.restassured.*;
    import com.jayway.restassured.http.ContentType;
    import static org.hamcrest.Matchers.*;
    import static com.jayway.restassured.RestAssured.*;

    public class APIresponse

    {

    @Test
        public void response ()
        {
            given().
                header("Id", "abc").
                header("Key", "NuDVhdsfYmNkDLOZQ").
                header("ConId", "xyz").
            when().
                get("testme/api/uk?Id=DT44FR100731").
            then().
                //contentType(ContentType.JSON).
                body("response.code", equalTo("200"));
        }

    }

Body:
Below code will be worked with io.rest-assured:rest-assured:4.2.1

    public void response ()
        {
           Header idHeader = new Header("Id", "abc");
           Header keyHeader = new Header("Key", "NuDVhdsfYmNkDLOZQ");
           Header conIdHeader = new Header("ConId", "xyz");
           Headers headers = new Headers(idHeader, keyHeader, conIdHeader);
            given().
                headers(headers).
            when().
                get("testme/api/uk?Id=DT44FR100731").
            then().
                //contentType(ContentType.JSON).
                body("response.code", equalTo("200"));
        }


问:
How to add element with props in react router V6
```<code><Router>
  <Route path="/Cart" element={<Cart data />}>
  </Route>
</Router>
</code>```

Here I want to pass the element Cart ,but the Cart has props of the following type

```<code>export type CartItemtype = {
  id: number;
  category: string;
  description: string;
  image: string;
  price: string;
  title: string;
  amount: number;
}
</code>```

data is an array of type CartItemtype[]
I am using react-router-dom V6

Below is App.tsx and Item.tsx file

```<code>import React from 'react';
import Page from './Page';
import Todo from './models/todo';
import FormSubmission from './FormSubmission';
import Registration from './Registration';
import { useState } from 'react';
import { Type } from 'typescript';
import { useQuery } from 'react-query';
import { Wrapper, StyledButton } from './App.styles';
import Item from './Item/Item';
import Grid from '@material-ui/core/Grid';
import Drawer from '@material-ui/core/Drawer';
import Badge from '@material-ui/core/Badge';
import Button from 'react-bootstrap/Button';
import Cart from './Cart/Cart';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import { useNavigate } from "react-router-dom";

export type CartItemtype = {
  id: number;
  category: string;
  description: string;
  image: string;
  price: string;
  title: string;
  amount: number;
}

const getProducts = async (): Promise<CartItemtype[]> => {
  return await (await fetch("https://fakestoreapi.com/products")).json();
}

function App() {
  const [cartOpen, setCartOpen] = useState(false);
  const [cartItems, setCartItems] = useState([] as CartItemtype[]);
  const { data, isLoading, error } = useQuery<CartItemtype[]>('products', getProducts);
  //useQuery is a react hook
  console.log(data);
  const getTotalItems = (items: CartItemtype[]) => null;

  const navigate = useNavigate();
  const handleClick = () => {
    navigate("/Cart");
  }
  if (error) return <div>Somethimg went wrong</div>;
  <Router>
    <Route path="/Cart" element={<Cart data />}>
    </Route>
  </Router>
  return (
    <Wrapper>
      <Button onClick={handleClick}>Navigate To Cart</Button>
      <Grid container spacing={3}>
        {data?.map((item, key) => {
          return (

            <Grid item key={item.id} xs={12} sm={4}>
              <Item item={item} />
            </Grid>

          )
        })
        }
      </Grid>
    </Wrapper>
  );
};
export default App;

import {CartItemtype} from '../App';
import {Wrapper} from './Item.styles';
import Button from 'react-bootstrap/Button';

type itemProps={
    item:CartItemtype;
    // handleAddToCart:(clickedItem:CartItemtype)=>void;
}
const handleAddToCart = (clickedItem: CartItemtype) => null;

const Item:React.FC<itemProps>=({item})=>
{
return(
<Wrapper>
<img src={item.image} alt={item.title}></img>
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
<h3>${item.price}</h3>
</div>
<Button onClick={()=>handleAddToCart(item)}>Add To Cart</Button>
</Wrapper>
);
}

export default Item;
</code>```

答:
You could try using useParams:

```<code><Router>
  <Route path="/cart" element={<Cart />} />
</Router>
</code>```

then in the Cart component:

```<code>import { useParams } from "react-router-dom"

const Cart = (props) => {
  const { id } = useParams()
}
export default Cart
</code>```

If you're having issues navigating to the component try changing:

```<code><Route path="/Cart" element={<Cart cartItems={cartItems} />}> </Route>
</code>```

to:

```<code><Route path="/cart" element={<Cart cartItems={cartItems} />}/>
</code>```

Body:
<Router>
  <Route path="/Cart" element={<Cart data />}>
  </Route>
</Router>

Here I want to pass the element Cart ,but the Cart has props of the following type

export type CartItemtype = {
  id: number;
  category: string;
  description: string;
  image: string;
  price: string;
  title: string;
  amount: number;
}

data is an array of type CartItemtype[]
I am using react-router-dom V6

Below is App.tsx and Item.tsx file

import React from 'react';
import Page from './Page';
import Todo from './models/todo';
import FormSubmission from './FormSubmission';
import Registration from './Registration';
import { useState } from 'react';
import { Type } from 'typescript';
import { useQuery } from 'react-query';
import { Wrapper, StyledButton } from './App.styles';
import Item from './Item/Item';
import Grid from '@material-ui/core/Grid';
import Drawer from '@material-ui/core/Drawer';
import Badge from '@material-ui/core/Badge';
import Button from 'react-bootstrap/Button';
import Cart from './Cart/Cart';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import { useNavigate } from "react-router-dom";

export type CartItemtype = {
  id: number;
  category: string;
  description: string;
  image: string;
  price: string;
  title: string;
  amount: number;
}

const getProducts = async (): Promise<CartItemtype[]> => {
  return await (await fetch("https://fakestoreapi.com/products")).json();
}

function App() {
  const [cartOpen, setCartOpen] = useState(false);
  const [cartItems, setCartItems] = useState([] as CartItemtype[]);
  const { data, isLoading, error } = useQuery<CartItemtype[]>('products', getProducts);
  //useQuery is a react hook
  console.log(data);
  const getTotalItems = (items: CartItemtype[]) => null;

  const navigate = useNavigate();
  const handleClick = () => {
    navigate("/Cart");
  }
  if (error) return
Somethimg went wrong
;
  <Router>
    <Route path="/Cart" element={<Cart data />}>
    </Route>
  </Router>
  return (
    <Wrapper>
      <Button onClick={handleClick}>Navigate To Cart</Button>
      <Grid container spacing={3}>
        {data?.map((item, key) => {
          return (

            <Grid item key={item.id} xs={12} sm={4}>
              <Item item={item} />
            </Grid>

          )
        })
        }
      </Grid>
    </Wrapper>
  );
};
export default App;

import {CartItemtype} from '../App';
import {Wrapper} from './Item.styles';
import Button from 'react-bootstrap/Button';

type itemProps={
    item:CartItemtype;
    // handleAddToCart:(clickedItem:CartItemtype)=>void;
}
const handleAddToCart = (clickedItem: CartItemtype) => null;

const Item:React.FC<itemProps>=({item})=>
{
return(
<Wrapper>

{item.title}

{item.description}

${item.price}

<Button onClick={()=>handleAddToCart(item)}>Add To Cart</Button>
</Wrapper>
);
}

export default Item;

Body:
You could try using useParams:

<Router>
  <Route path="/cart" element={<Cart />} />
</Router>

then in the Cart component:

import { useParams } from "react-router-dom"

const Cart = (props) => {
  const { id } = useParams()
}
export default Cart

If you're having issues navigating to the component try changing:

<Route path="/Cart" element={<Cart cartItems={cartItems} />}> </Route>

to:

<Route path="/cart" element={<Cart cartItems={cartItems} />}/>


问:
how to download large files without memory issues in java
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

```<code>String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();
</code>```

答:
First you can remove the (in != null) from your while statement, it's unnecessary.  Second, try removing the BufferedInputStream and just do:</p>

```<code>FileInputStream in = new FileInputStream(file);
</code>```

Body:
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();

Body:
First you can remove the (in != null) from your while statement, it's unnecessary.  Second, try removing the BufferedInputStream and just do:

FileInputStream in = new FileInputStream(file);


问:
How can I access Istio Authorization details in my target Service(For e.g. Flask code)
For Example I have enabled the mTLS in my istio service in STRICT mode. and I have authorization policy that have kind of source.principals rule check.

Now I want to access these rules details like source.principals and source.namespace after request is authenticated and authorized so that I can do more business login in my flask(python) service.

My python code looks like this:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/mutate-hook", methods=['POST'])
def mutate():
    source = request.headers.get('source')
    # I am expacting source to the source from this: https://istio-releases.github.io/v0.1/docs/reference/config/mixer/attribute-vocabulary.html
    print(source)
    request_json = request.get_json()
    # I am expacting source to the source from this: https://istio-releases.github.io/v0.1/docs/reference/config/mixer/attribute-vocabulary.html
    request_source = request_json.get('source')
    print(request_source["principal"], request_source['namespace'])

</code>```

答:
I solved this using a different approach.

So each pod in k8s has access to its service account token and we can use TokeReview api to validate this token and that tokenreview api return the service account with its namespace.
So when a service talks to another service, we pass this serviceaccount token from Service A to Service B and then Service B validates this token using TokenReview API. and gets the principal (which is service account name) and namespace.

Body:
For Example I have enabled the mTLS in my istio service in STRICT mode. and I have authorization policy that have kind of source.principals rule check.

Now I want to access these rules details like source.principals and source.namespace after request is authenticated and authorized so that I can do more business login in my flask(python) service.

My python code looks like this:

from flask import Flask
app = Flask(__name__)

@app.route("/mutate-hook", methods=['POST'])
def mutate():
    source = request.headers.get('source')
    # I am expacting source to the source from this: https://istio-releases.github.io/v0.1/docs/reference/config/mixer/attribute-vocabulary.html
    print(source)
    request_json = request.get_json()
    # I am expacting source to the source from this: https://istio-releases.github.io/v0.1/docs/reference/config/mixer/attribute-vocabulary.html
    request_source = request_json.get('source')
    print(request_source["principal"], request_source['namespace'])


问:
What to do with an element if i can't assign it to any group in Karnaugh map?

See in the image i got a 1(min term) at the bottom right corner which I can't assign it to any groups . What should i do ? Should i leave this 1 as it is and do other simplification or i should count it as single group ?

答:
It would be: AB'CD' as those are the constant variables.

The larger the group, the less variables (ABCD) you will need to represent it.

It is considered an essential prime implicant (meaning that it is required to be represented as it can only be grouped in a single way) - therefore it has it's own grouping of 1 (in this case). Groupings work for powers of 2, so a grouping of a single element is the same as 2^0. You can have groupings of: 1,2,4,8, etc. This will be more relevant once you work on 5-variable or 6-variable K-Maps


问:
How to index a Matplotlib subplot
Im trying to plot two piecharts together. I have been reading the Matplotlib documentation https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_demo2.htmland cannot see what im doing wrong. I'm getting an indexing error in line 13 (patches = axs[1,1].pie...)

The code worked until I started using the axs[1,1] etc and tried to have the subplots.

Code

```<code>import matplotlib.pyplot as plt
from matplotlib import rcParams

print('\n'*10)

# Make figure and axes
fig, axs = plt.subplots(1,2)

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
#patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,1].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)

# Pie chart 2
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,2].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,2].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)

plt.show()
</code>```

Traceback

```<code>Traceback (most recent call last):
  File "/Users/.../Desktop/WORK/time_1.py", line 13, in <module>
    patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
</code>```

答:
The problem is that Matplotlib squeezes the axs array into a 1D shape if there is only one row or only one column of subplots. Fortunately, this inconsistent bahaviour can be disabled by passing the squeeze argument:

```<code>fig, axs = plt.subplots(1, 2, squeeze=False)
</code>```

And then you can just normally index into it with axs[0,0] and axs[0,1], like you would if there were multiple rows of subplots.

I would recommend to always pass squeeze=False, so that the behaviour is the same regardless of how many rows there are and automated plotting scripts don't need to come up with special cases for single-row plots (or else risk cryptic errors if somebody later on wants to generate a plot that happens to have only a single row).

Title: How to index a Matplotlib subplot

Body:
Im trying to plot two piecharts together. I have been reading the Matplotlib documentation https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_demo2.htmland cannot see what im doing wrong. I'm getting an indexing error in line 13 (patches = axs[1,1].pie...)

The code worked until I started using the axs[1,1] etc and tried to have the subplots.

Code

import matplotlib.pyplot as plt
from matplotlib import rcParams

print('\n'*10)

# Make figure and axes
fig, axs = plt.subplots(1,2)

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
#patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,1].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)

# Pie chart 2
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,2].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,2].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)

plt.show()

Traceback

Traceback (most recent call last):
  File "/Users/.../Desktop/WORK/time_1.py", line 13, in <module>
    patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

Body:
The problem is that Matplotlib squeezes the axs array into a 1D shape if there is only one row or only one column of subplots. Fortunately, this inconsistent bahaviour can be disabled by passing the squeeze argument:

fig, axs = plt.subplots(1, 2, squeeze=False)

And then you can just normally index into it with axs[0,0] and axs[0,1], like you would if there were multiple rows of subplots.

I would recommend to always pass squeeze=False, so that the behaviour is the same regardless of how many rows there are and automated plotting scripts don't need to come up with special cases for single-row plots (or else risk cryptic errors if somebody later on wants to generate a plot that happens to have only a single row).


问:
Flutter how to show the same bottom navigation bar to a sub screen
I have bottom navigation buttons, for three screens, but one of the screens has a subscreen, in this case the Profile Screen has a EditProfileScreen as a subscreen, when i navigate.push to the EditProfileScreen the bottom navigation bar dissapears. i want to have the same bottom navigation bar that i had in ProfileScreen to the EditProfileScreen. I saw some tutorials on it of people fixing this but i couldnt implement it on my project. If someone could show how this is done and implement it i would highly appreciate it.</p>
```<code>int pageIndex = 0;

List<Widget> pageList = <Widget>[
  const IsUserWorking(),
  const ReportsScreen(),
  const ProfileScreen(),
];

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        var isWorking = snapshot.data?.getString('isWorking');
        if (isWorking != null) {
          return const StopWorkingScreen();
        }
        return const WorkingScreen();
      },
    );
  }
}

class ScreensWithBottomNavigation extends StatefulWidget {
  const ScreensWithBottomNavigation({Key? key}) : super(key: key);

  @override
  State<ScreensWithBottomNavigation> createState() =>
      _ScreensWithBottomNavigation();
}

class _ScreensWithBottomNavigation extends State<ScreensWithBottomNavigation> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageList[pageIndex],
      bottomNavigationBar: ClipRRect(
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(30.0),
          topRight: Radius.circular(30.0),
        ),
        child: BottomNavigationBar(
          unselectedItemColor: Colors.white,
          currentIndex: pageIndex,
          onTap: (value) {
            setState(() {
              pageIndex = value;
            });
          },
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.assignment_ind_outlined),
              label: 'Working',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.assessment_outlined),
              label: 'Reports',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school_outlined),
              label: 'Profile',
            ),
          ],
          backgroundColor: Colors.blue.shade100,
          // currentIndex: _selectedIndex,
          // selectedItemColor: Colors.amber[800],
          // onTap: _onItemTapped,
        ),
      ),
    );
  }
}

</code>```

答: Take a look at persistent_bottom_nav_bar, I think it's exactly what you're looking for.</p>

Body:
I have bottom navigation buttons, for three screens, but one of the screens has a subscreen, in this case the Profile Screen has a EditProfileScreen as a subscreen, when i navigate.push to the EditProfileScreen the bottom navigation bar dissapears. i want to have the same bottom navigation bar that i had in ProfileScreen to the EditProfileScreen. I saw some tutorials on it of people fixing this but i couldnt implement it on my project. If someone could show how this is done and implement it i would highly appreciate it.

int pageIndex = 0;

List<Widget> pageList = <Widget>[
  const IsUserWorking(),
  const ReportsScreen(),
  const ProfileScreen(),
];

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        var isWorking = snapshot.data?.getString('isWorking');
        if (isWorking != null) {
          return const StopWorkingScreen();
        }
        return const WorkingScreen();
      },
    );
  }
}

class ScreensWithBottomNavigation extends StatefulWidget {
  const ScreensWithBottomNavigation({Key? key}) : super(key: key);

  @override
  State<ScreensWithBottomNavigation> createState() =>
      _ScreensWithBottomNavigation();
}

class _ScreensWithBottomNavigation extends State<ScreensWithBottomNavigation> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageList[pageIndex],
      bottomNavigationBar: ClipRRect(
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(30.0),
          topRight: Radius.circular(30.0),
        ),
        child: BottomNavigationBar(
          unselectedItemColor: Colors.white,
          currentIndex: pageIndex,
          onTap: (value) {
            setState(() {
              pageIndex = value;
            });
          },
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.assignment_ind_outlined),
              label: 'Working',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.assessment_outlined),
              label: 'Reports',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school_outlined),
              label: 'Profile',
            ),
          ],
          backgroundColor: Colors.blue.shade100,
          // currentIndex: _selectedIndex,
          // selectedItemColor: Colors.amber[800],
          // onTap: _onItemTapped,
        ),
      ),
    );
  }
}


问:
react-router-dom exact url to outer route
Inside the Posts.js component which is in the "/home" route, I want a link to user profile so I use this code:

```<code><Link to={`profile/${users.username}`}>
</code>```

I want this link to go to "/profile/:username", but instead it goes to "/home/profile/:username".

How to fix that?

答:
Seems you are using react-router-dom v6, which can use relative links as well as absolute links. The difference between the two is a leading "/" character. Paths starting with "/" are absolute paths, and without will navigate relative to the current location. For example, if the current path is "/home" and you push a navigation to "profile/123" then the result is that you navigate to "/home/profile/123".

You can read a bit more about Relative Links. Relative links are useful when building nested routes/links/UI.

Use an absolute path.

```<code><Link to={`/profile/${users.username}`}>
</code>```

Body:
Inside the Posts.js component which is in the "/home" route, I want a link to user profile so I use this code:

<Link to={`profile/${users.username}`}>

I want this link to go to "/profile/:username", but instead it goes to "/home/profile/:username".

How to fix that?

Body:
Seems you are using react-router-dom v6, which can use relative links as well as absolute links. The difference between the two is a leading "/" character. Paths starting with "/" are absolute paths, and without will navigate relative to the current location. For example, if the current path is "/home" and you push a navigation to "profile/123" then the result is that you navigate to "/home/profile/123".

You can read a bit more about Relative Links. Relative links are useful when building nested routes/links/UI.

Use an absolute path.

<Link to={`/profile/${users.username}`}>


问:
I want to reuse a library of WPF UserControls - How can I set the styles?
I have created a WPF desktop application using the MVVM pattern. As part of this effort, I have created a namespace with many dialog windows, dialogViewModels and dialogViews. The dialog windows typically display one of the dialogViews, depending on the assigned dialogViewModel.

I now want to convert the Views and ViewModels in this namespace to a separate library, so that I may reuse the dialogs in other applications. However, I have two questions:

How can I set the styles on my usercontrols so that, when the library is used in a different application, it uses the styles from that application.

Will I able to override datatemplate assignments made in the library controls when reusing the library?

Some code to illustrate my point:

```<code><Window x:Class="FeehandlerMain.Dialogs.OKDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding Path=DialogTitle}"
        Height="200" Width="400" ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True" WindowStartupLocation="CenterOwner" SizeToContent="Height">

    <Window.Resources>
        <DataTemplate DataType="{x:Type dialogs:MessageBoxDialogViewModel}">
            <dialogs:MessageBoxDialogView />
        </DataTemplate>
    </Window.Resources>

    <Border Style="{StaticResource StandardBorderStyle}" >
        <Grid Margin="5">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <ContentControl Content="{Binding}"
                            Grid.Column="0" Grid.Row="0"  />

            <StackPanel Orientation="Horizontal"
                        Grid.Column="0" Grid.Row="1">
                <Button Content="OK" IsDefault="True" IsCancel="True"
                        Style="{StaticResource StandardButtonStyle}"/>
            </StackPanel>
        </Grid>
    </Border>
</Window>
</code>```

Question 1 is regarding the use of StandardBorderStyle and StandardButtonStyle. These styles are currently defined in my App.xaml file under <Application.Resources>. If I put the dialogs in a library, and I reference that library from a new application, how can I get the dialog to use StandardBorderStyle and StandardButtonStyle from the new application, so that each application can define it's own visual style?

Question 2 is regarding the DataTemplates. These templates are used to select the appropriate view for the Dialog (inserted as a ContentControl element in the example above), based on the type of ViewModel assigned as the Dialog's DataContext. Will I be able to override the above DataTemplate when reusing the library, in a scenario where I want to use a different View than MessageBoxDialogView for MessageBoxDialogViewModel?

Oh and I know it's two questions, but you will still just get reputation for one answer, sorry! ;-)

答:
For the styles, the best way I can think of is to define a DependencyProperty for each of them in your own UserControl. So you'll have, for example, a DependencyProperty called BorderStyle which you set the default to the style you define internaly in your control library, while still allowing the client code using your control to override this style the way they want.

For the DataTemplate, you wouldn't really have to do anything, since the user of your library can define a another DataTemplate (for example for MessageBoxDialogViewModel) in his code, and that would take precedence and be used instead of the default one.

Hope this helps :)

Body:
I have created a WPF desktop application using the MVVM pattern. As part of this effort, I have created a namespace with many dialog windows, dialogViewModels and dialogViews. The dialog windows typically display one of the dialogViews, depending on the assigned dialogViewModel.

I now want to convert the Views and ViewModels in this namespace to a separate library, so that I may reuse the dialogs in other applications. However, I have two questions:

How can I set the styles on my usercontrols so that, when the library is used in a different application, it uses the styles from that application.

Will I able to override datatemplate assignments made in the library controls when reusing the library?

Some code to illustrate my point:

<Window x:Class="FeehandlerMain.Dialogs.OKDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding Path=DialogTitle}"
        Height="200" Width="400" ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True" WindowStartupLocation="CenterOwner" SizeToContent="Height">

    <Window.Resources>
        <DataTemplate DataType="{x:Type dialogs:MessageBoxDialogViewModel}">
            <dialogs:MessageBoxDialogView />
        </DataTemplate>
    </Window.Resources>

    <Border Style="{StaticResource StandardBorderStyle}" >
        <Grid Margin="5">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <ContentControl Content="{Binding}"
                            Grid.Column="0" Grid.Row="0"  />

            <StackPanel Orientation="Horizontal"
                        Grid.Column="0" Grid.Row="1">
                <Button Content="OK" IsDefault="True" IsCancel="True"
                        Style="{StaticResource StandardButtonStyle}"/>
            </StackPanel>
        </Grid>
    </Border>
</Window>

Question 1 is regarding the use of StandardBorderStyle and StandardButtonStyle. These styles are currently defined in my App.xaml file under <Application.Resources>. If I put the dialogs in a library, and I reference that library from a new application, how can I get the dialog to use StandardBorderStyle and StandardButtonStyle from the new application, so that each application can define it's own visual style?

Question 2 is regarding the DataTemplates. These templates are used to select the appropriate view for the Dialog (inserted as a ContentControl element in the example above), based on the type of ViewModel assigned as the Dialog's DataContext. Will I be able to override the above DataTemplate when reusing the library, in a scenario where I want to use a different View than MessageBoxDialogView for MessageBoxDialogViewModel?

Oh and I know it's two questions, but you will still just get reputation for one answer, sorry! ;-)


问:
Python rock paper scissors score counter
I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.

I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!

here is what I get when I run the program:

```<code>Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .
</code>```

```<code>#import the library function "random" so that you can use it for computer
#choice
import random

#define main
def main():
    #assign win, lose, and tie to zero for tallying
    win = 0
    lose = 0
    tie = 0

    #control loop with 'y' variable
    play_again = 'y'

    #start the game
    while play_again == 'y':
        #make a welcome message and give directions
        print('Prepare to battle in a game of paper, rock, scissors!')
        print('Please input the correct number according')
        print('to the object you want to choose.')

        #Get the player and computers choices and
        #assign them to variables
        computer_choice = get_computer_choice()
        player_choice = get_player_choice()

        #print choices
        print('Computer chose', computer_choice, '.')
        print('You chose', player_choice, '.')

        #determine who won
        winner_result(computer_choice, player_choice)

        #ask the user if they want to play again
        play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")

    #print results
    print('Your total wins are', win, '.')
    print('Your total losses are', lose, '.')
    print('Your total ties are', tie, '.')

#define computer choice
def get_computer_choice():
    #use imported random function from library
    choice = random.randint(1,3)

    #assign what the computer chose to rock, paper, or scissors
    if choice == 1:
        choice = 'ROCK'
    elif choice == 2:
        choice = 'PAPER'
    else:
        choice = 'SCISSORS'

    #return value
    return choice

#define player choice
def get_player_choice():
    #assign input to variable by prompting user
    choice = int(input("Select rock(1), paper(2), or scissors(3): "))

    #Detect invalid entry
    while choice != 1 and choice != 2 and choice != 3:
        print('The valid numbers are rock(type in 1), paper(type in 2),')
        print('or scissors(type in 3).')
        choice = int(input('Enter a valid number please: '))

    #assign what the player chose based on entry
    if choice == 1:
        choice = 'ROCK'
    elif choice == 2:
        choice = 'PAPER'
    else:
        choice = 'SCISSORS'

    #return value
    return choice

#determine the winner from the variables
def winner_result(computer_choice, player_choice):
    #if its a tie, add 1 to tie variable and display message
    if computer_choice == player_choice:
        result = 'tie'
        print("It's a tie!")

    #if its a win, add to win tally and display message
    elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
        result = 'win'
        print('ROCK crushes SCISSORS! You win!')
    elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
        result = 'win'
        print('SCISSORS cut PAPER! You win!')
    elif computer_choice == 'ROCK' and player_choice == 'PAPER':
        result = 'win'
        print('PAPER covers ROCK! You win!')

    #if it does not match any of the win criteria then add 1 to lose and
    #display lose message
    else:
        result = 'lose'
        print('You lose!')

def result(winner_result,player_choice, computer_choice):

    # accumulate the appropriate winner of game total
    if result == 'win':
        win += 1
    elif result == 'lose':
        lose += 1
    else:
        tie += 1
    return result

main()
</code>```

答:
This works (kinda)
there are many issues with the code at the top of the page.
Firstly, Scoring doesn't work.
Secondly, nothing is indented meaning that nothing inside of the other def functions will work.
Thirdly, The other def functions are referred to in the first def main statement which causes Python to show an invalid syntax due to Python not knowing the other functions as they were referred to before they were introduced to python.</p>

Body:
I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.

I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!

here is what I get when I run the program:

Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .

#import the library function "random" so that you can use it for computer
#choice
import random

#define main
def main():
    #assign win, lose, and tie to zero for tallying
    win = 0
    lose = 0
    tie = 0

    #control loop with 'y' variable
    play_again = 'y'

    #start the game
    while play_again == 'y':
        #make a welcome message and give directions
        print('Prepare to battle in a game of paper, rock, scissors!')
        print('Please input the correct number according')
        print('to the object you want to choose.')

        #Get the player and computers choices and
        #assign them to variables
        computer_choice = get_computer_choice()
        player_choice = get_player_choice()

        #print choices
        print('Computer chose', computer_choice, '.')
        print('You chose', player_choice, '.')

        #determine who won
        winner_result(computer_choice, player_choice)

        #ask the user if they want to play again
        play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")

    #print results
    print('Your total wins are', win, '.')
    print('Your total losses are', lose, '.')
    print('Your total ties are', tie, '.')

#define computer choice
def get_computer_choice():
    #use imported random function from library
    choice = random.randint(1,3)

    #assign what the computer chose to rock, paper, or scissors
    if choice == 1:
        choice = 'ROCK'
    elif choice == 2:
        choice = 'PAPER'
    else:
        choice = 'SCISSORS'

    #return value
    return choice

#define player choice
def get_player_choice():
    #assign input to variable by prompting user
    choice = int(input("Select rock(1), paper(2), or scissors(3): "))

    #Detect invalid entry
    while choice != 1 and choice != 2 and choice != 3:
        print('The valid numbers are rock(type in 1), paper(type in 2),')
        print('or scissors(type in 3).')
        choice = int(input('Enter a valid number please: '))

    #assign what the player chose based on entry
    if choice == 1:
        choice = 'ROCK'
    elif choice == 2:
        choice = 'PAPER'
    else:
        choice = 'SCISSORS'

    #return value
    return choice

#determine the winner from the variables
def winner_result(computer_choice, player_choice):
    #if its a tie, add 1 to tie variable and display message
    if computer_choice == player_choice:
        result = 'tie'
        print("It's a tie!")

    #if its a win, add to win tally and display message
    elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
        result = 'win'
        print('ROCK crushes SCISSORS! You win!')
    elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
        result = 'win'
        print('SCISSORS cut PAPER! You win!')
    elif computer_choice == 'ROCK' and player_choice == 'PAPER':
        result = 'win'
        print('PAPER covers ROCK! You win!')

    #if it does not match any of the win criteria then add 1 to lose and
    #display lose message
    else:
        result = 'lose'
        print('You lose!')

def result(winner_result,player_choice, computer_choice):

    # accumulate the appropriate winner of game total
    if result == 'win':
        win += 1
    elif result == 'lose':
        lose += 1
    else:
        tie += 1
    return result

main()


问:
How do you convert an integer into a date (format YYYY) in R
I have a big data set, filled with dates that are in integer form, and different types of integer form (YYYYMMDD, YYYYMM and YYYY)

I just want to get all of them to YYYY.

I first tried splitting up the data frame into three data frames with the different respective date (integer) forms. And then I tried to change the data form from integer to date.

Below is me splitting up the data and then all the various things i have tried and subsequently commented out.

```<code>Opera_A <- Opera_split$Date_Format_A
Opera_B <- Opera_split$Date_Format_B
Opera_C <- Opera_split$Date_Format_C

lubridate::dmy(Opera_C$Composer_Born)
#as.Date(Opera_C$Composer_Born, "%m/%d/%y")
#Composer_Born_C <- data.frame(Composer_Born)
#Opera_C <- Opera_C %>% mutate(df,dateTime=as.Date(Composer_Born, format = "%Y-%m-%d"))
#Opera_C <- transform(Opera_C,Composer_Born=as.Date(as.character(Integer),"%Y%m%d"))
# Opera_C$Composer_Born <- as.Date(Opera_C$Composer_Born, '%Y-%m-%d')
</code>```

I keep getting Error in Opera_C$Composer_Born : $ operator is invalid for atomic vectors --- do i have to turn these vectors into dfs or can i just convert them directly?

Any help much appreciated --- I'm an R beginner!

Thank you

答:
As suggested by @caldwellst in the comments you can just pull the first 4 characters if they're all in the format you indicated. Then you can use as.Date(format = "%Y) to turn into actual date format and just fill in the M and D portions. Then use lubridate::year() to pull the year info.

library(tidyverse)
library(lubridate)

c(17701216, 177012, 1770) %>%
  as.character() %>%
  str_sub(1, 4) %>%
  as.Date(format = "%Y") %>%
  year()
#> [1] 1770 1770 1770
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
I have a big data set, filled with dates that are in integer form, and different types of integer form (YYYYMMDD, YYYYMM and YYYY)

I just want to get all of them to YYYY.

I first tried splitting up the data frame into three data frames with the different respective date (integer) forms. And then I tried to change the data form from integer to date.

Below is me splitting up the data and then all the various things i have tried and subsequently commented out.

Opera_A <- Opera_split$Date_Format_A
Opera_B <- Opera_split$Date_Format_B
Opera_C <- Opera_split$Date_Format_C

lubridate::dmy(Opera_C$Composer_Born)
#as.Date(Opera_C$Composer_Born, "%m/%d/%y")
#Composer_Born_C <- data.frame(Composer_Born)
#Opera_C <- Opera_C %>% mutate(df,dateTime=as.Date(Composer_Born, format = "%Y-%m-%d"))
#Opera_C <- transform(Opera_C,Composer_Born=as.Date(as.character(Integer),"%Y%m%d"))
# Opera_C$Composer_Born <- as.Date(Opera_C$Composer_Born, '%Y-%m-%d')

I keep getting Error in Opera_C$Composer_Born : $ operator is invalid for atomic vectors --- do i have to turn these vectors into dfs or can i just convert them directly?

Any help much appreciated --- I'm an R beginner!

Thank you

Body:
As suggested by @caldwellst in the comments you can just pull the first 4 characters if they're all in the format you indicated. Then you can use as.Date(format = "%Y) to turn into actual date format and just fill in the M and D portions. Then use lubridate::year() to pull the year info.

library(tidyverse)
library(lubridate)

c(17701216, 177012, 1770) %>%
  as.character() %>%
  str_sub(1, 4) %>%
  as.Date(format = "%Y") %>%
  year()
#> [1] 1770 1770 1770

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
Microsoft.Identity.Web OnTokenValidated event doesn't seem to play nicely with async
I've been struggling with the Func that I attach to OnTokenValidated not doing what it should be.

After lots of trying different things:

```<code>services.Configure<MicrosoftIdentityOptions>(options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += context =>
    {
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
        return Task.CompletedTask;
    };
}
</code>```

works as expected and the claim "Foo" with value "Bar" is added to the identity.

but, as soon as I await a Task within the code and make the func async, the additional claim does not get added to the signed in Identity:

```<code>services.Configure<MicrosoftIdentityOptions>(options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var someValue = await someService.SomeMethod();
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
    };
}
</code>```

does not work. To be clear, it doesn't error, but after the method completes, the additional claim does not exist on the identity...

As far as I can tell, by elimating various things, it's the await which is making it break, yet the definition of OnTokenValidated is:

```<code>Func<TokenValidatedContext,Task> OnTokenValidated
</code>```

So it seems to expect handlers to be async?

Update: 2022-02-07
Taking this even further:

```<code>OnTicketReceived = ctx =>
{
    throw new AuthenticationException("Sorry, you cannot log in");
}
</code>```

causes the login to fail due to the exception being thrown, whereas

```<code>OnTicketReceived = async ctx =>
{
    throw new AuthenticationException("Sorry, you cannot log in");
}
</code>```

does not work - the exception being thrown does not affect the login, the user is logged in correctly despite an exception being thrown. It appears as though the code exection has already moved on as if something somewhere in the stack is not awaiting... yet looking at the code on github I can't find anywhere that an async method in the stack isn't awaited

Update 2022-02-09
Example:
https://github.com/VaticanUK/msal_so_fail_example

I have taken one of the official MS examples (available here: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2) and added the customisation of MicrosoftIdentityOptions in Startup.cs: (https://github.com/VaticanUK/msal_so_fail_example/blob/master/Startup.cs#L40) using the pattern shown in the documentation: https://github.com/AzureAD/microsoft-identity-web/wiki/customization#customization-in-the-startupcs

To run the example, you need to create an app in Azure and set your client ID in appsettings.json.

As-is, the example will work, by which I mean login will fail (since there is no async keyword):

If you add the async keyword, the exception will not prevent login:

答:
I raised the above on the MSAL Github account and after chatting to one of the contributors, the answer is that in the registration of the Options that contains the event handler it needs to be registered as:

```<code>services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
</code>```

rather than:

```<code>services.Configure<MicrosoftIdentityOptions>(options =>
</code>```

so the full registration that works is:

```<code>services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var someValue = await someService.SomeMethod();
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
    };
}
</code>```

At the moment, I don't understand how this fixes the issue, or why not having the authentication scheme as a name for the registration causes it to only work synchronously, but it's fixed my problem so I'll probably try and get to the bottom of it out of intellectual curiosity, but the above fixes the immediate issue!

Body:
I've been struggling with the Func that I attach to OnTokenValidated not doing what it should be.

After lots of trying different things:

services.Configure<MicrosoftIdentityOptions>(options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += context =>
    {
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
        return Task.CompletedTask;
    };
}

works as expected and the claim "Foo" with value "Bar" is added to the identity.

but, as soon as I await a Task within the code and make the func async, the additional claim does not get added to the signed in Identity:

services.Configure<MicrosoftIdentityOptions>(options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var someValue = await someService.SomeMethod();
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
    };
}

does not work. To be clear, it doesn't error, but after the method completes, the additional claim does not exist on the identity...

As far as I can tell, by elimating various things, it's the await which is making it break, yet the definition of OnTokenValidated is:

Func<TokenValidatedContext,Task> OnTokenValidated

So it seems to expect handlers to be async?

Update: 2022-02-07
Taking this even further:

OnTicketReceived = ctx =>
{
    throw new AuthenticationException("Sorry, you cannot log in");
}

causes the login to fail due to the exception being thrown, whereas

OnTicketReceived = async ctx =>
{
    throw new AuthenticationException("Sorry, you cannot log in");
}

does not work - the exception being thrown does not affect the login, the user is logged in correctly despite an exception being thrown. It appears as though the code exection has already moved on as if something somewhere in the stack is not awaiting... yet looking at the code on github I can't find anywhere that an async method in the stack isn't awaited

Update 2022-02-09
Example:
https://github.com/VaticanUK/msal_so_fail_example

I have taken one of the official MS examples (available here: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2) and added the customisation of MicrosoftIdentityOptions in Startup.cs: (https://github.com/VaticanUK/msal_so_fail_example/blob/master/Startup.cs#L40) using the pattern shown in the documentation: https://github.com/AzureAD/microsoft-identity-web/wiki/customization#customization-in-the-startupcs

To run the example, you need to create an app in Azure and set your client ID in appsettings.json.

As-is, the example will work, by which I mean login will fail (since there is no async keyword):

If you add the async keyword, the exception will not prevent login:

Body:
I raised the above on the MSAL Github account and after chatting to one of the contributors, the answer is that in the registration of the Options that contains the event handler it needs to be registered as:

services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>

rather than:

services.Configure<MicrosoftIdentityOptions>(options =>

so the full registration that works is:

services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var someValue = await someService.SomeMethod();
        context.Principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("Foo", "Bar")}));
    };
}

At the moment, I don't understand how this fixes the issue, or why not having the authentication scheme as a name for the registration causes it to only work synchronously, but it's fixed my problem so I'll probably try and get to the bottom of it out of intellectual curiosity, but the above fixes the immediate issue!


问:
How can I add the dots into numpy.ndarray output?
Given two lists of 1s and 0s (1 represents the true label, and 0 represents the false false) of the same length, output a 2darrary of counts, each cell is defined as follows

Top left: Predicted true and actually true (True positive)
Top right: Predicted true but actually false (False positive)
Bottom left: Predicted false but actually true (False negative)
Bottom right: Predicted false and actually false (True negative)

Sample Input

```<code>1 1 0 0
1 0 0 0
</code>```

Sample Output

```<code>[[1., 0.],
[1., 2.]]
</code>```

My code outputs:

```<code>[[1 0]
 [1 2]]
</code>```

Where can I get those dots??? Don't care about commas, i don't know why, but the answer without them is correct.

My code:

```<code>import numpy as np

y_true = [int(x) for x in input().split()]
y_pred =  [int(x) for x in input().split()]
y_true = np.array(list(map(lambda x: 0 if x == 1 else 1, y_true)))
y_pred = np.array(list(map(lambda x: 0 if x == 1 else 1, y_pred)))
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_pred, y_true))
</code>```

答:
The dots there are because those numbers are floating points. You'll need to add .astype(float):

```<code>print(confusion_matrix(y_pred, y_true).astype(float))
</code>```

Body:
Given two lists of 1s and 0s (1 represents the true label, and 0 represents the false false) of the same length, output a 2darrary of counts, each cell is defined as follows

Top left: Predicted true and actually true (True positive)
Top right: Predicted true but actually false (False positive)
Bottom left: Predicted false but actually true (False negative)
Bottom right: Predicted false and actually false (True negative)

Sample Input

1 1 0 0
1 0 0 0

Sample Output

[[1., 0.],
[1., 2.]]

My code outputs:

[[1 0]
 [1 2]]

Where can I get those dots??? Don't care about commas, i don't know why, but the answer without them is correct.

My code:

import numpy as np

y_true = [int(x) for x in input().split()]
y_pred =  [int(x) for x in input().split()]
y_true = np.array(list(map(lambda x: 0 if x == 1 else 1, y_true)))
y_pred = np.array(list(map(lambda x: 0 if x == 1 else 1, y_pred)))
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_pred, y_true))

Body:
The dots there are because those numbers are floating points. You'll need to add .astype(float):

print(confusion_matrix(y_pred, y_true).astype(float))