问:
Can I have an Express middleware that runs after the router but before the route handler?
I want a generic middleware that can take the "req.route.path" value (e.g. "/foo/:id" and not the actual URL value "/foo/123") and return it on a HTTP response header called "X-ROUTE-NAME". The idea is for this route value to be recorded and logged by separate logging/metrics infrastructure and allow "group by" on the route name for other analysis purposes later.

Here's my first attempt:

```<code>app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);
  res.setHeader("X-ROUTE-NAME", req.route.path);
  next();
});
</code>```

It doesn't work because if you put it BEFORE you register routes, it doesn't have any value in req.route.path yet. But if you register it AFTER the routes, you get an exception when you try to set the header if a handler has already sent content on the req.

So yah, the tricky part is figuring out how to snatch the "req.route.path" value AFTER it's set by the router (and saving it to the response as a header), but BEFORE a handler picks it up (since the handler can send content if it wants to and then you wont be able to set headers anymore).

Any ideas?

答:
I found a solution that worked for me:</p>
```<code>// create a test router and handler
const testRouter = express.Router();

testRouter.get('/test/:testId', (req, res) => {
  console.log("HANDLER");
  res.send("{}")
});

// create a function that injects a "beforeHandle" function into a router instance (depends on a private interface though)
function onBeforeHandle(router: IRouter, beforeHandle: (req: Request, res: Response) => void) {
  const methodName = "process_params";
  const routerAny: any = router;
  const oldFn = routerAny[methodName];

  if (!oldFn) {
    throw new Error(`No private '${methodName}' method found on router. This may be an incompatible version of Express.`);
  }

  if (oldFn.length !== 5) {
    throw new Error(`Invalid number of arguments on private '${methodName}' method. This may be an incompatible version of Express.`);
  }

  const newFn = (...args: any[]) => {
    const [, , req, res, handler] = args;

    beforeHandle(req, res);
    return oldFn.apply(routerAny, args as any);
  }
  routerAny[methodName] = newFn;
}

// function to be executed prior to the route handler
function setRouteNameHeader(req: Request, res: Response) {
  const routeHeaderName = "Q-ROUTE-NAME";
  if (!req.route) {
    console.log(`Can't add '${routeHeaderName}' header as 'req.route' is not set.`);
  } else {
    if (!res.headersSent) {
      res.setHeader(routeHeaderName, req.route.path);
    } else {
      console.log(`Can't add '${routeHeaderName} ${req.route.path}' header as headers were already sent.`);
    }
  }
}

// actually inject the function
onBeforeHandle(testRouter, setRouteNameHeader);
</code>```

Body:
I want a generic middleware that can take the "req.route.path" value (e.g. "/foo/:id" and not the actual URL value "/foo/123") and return it on a HTTP response header called "X-ROUTE-NAME". The idea is for this route value to be recorded and logged by separate logging/metrics infrastructure and allow "group by" on the route name for other analysis purposes later.

Here's my first attempt:

app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);
  res.setHeader("X-ROUTE-NAME", req.route.path);
  next();
});

It doesn't work because if you put it BEFORE you register routes, it doesn't have any value in req.route.path yet. But if you register it AFTER the routes, you get an exception when you try to set the header if a handler has already sent content on the req.

So yah, the tricky part is figuring out how to snatch the "req.route.path" value AFTER it's set by the router (and saving it to the response as a header), but BEFORE a handler picks it up (since the handler can send content if it wants to and then you wont be able to set headers anymore).

Any ideas?

Body:
I found a solution that worked for me:

// create a test router and handler
const testRouter = express.Router();

testRouter.get('/test/:testId', (req, res) => {
  console.log("HANDLER");
  res.send("{}")
});

// create a function that injects a "beforeHandle" function into a router instance (depends on a private interface though)
function onBeforeHandle(router: IRouter, beforeHandle: (req: Request, res: Response) => void) {
  const methodName = "process_params";
  const routerAny: any = router;
  const oldFn = routerAny[methodName];

  if (!oldFn) {
    throw new Error(`No private '${methodName}' method found on router. This may be an incompatible version of Express.`);
  }

  if (oldFn.length !== 5) {
    throw new Error(`Invalid number of arguments on private '${methodName}' method. This may be an incompatible version of Express.`);
  }

  const newFn = (...args: any[]) => {
    const [, , req, res, handler] = args;

    beforeHandle(req, res);
    return oldFn.apply(routerAny, args as any);
  }
  routerAny[methodName] = newFn;
}

// function to be executed prior to the route handler
function setRouteNameHeader(req: Request, res: Response) {
  const routeHeaderName = "Q-ROUTE-NAME";
  if (!req.route) {
    console.log(`Can't add '${routeHeaderName}' header as 'req.route' is not set.`);
  } else {
    if (!res.headersSent) {
      res.setHeader(routeHeaderName, req.route.path);
    } else {
      console.log(`Can't add '${routeHeaderName} ${req.route.path}' header as headers were already sent.`);
    }
  }
}

// actually inject the function
onBeforeHandle(testRouter, setRouteNameHeader);


来源: stackexchange

问:
How do I force intercept on a python linear regression plot?
How do I force the line and equation through 0 on this dataframe? I only know how to make a line that is the best fit and equation to match.Below is the code of the best fit line without force intercept through 0. Any help getting forced intercept is appreciated!

```<code>import seaborn as sns
import scipy as sp
r, p = sp.stats.pearsonr(x=df['mass(mg)'], y=df['Abs'])
sns.regplot(x=df['mass(mg)'],y=df['Abs']).set(Title='biuret standard plot')

def equation(x,y):
    x_mean = x.mean()
    y_mean = y.mean()

    B1_num = ((x - x_mean) * (y - y_mean)).sum()
    B1_den = ((x - x_mean)**2).sum()
    B1 = B1_num / B1_den
    B0 = y_mean - (B1*x_mean)

    reg_line = 'y = {} + {}β'.format(B0, round(B1, 3))

    return (B0, B1, reg_line)
equation(df['mass(mg)'],df['Abs'])
</code>```

答:
sns.regplot has a parameter truncate= which default to True and limits the line to the given data.  With truncate=False the line is extended until the border.  You can set the xlim before calling sns.regplot to a suitable range.

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
plt.xlim(-10, 80)
sns.regplot(data=tips, x='total_bill', y='tip', truncate=False, color='turquoise')
plt.axvline(0, color='gray', ls='--')
plt.show()
```
<p><img src="https://i.stack.imgur.com/lv8Hl.png" alt="sns.regplot extended till the borders" /></p>
<p>If you want to extend till <code>x=0</code> and still limit the right to the data limit, you can set the <code>xlim</code> both before and after the <code>regplot</code>:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
plt.xlim(0, tips['total_bill'].max())
sns.regplot(data=tips, x='total_bill', y='tip', truncate=False, color='coral')
plt.axvline(0, color='gray', ls='--')
plt.xlim(-5, tips['total_bill'].max() + 5)
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I force the line and equation through 0 on this dataframe? I only know how to make a line that is the best fit and equation to match.Below is the code of the best fit line without force intercept through 0. Any help getting forced intercept is appreciated!

import seaborn as sns
import scipy as sp
r, p = sp.stats.pearsonr(x=df['mass(mg)'], y=df['Abs'])
sns.regplot(x=df['mass(mg)'],y=df['Abs']).set(Title='biuret standard plot')

def equation(x,y):
    x_mean = x.mean()
    y_mean = y.mean()

    B1_num = ((x - x_mean) * (y - y_mean)).sum()
    B1_den = ((x - x_mean)**2).sum()
    B1 = B1_num / B1_den
    B0 = y_mean - (B1*x_mean)

    reg_line = 'y = {} + {}β'.format(B0, round(B1, 3))

    return (B0, B1, reg_line)
equation(df['mass(mg)'],df['Abs'])

Body:
sns.regplot has a parameter truncate= which default to True and limits the line to the given data.  With truncate=False the line is extended until the border.  You can set the xlim before calling sns.regplot to a suitable range.

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
plt.xlim(-10, 80)
sns.regplot(data=tips, x='total_bill', y='tip', truncate=False, color='turquoise')
plt.axvline(0, color='gray', ls='--')
plt.show()

If you want to extend till x=0 and still limit the right to the data limit, you can set the xlim both before and after the regplot:

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset('tips')
plt.xlim(0, tips['total_bill'].max())
sns.regplot(data=tips, x='total_bill', y='tip', truncate=False, color='coral')
plt.axvline(0, color='gray', ls='--')
plt.xlim(-5, tips['total_bill'].max() + 5)
plt.show()


问:
Is this a valid solution to the palindrome problem?
Is my solution down below valid or am I relying too much on built in functions?
Just to give some context, suppose this was an interview question or something of similar magnitude.</p>
```<code>    public static boolean palindrome(String s){
    char[] arr = new char[s.length()];
    for (int i = 0; i < s.length(); i++) {
        arr[i] = s.charAt(s.length() - 1 - i);
    }

    return s.compareTo(String.valueOf(arr)) == 0;
}
</code>```

答:
I don't claim this to be most optimal, but I will share it with you as I think it might be better than your answer.

If you think of a String as an array of characters, what if you create two pointers, one that points to the head and one that points to the tail and do a character-by-character comparison until the pointer indexes are the same or the tail pointer is lower than the head? This is how that looks in code:

```<code>import java.util.List;

public class PalindromeDemo {
    public static void main(String[] args) {
        List<String> inputs = List.of("Otto", "Hello", "Delia saw I was ailed");

        for (String s : inputs) {
            System.out.println(s + " is palindrome? " + isPalindrome(s));
        }
    }

    public static boolean isPalindrome(String s) {

        int headPtr = 0;
        int tailPtr = s.length() - 1;
        char[] chars = s.toLowerCase().toCharArray();

        while (headPtr < tailPtr) {
            if (chars[headPtr] != chars[tailPtr]) {
                return false;
            }
            headPtr++;
            tailPtr--;
        }
        return true;
    }
}
</code>```

You may have to ask if the solution need to be case-sensitive. My solution is not. Most times when I have seen this question, the person asking is interested in a case-insensitive solution. That's why I called toLowerCase(). Also (not that it matters that much), this solution doesn't reverse the string. It simply walks two pointers and compare the characters each one is pointing to. If a mismatch is encounter, I break immediately. That's why I think this solution is a bit more effective. I also don't need to use a comparator class.

Body:
Is my solution down below valid or am I relying too much on built in functions?
Just to give some context, suppose this was an interview question or something of similar magnitude.

    public static boolean palindrome(String s){
    char[] arr = new char[s.length()];
    for (int i = 0; i < s.length(); i++) {
        arr[i] = s.charAt(s.length() - 1 - i);
    }

    return s.compareTo(String.valueOf(arr)) == 0;
}

Body:
I don't claim this to be most optimal, but I will share it with you as I think it might be better than your answer.

If you think of a String as an array of characters, what if you create two pointers, one that points to the head and one that points to the tail and do a character-by-character comparison until the pointer indexes are the same or the tail pointer is lower than the head? This is how that looks in code:

import java.util.List;

public class PalindromeDemo {
    public static void main(String[] args) {
        List<String> inputs = List.of("Otto", "Hello", "Delia saw I was ailed");

        for (String s : inputs) {
            System.out.println(s + " is palindrome? " + isPalindrome(s));
        }
    }

    public static boolean isPalindrome(String s) {

        int headPtr = 0;
        int tailPtr = s.length() - 1;
        char[] chars = s.toLowerCase().toCharArray();

        while (headPtr < tailPtr) {
            if (chars[headPtr] != chars[tailPtr]) {
                return false;
            }
            headPtr++;
            tailPtr--;
        }
        return true;
    }
}

You may have to ask if the solution need to be case-sensitive. My solution is not. Most times when I have seen this question, the person asking is interested in a case-insensitive solution. That's why I called toLowerCase(). Also (not that it matters that much), this solution doesn't reverse the string. It simply walks two pointers and compare the characters each one is pointing to. If a mismatch is encounter, I break immediately. That's why I think this solution is a bit more effective. I also don't need to use a comparator class.


问:
MongoDB: aggregation $lookup between ObjectIds returning an empty array
I'm trying to perform an aggregation using $lookup between two fields of type ObjectId. I've already checked my data and it should be returning something. Also, the schemas indeed define the fields as ObjectId, so if I am not mistaken I should not need to convert the data type as I've seen in some posts. Here's my query:

```<code>db.workerlocationcontexts.aggregate([
    {
        $lookup: {
            from: "LocationSensors",
            localField: "sensor",
            foreignField: "_id",
            as: "test"
        }
    }
])
</code>```

Here are my collections/sample data:

WorkerLocationContexts

```<code>{
  "_id":{"$oid":"615676c885ccad55a493503b"},
  "updatedAt":{"$date":"2021-10-01T02:47:36.207Z"},
  "createdAt":{"$date":"2021-10-01T02:47:36.207Z"},
  "sensor":{"$oid":"6181e5f83fca98374cf901fd"},
  "worker":{"$oid":"6153dcfb58ad722c747eb42d"},
  "__v":0
}
</code>```

LocationSensor

```<code>{
  "_id":{"$oid":"6181e5f83fca98374cf901fd"},
  "name":"Location Sensor 1",
  "description":"Location sensor for Location 2",
  "location": "$oid":"6181df3b3fca98374cf901fb"},
  "trackerType":"RFID",
  "sensorType":"ENVIRONMENT",
  "type":"LOCATION",
  "__v":0
}
</code>```

The result I'm getting are all my WorkerLocationContexts, but the field "test" returns as an empty array.

Can someone help me?

Thanks in advance!

答:
from field into $lookup seems to be case sensitive so it is a common problem the collection name typed in that field.

One common problem is not add the final "s" while using mongoose. Os, as in this case, the use of capital letters, yo using from: locationsensors should works like this example

The from field has to be the same as the collection name, otherwise Mongo can't find the desired collection.

Body:
I'm trying to perform an aggregation using $lookup between two fields of type ObjectId. I've already checked my data and it should be returning something. Also, the schemas indeed define the fields as ObjectId, so if I am not mistaken I should not need to convert the data type as I've seen in some posts. Here's my query:

db.workerlocationcontexts.aggregate([
    {
        $lookup: {
            from: "LocationSensors",
            localField: "sensor",
            foreignField: "_id",
            as: "test"
        }
    }
])

Here are my collections/sample data:

WorkerLocationContexts

{
  "_id":{"$oid":"615676c885ccad55a493503b"},
  "updatedAt":{"$date":"2021-10-01T02:47:36.207Z"},
  "createdAt":{"$date":"2021-10-01T02:47:36.207Z"},
  "sensor":{"$oid":"6181e5f83fca98374cf901fd"},
  "worker":{"$oid":"6153dcfb58ad722c747eb42d"},
  "__v":0
}

LocationSensor

{
  "_id":{"$oid":"6181e5f83fca98374cf901fd"},
  "name":"Location Sensor 1",
  "description":"Location sensor for Location 2",
  "location": "$oid":"6181df3b3fca98374cf901fb"},
  "trackerType":"RFID",
  "sensorType":"ENVIRONMENT",
  "type":"LOCATION",
  "__v":0
}

The result I'm getting are all my WorkerLocationContexts, but the field "test" returns as an empty array.

Can someone help me?

Thanks in advance!


问:
Python - Code returns dates but when added to list the format changes
I am trying to create a list of dates to add to a Pandas dataframe as a new column using ...

```<code>df['Surveys_Last_Week'] = list
</code>```

I have done this before without issues. However, with the code below I get the dates returned in the format I want but when I add them to a list the format changes and they become prefixed with datetime.date

```<code>2022-05-14
2022-07-09
2022-03-05
2022-03-12

[datetime.date(2022, 5, 14), datetime.date(2022, 7, 9), datetime.date(2022, 3, 5), datetime.date(2022, 3, 12)]
</code>```

How can I get the dates into a list in the format that they return in?

The code I am using is as follows ...

```<code>today = datetime.date.today()

completion_list_80 = []

for value in df.Weeks_to_80pc:
    if value == float('inf'):
        pass
    else:
        remaining_weeks = datetime.timedelta(weeks=value)
        projected_completion = today + remaining_weeks
        print(projected_completion)
        completion_list_80.append(projected_completion)

print(completion_list_80)
</code>```

Any help very much appreciated.

Thank you

答:
To convert the list of datetime.date objects to a pandas.DatetimeIndex column using NumPy's datetime64 dtype, you can wrap pandas.to_datetime() around your list when you insert it into your DataFrame:

```<code>df['Surveys_Last_Week'] = pd.to_datetime(completion_list_80)
</code>```

Alternatively, to convert the datetime.date objects to their yyy-mm-dd string representations, you can format them with strftime as you append them to the list (however, I would recommend sticking to pandas' builtin DatetimeIndex support):

```<code>completion_list_80.append(projected_completion.strftime('%Y-%m-%d'))
</code>```

Body:
I am trying to create a list of dates to add to a Pandas dataframe as a new column using ...

df['Surveys_Last_Week'] = list

I have done this before without issues. However, with the code below I get the dates returned in the format I want but when I add them to a list the format changes and they become prefixed with datetime.date

2022-05-14
2022-07-09
2022-03-05
2022-03-12

[datetime.date(2022, 5, 14), datetime.date(2022, 7, 9), datetime.date(2022, 3, 5), datetime.date(2022, 3, 12)]

How can I get the dates into a list in the format that they return in?

The code I am using is as follows ...

today = datetime.date.today()

completion_list_80 = []

for value in df.Weeks_to_80pc:
    if value == float('inf'):
        pass
    else:
        remaining_weeks = datetime.timedelta(weeks=value)
        projected_completion = today + remaining_weeks
        print(projected_completion)
        completion_list_80.append(projected_completion)

print(completion_list_80)

Any help very much appreciated.

Thank you

Body:
To convert the list of datetime.date objects to a pandas.DatetimeIndex column using NumPy's datetime64 dtype, you can wrap pandas.to_datetime() around your list when you insert it into your DataFrame:

df['Surveys_Last_Week'] = pd.to_datetime(completion_list_80)

Alternatively, to convert the datetime.date objects to their yyy-mm-dd string representations, you can format them with strftime as you append them to the list (however, I would recommend sticking to pandas' builtin DatetimeIndex support):

completion_list_80.append(projected_completion.strftime('%Y-%m-%d'))


问:
Plotting monthly average over time of a column grouped by another column - RStudio
I have a dataframe df_have that looks like this:

```<code>  Arrival_Date     Cust_ID      Wait_Time_Mins    Cust_Priority
  <chr>              <int>          <int>           <int>
1 1/01/2010         612345            114               1
2 1/01/2010         415911            146               4
3 1/01/2010         445132             13               2
4 1/01/2010         515619             72               3
5 1/01/2010         725521            155               4
6 1/01/2010         401404            100               5
    ...               ...              ...             ...
</code>```

And I want to create five line graphs - 1 for each of the unique values in Cust_Priority -
overlayed on the same plot, such that it is the such that it is the average Wait_Time_Mins by Cust_Priority by month.

How would I do this?

I know how

答:
You can use floor_date to change the date to 1st day of the month. Then for each Cust_Priority in each Month get the average wait time and create a line plot.

We use scale_x_date to format the labels on X-axis.

```<code>library(dplyr)
library(lubridate)
library(ggplot2)

df %>%
  #If the date is in mdy format use mdy() function to change Arrival_Date to date
  mutate(Arrival_Date = dmy(Arrival_Date),
         date = floor_date(Arrival_Date, 'month')) %>%
  group_by(Cust_Priority, date) %>%
  summarise(Wait_Time_Mins = mean(Wait_Time_Mins), .groups = 'drop') %>%
  ggplot(aes(date, Wait_Time_Mins, color = factor(Cust_Priority),
             group = Cust_Priority)) +
  geom_line() +
  labs(x = "Month", y = "Average wait time",
       title = "Average wait time for each month", color = "Customer Priority") +
  scale_x_date(date_labels = '%b - %Y', date_breaks = '1 month')
</code>```

Body:
I have a dataframe df_have that looks like this:

  Arrival_Date     Cust_ID      Wait_Time_Mins    Cust_Priority
  <chr>              <int>          <int>           <int>
1 1/01/2010         612345            114               1
2 1/01/2010         415911            146               4
3 1/01/2010         445132             13               2
4 1/01/2010         515619             72               3
5 1/01/2010         725521            155               4
6 1/01/2010         401404            100               5
    ...               ...              ...             ...

And I want to create five line graphs - 1 for each of the unique values in Cust_Priority -
overlayed on the same plot, such that it is the such that it is the average Wait_Time_Mins by Cust_Priority by month.

How would I do this?

I know how

Body:
You can use floor_date to change the date to 1st day of the month. Then for each Cust_Priority in each Month get the average wait time and create a line plot.

We use scale_x_date to format the labels on X-axis.

library(dplyr)
library(lubridate)
library(ggplot2)

df %>%
  #If the date is in mdy format use mdy() function to change Arrival_Date to date
  mutate(Arrival_Date = dmy(Arrival_Date),
         date = floor_date(Arrival_Date, 'month')) %>%
  group_by(Cust_Priority, date) %>%
  summarise(Wait_Time_Mins = mean(Wait_Time_Mins), .groups = 'drop') %>%
  ggplot(aes(date, Wait_Time_Mins, color = factor(Cust_Priority),
             group = Cust_Priority)) +
  geom_line() +
  labs(x = "Month", y = "Average wait time",
       title = "Average wait time for each month", color = "Customer Priority") +
  scale_x_date(date_labels = '%b - %Y', date_breaks = '1 month')


问:
python "TypeError: 'builtin_function_or_method' object is not iterable"
im trying to make a function that calculates the mad in a list but after i was done making it, it didnt work and said 'TypeError: 'builtin_function_or_method' object is not iterable' and i dont know why is said this. heres the code.</p>
```<code>def mad(a):

    mean = sum(a)/len(a)

    absoluteDeviation = []
    for eachValue in input:
        absoluteDeviation.append(abs(eachValue - mean))
        eachValue += 1

    mad = sum(absoluteDeviation)/len(absoluteDeviation)
    print(mad)
mad([2,4,6,8])
</code>```

答:
instead of

```<code>for eachValue in input:
</code>```

It should be:

```<code>for eachValue in a:#since a is the iterable not input
</code>```

there is no need for:

```<code>eachValue += 1
</code>```

Code:

```<code>def mad(a):

    mean = sum(a)/len(a)

    absoluteDeviation = []
    for eachValue in a:
        absoluteDeviation.append(abs(eachValue - mean))
        #eachValue += 1

    return sum(absoluteDeviation)/len(absoluteDeviation)
print(mad([2,4,6,8]))
</code>```

Output:

```<code>$python3.10 iterable.py
2.0
</code>```

A better approach to calculate mean absolute deviation since we are using less memory as compare to above code:

```<code>"""
mean absolute deviation
"""
def mad(a):

    mean = sum(a)/float(len(a))

    mean_absolute_deviation = 0
    for eachValue in a:
        mean_absolute_deviation += abs(eachValue - mean)

    mean_absolute_deviation /= len(a)
    return mean_absolute_deviation

print(mad([2,4,6,8]))
</code>```

Body:
im trying to make a function that calculates the mad in a list but after i was done making it, it didnt work and said 'TypeError: 'builtin_function_or_method' object is not iterable' and i dont know why is said this. heres the code.

def mad(a):

    mean = sum(a)/len(a)

    absoluteDeviation = []
    for eachValue in input:
        absoluteDeviation.append(abs(eachValue - mean))
        eachValue += 1

    mad = sum(absoluteDeviation)/len(absoluteDeviation)
    print(mad)
mad([2,4,6,8])

Body:
instead of

for eachValue in input:

It should be:

for eachValue in a:#since a is the iterable not input

there is no need for:

eachValue += 1

Code:

def mad(a):

    mean = sum(a)/len(a)

    absoluteDeviation = []
    for eachValue in a:
        absoluteDeviation.append(abs(eachValue - mean))
        #eachValue += 1

    return sum(absoluteDeviation)/len(absoluteDeviation)
print(mad([2,4,6,8]))

Output:

$python3.10 iterable.py
2.0

A better approach to calculate mean absolute deviation since we are using less memory as compare to above code:

"""
mean absolute deviation
"""
def mad(a):

    mean = sum(a)/float(len(a))

    mean_absolute_deviation = 0
    for eachValue in a:
        mean_absolute_deviation += abs(eachValue - mean)

    mean_absolute_deviation /= len(a)
    return mean_absolute_deviation

print(mad([2,4,6,8]))


问:
How to run qt-creator project with 'sudo nice x' prefixes?
So i have a C program that i made a while back that im going to remake in qt with additional features.

Typically how i ran the program is I open the terminal, navigate to the project folder, and use the command

```<code>$ sudo nice --10 ./myprogram
</code>```

That is not the case anymore, since i am using qt-creator i now just simply click the 'run' button and the program starts. My program works best when it has elevated scheduler priority hence the nice --10.

How do i modify my qt-creator project to run my program with the sudo nice --10 command?

答:
To do that go to

Tools-> Options-> Environment -> System Tab under the terminal option write "/usr/bin/xterm sudo nice --10"

Also if you have not done it already go to Projects -> Build & Run -> Run and check the box Run in terminal.

Body:
So i have a C program that i made a while back that im going to remake in qt with additional features.

Typically how i ran the program is I open the terminal, navigate to the project folder, and use the command

$ sudo nice --10 ./myprogram

That is not the case anymore, since i am using qt-creator i now just simply click the 'run' button and the program starts. My program works best when it has elevated scheduler priority hence the nice --10.

How do i modify my qt-creator project to run my program with the sudo nice --10 command?


问:
How is the number of random walks determined in GDS/Neo4j?
I am running the random walk algorithm on my Neo4j graph named 'example', with the minimum allowed walk length (2) and walks per node (1). Namely,

```<code>CALL gds.beta.randomWalk.stream(
  'example',
  {
    walkLength: 2,
    walksPerNode: 1,
    randomSeed: 42,
    concurrency: 1
  }
)
YIELD nodeIds, path
RETURN nodeIds, [node IN nodes(path) | node.name ] AS event_name
</code>```

And I get 41 walks. How is this number determined? I checked the graph and it contains 161 nodes and 574 edges. Any insights?

Added later: Here is more info on the projected graph that I am constructing. Basically, I am filtering on nodes and relationships and just projecting the subgraph and doing nothing else. Here is the code -

```<code>// Filter for only IDH Codel recurrent events
WITH [path=(m:IDHcodel)--(n:Tissue)
WHERE (m.node_category = 'molecular' AND n.event_class = 'Recurrence')
AND NOT EXISTS((m)--(:Tissue{event_class:'Primary'})) | m] AS recur_events
// Obtain the sub-network with 2 or more patients in edges
MATCH p=(m1)-[r:hasIDHcodelPatients]-(m2)
WHERE (m1 IN recur_events AND m2 IN recur_events AND r.total_common_patients >= 2)
WITH COLLECT(p) AS all_paths
WITH [p IN all_paths | nodes(p)] AS path_nodes, [p IN all_paths | relationships(p)] AS path_rels
WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Form the GDS Cypher projection
CALL gds.graph.create.cypher(
'example',
'MATCH (n) where n in $sn RETURN id(n) as id',
'MATCH ()-[r]-() where r in $sr RETURN id(startNode(r)) as source , id(endNode(r)) as target, { LINKS: { orientation: "UNDIRECTED" } }',
{parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
)
YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels
RETURN graph, nodes, rels
</code>```

Thanks.

答:
It seems that the documentation is missing the description for the sourceNodes parameter, which would tell you how many walks will be created.
We don't know the default value, but we can use the parameter to set the source nodes that the walk should start from.

For example, you could use all the nodes in the graph to be treated as a source node (the random walk will start from them).

```<code>MATCH (n)
WITH collect(n) AS nodes
CALL gds.beta.randomWalk.stream(
  'example',
  { sourceNodes:nodes,
    walkLength: 2,
    walksPerNode: 1,
    randomSeed: 42,
    concurrency: 1
  }
)
YIELD nodeIds, path
RETURN nodeIds, [node IN nodes(path) | node.name ] AS event_name
</code>```

This way you should get 161 walks as there are 161 nodes in your graph and the walksPerNode is set to 1, so a single random walk will start from every node in the graph. In essence, the number of source nodes times the walks per node will determine the number of random walks.

Body:
I am running the random walk algorithm on my Neo4j graph named 'example', with the minimum allowed walk length (2) and walks per node (1). Namely,

CALL gds.beta.randomWalk.stream(
  'example',
  {
    walkLength: 2,
    walksPerNode: 1,
    randomSeed: 42,
    concurrency: 1
  }
)
YIELD nodeIds, path
RETURN nodeIds, [node IN nodes(path) | node.name ] AS event_name

And I get 41 walks. How is this number determined? I checked the graph and it contains 161 nodes and 574 edges. Any insights?

Added later: Here is more info on the projected graph that I am constructing. Basically, I am filtering on nodes and relationships and just projecting the subgraph and doing nothing else. Here is the code -

// Filter for only IDH Codel recurrent events
WITH [path=(m:IDHcodel)--(n:Tissue)
WHERE (m.node_category = 'molecular' AND n.event_class = 'Recurrence')
AND NOT EXISTS((m)--(:Tissue{event_class:'Primary'})) | m] AS recur_events
// Obtain the sub-network with 2 or more patients in edges
MATCH p=(m1)-[r:hasIDHcodelPatients]-(m2)
WHERE (m1 IN recur_events AND m2 IN recur_events AND r.total_common_patients >= 2)
WITH COLLECT(p) AS all_paths
WITH [p IN all_paths | nodes(p)] AS path_nodes, [p IN all_paths | relationships(p)] AS path_rels
WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Form the GDS Cypher projection
CALL gds.graph.create.cypher(
'example',
'MATCH (n) where n in $sn RETURN id(n) as id',
'MATCH ()-[r]-() where r in $sr RETURN id(startNode(r)) as source , id(endNode(r)) as target, { LINKS: { orientation: "UNDIRECTED" } }',
{parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
)
YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels
RETURN graph, nodes, rels

Thanks.

Body:
It seems that the documentation is missing the description for the sourceNodes parameter, which would tell you how many walks will be created.
We don't know the default value, but we can use the parameter to set the source nodes that the walk should start from.

For example, you could use all the nodes in the graph to be treated as a source node (the random walk will start from them).

MATCH (n)
WITH collect(n) AS nodes
CALL gds.beta.randomWalk.stream(
  'example',
  { sourceNodes:nodes,
    walkLength: 2,
    walksPerNode: 1,
    randomSeed: 42,
    concurrency: 1
  }
)
YIELD nodeIds, path
RETURN nodeIds, [node IN nodes(path) | node.name ] AS event_name

This way you should get 161 walks as there are 161 nodes in your graph and the walksPerNode is set to 1, so a single random walk will start from every node in the graph. In essence, the number of source nodes times the walks per node will determine the number of random walks.


答:
You need to use total_seconds() instead of seconds.  The latter only includes the time within a day, but your time differences are larger than one day.

Ref: https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.total_seconds.html vs https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.seconds.html

Title: Calculate time difference from row before within groups

Body:
OK, I'm super confused here.

I had a look at this post (Time difference within group by objects in Python Pandas) and others and tried to follow them. Still I'm getting wonky answers.

What I would like to do is calculate the time in minutes since the previous row within each person's ID, and the first reading for each person should also = 30 minutes.

Here's what I tried:

import pandas as pd

ids = [1,1,1,2,2,2,3,3,3,4]
dates = ["12/25/2021 7:47:01", "6/23/2021 20:02:32", "2/24/2021 18:57:40", "2/26/2021 20:17", "3/7/2021 11:23:01", "3/11/2021 17:48:55", "3/12/2021 19:22:32", "3/25/2021 11:11:11", "4/4/2021 14:53:40",  "4/6/2021 13:07:07"]

df = pd.DataFrame({'ids':ids,
                   'dates':dates})

df['dates'] = pd.to_datetime(df['dates'])

df = df.sort_values(by = ['ids', 'dates'])

print(df)

   ids               dates
2    1 2021-02-24 18:57:40
1    1 2021-06-23 20:02:32
0    1 2021-12-25 07:47:01
3    2 2021-02-26 20:17:00
4    2 2021-03-07 11:23:01
5    2 2021-03-11 17:48:55
6    3 2021-03-12 19:22:32
7    3 2021-03-25 11:11:11
8    3 2021-04-04 14:53:40
9    4 2021-04-06 13:07:07

df = df.assign(
    timediff=df.groupby(['ids']).dates.diff().dt.seconds.div(60).fillna(30))

print(df)

   ids               dates    timediff
2    1 2021-02-24 18:57:40   30.000000
1    1 2021-06-23 20:02:32   64.866667
0    1 2021-12-25 07:47:01  704.483333
3    2 2021-02-26 20:17:00   30.000000
4    2 2021-03-07 11:23:01  906.016667
5    2 2021-03-11 17:48:55  385.900000
6    3 2021-03-12 19:22:32   30.000000
7    3 2021-03-25 11:11:11  948.650000
8    3 2021-04-04 14:53:40  222.483333
9    4 2021-04-06 13:07:07   30.000000

As you can see, I'm getting weird results. Here is something like what I would expect (just ballparked numbers):

   ids               dates    timediff
2    1 2021-02-24 18:57:40   30.000000
1    1 2021-06-23 20:02:32   171360.000000
0    1 2021-12-25 07:47:01  262800.000000
3    2 2021-02-26 20:17:00   30.000000
4    2 2021-03-07 11:23:01  43800.0000
5    2 2021-03-11 17:48:55  34320.00000
6    3 2021-03-12 19:22:32   30.000000
7    3 2021-03-25 11:11:11  18720.00000
8    3 2021-04-04 14:53:40  14400.00000
9    4 2021-04-06 13:07:07   30.000000

What's going on here and how could I fix it? Thanks in advance.


问:
docker: error pulling image configuration: Get https://production.cloudflare.docker.com Forbidden
When I run:

```<code>docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pulling fs layer
docker: error pulling image configuration: Get https://production.cloudflare.docker.com/registry-v2/docker/registry/v2/blobs/sha256/fe/feb5d8asdf678asd9fsdf7a9sd6f789sa6d7f8b825965ba48de054caab5ef356dc6b3412/data?verify=161234117-fZrnvGSb678afASf87g7dfd7InfY%3D: Forbidden.
</code>```

I am running docker from behind a proxy and have done the following setup:
https://docs.docker.com/config/daemon/systemd/

I have found this for the error, which states that the IP is blocked by Cloudflare and nothing can be done https://forums.docker.com/t/unable-to-pull-image-from-docker-hub-forbidden/27376/2 ?

Is there any solution to the Forbidden error?

答: I noticed that this happens when you're trying to request for an image multiple times, so if this continues trying using a VPN application, so that you can produce a new IP and bypass that issue. Is just a common thing with cloudflare. So in this case a vpn can help you for the mean time.</p>

Body:
When I run:

docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pulling fs layer
docker: error pulling image configuration: Get https://production.cloudflare.docker.com/registry-v2/docker/registry/v2/blobs/sha256/fe/feb5d8asdf678asd9fsdf7a9sd6f789sa6d7f8b825965ba48de054caab5ef356dc6b3412/data?verify=161234117-fZrnvGSb678afASf87g7dfd7InfY%3D: Forbidden.

I am running docker from behind a proxy and have done the following setup:
https://docs.docker.com/config/daemon/systemd/

I have found this for the error, which states that the IP is blocked by Cloudflare and nothing can be done https://forums.docker.com/t/unable-to-pull-image-from-docker-hub-forbidden/27376/2 ?

Is there any solution to the Forbidden error?


问:
Rails first app browser error. undefined local variable or method `state' for ActiveSupport
Nwbie here. After following some guides to install and setup Ruby on Rails I have the following error when opening the server in the browser.

Guides:

https://www.youtube.com/watch?v=fmyvWz5TUWg&t=1567s&ab_channel=freeCodeCamp.org

https://guides.rubyonrails.org/getting_started.html

Im using these versions

Ubuntu: 20.04.03 LTS

Ruby: 3.0.3

Rails: 7.0.2.1

SQLite3: 3.31.1

Node: 16.13.2

Yarn 1.22.17

Puma caught this error: undefined local variable or method state' for ActiveSupport::IsolatedExecutionState:Module (NameError) /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/activesupport-7.0.2.1/lib/active_support/isolated_execution_state.rb:45:in delete'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/activesupport-7.0.2.1/lib/active_support/execution_wrapper.rb:69:in run!' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/actionpack-7.0.2.1/lib/action_dispatch/middleware/executor.rb:12:in call'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/actionpack-7.0.2.1/lib/action_dispatch/middleware/static.rb:23:in call' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/rack-2.2.3/lib/rack/sendfile.rb:110:in call'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/actionpack-7.0.2.1/lib/action_dispatch/middleware/host_authorization.rb:137:in call' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/railties-7.0.2.1/lib/rails/engine.rb:530:in call'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/configuration.rb:252:in call' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/request.rb:77:in block in handle_request'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/thread_pool.rb:340:in with_force_shutdown' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/request.rb:76:in handle_request'
/home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/server.rb:441:in process_client' /home/matias/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/puma-5.6.1/lib/puma/thread_pool.rb:147:in block in spawn_thread'

I have no clue whats going on, also couldnt find any related topic here. Tried to re-install everything and with different versions, same error

Thank you in advance

答:
Solved.

Initiating the server swith sudo showed some problems with Ruby version.

Check how you install ruby, make sure you have a clean installation. I recommend deleting everything and clean start with rbenv.

This guide made the thing:
https://www.youtube.com/watch?v=FfXd0XQ4QbY&list=FL1o8s2zTqBUnUqNxwtF8fHA&index=1&t=90s&ab_channel=apiske


问:
JPA @OneToMany and @ManyToOne: back reference is null though mappedBy is included
I have 4 Entities, that a related to each other with @OneToMany relationships.
When I try to save Order that contains OrderItem - Orderitem has no backreference.

In the code below only important fields are showed for brevity ( usual strings and primitives are omitted ). I decided to include Dish and User Entities also.

Order:

```<code>@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(
        mappedBy = "order",
        cascade = CascadeType.ALL,
        fetch = FetchType.EAGER,
        orphanRemoval = true)
    private List < OrderItem > orderItems;
}
</code>```

Dish:

```<code>@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Dish {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        mappedBy = "dish")
    @ToString.Exclude
    private List < OrderItem > orderItems;
}
</code>```

OrderItem:

```<code>@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class OrderItem {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @ToString.Exclude
    private Dish dish;
    @ManyToOne(fetch = FetchType.LAZY)
    private Order order;
    private int quantity;
}
</code>```

User:

```<code>@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @OneToMany(
        mappedBy = "user",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List < Order > orders;
}
</code>```

The problem happens when I try to save Order with Spring data JPA.
Let's print Order to see OrderItem before saving.

```<code>public Order saveOrder(Order order) {
    System.out.println("SERVICE saving order " + order);
    return orderRepository.save(order);
}
</code>```

As you can see, orderItems backreference is null before saving ( I though spring data jpa should deal with setting it ).

SERVICE saving order Order(id=0,
orderItems=[OrderItem(id=0, quantity=2, order=null)])

Here is what I have in DB ( Order and OrderItem entities ).

答:
In your OrderItem class, add annotation below:

```<code>@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST}, fetch=FetchType.LAZY)
@JoinColumn(name="order_id", referencedColumnName="id", nullable = false)
Order order.
</code>```

One more thing, I suggest you use SEQUENCE_GENERATOR, beacause IDENTITY means: I'll create the entity with a null ID and the database will generate one for me. I don't think Postgres even supports that, and even if it does, a sequence generator is a better, more efficient choice.

Body:
I have 4 Entities, that a related to each other with @OneToMany relationships.
When I try to save Order that contains OrderItem - Orderitem has no backreference.

In the code below only important fields are showed for brevity ( usual strings and primitives are omitted ). I decided to include Dish and User Entities also.

Order:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(
        mappedBy = "order",
        cascade = CascadeType.ALL,
        fetch = FetchType.EAGER,
        orphanRemoval = true)
    private List < OrderItem > orderItems;
}

Dish:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Dish {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        mappedBy = "dish")
    @ToString.Exclude
    private List < OrderItem > orderItems;
}

OrderItem:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
public class OrderItem {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @ToString.Exclude
    private Dish dish;
    @ManyToOne(fetch = FetchType.LAZY)
    private Order order;
    private int quantity;
}

User:

@Entity
@NoArgsConstructor
@Getter
@Setter
@ToString
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @OneToMany(
        mappedBy = "user",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List < Order > orders;
}

The problem happens when I try to save Order with Spring data JPA.
Let's print Order to see OrderItem before saving.

public Order saveOrder(Order order) {
    System.out.println("SERVICE saving order " + order);
    return orderRepository.save(order);
}

As you can see, orderItems backreference is null before saving ( I though spring data jpa should deal with setting it ).

SERVICE saving order Order(id=0,
orderItems=[OrderItem(id=0, quantity=2, order=null)])

Here is what I have in DB ( Order and OrderItem entities ).

Body:
In your OrderItem class, add annotation below:

@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST}, fetch=FetchType.LAZY)
@JoinColumn(name="order_id", referencedColumnName="id", nullable = false)
Order order.

One more thing, I suggest you use SEQUENCE_GENERATOR, beacause IDENTITY means: I'll create the entity with a null ID and the database will generate one for me. I don't think Postgres even supports that, and even if it does, a sequence generator is a better, more efficient choice.


问:
media query for the smallest screen not taking effect
I have the following three queries. My purpose is when screen width is 1200 or higher; screen between 800 and 1199 and any screen width below 800. the following code does not fire on any width below 800.

I have no additional CSS to overwride any style. the 400px width still takes the styles of   between 800 and 1199 pixels block.

What am I doing wrong?

```<code>  @media screen and (min-width: 1200px) {

   }

@media screen and (min-width: 800px) and (max-width: 1199px) {

}

@media screen and (max-width: 799px) {

}
</code>```

答:
You either go (desktop-first) approach OR (mobile-first) approach. Don't mix both of them.

Desktop First:

div {background:yellow; height:200px; width:200px; border:2px solid #000;}

@media screen and (max-width: 1200px) {
  div {background:green;}
}

@media screen and (max-width: 800px) {
   div {background:blue;}
}

@media screen and (max-width: 480px) {
  div {background:pink;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Mobile-First:

div {background:pink; height:200px; width:200px; border:2px solid #000;}

@media screen and (min-width: 480px) {
  div {background:blue;}
}

@media screen and (min-width: 800px) {
   div {background:green;}
}

@media screen and (min-width: 1200px) {
  div {background:yellow;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Start describing CSS from one end (Either biggest-screen size) OR (Smallest screen-size) and go to the other end. Never try add min-width and max-width in same CSS defination. Its confusing and inappropriate.

Also, use something like @media screen and (min-width:520px) and (max-width:560px) when after all CSS you've written, only for certain width-zone, you specifically want to change something or add a unique CSS. Otherwise don't use the mix of (min-width) and (max-width) in same CSS code ever. That's not a good practise.

Go with flow in uni-direction, either from Wide-screens then keep using (max-widths) OR starting from 0px or smallest-mobiles and then keep using (min-width) to keep defining new CSS till you reach other end.

Body:
I have the following three queries. My purpose is when screen width is 1200 or higher; screen between 800 and 1199 and any screen width below 800. the following code does not fire on any width below 800.

I have no additional CSS to overwride any style. the 400px width still takes the styles of   between 800 and 1199 pixels block.

What am I doing wrong?

  @media screen and (min-width: 1200px) {

   }

@media screen and (min-width: 800px) and (max-width: 1199px) {

}

@media screen and (max-width: 799px) {

}

Body:
You either go (desktop-first) approach OR (mobile-first) approach. Don't mix both of them.

Desktop First:

div {background:yellow; height:200px; width:200px; border:2px solid #000;}

@media screen and (max-width: 1200px) {
  div {background:green;}
}

@media screen and (max-width: 800px) {
   div {background:blue;}
}

@media screen and (max-width: 480px) {
  div {background:pink;}
}

<div></div>

Mobile-First:

div {background:pink; height:200px; width:200px; border:2px solid #000;}

@media screen and (min-width: 480px) {
  div {background:blue;}
}

@media screen and (min-width: 800px) {
   div {background:green;}
}

@media screen and (min-width: 1200px) {
  div {background:yellow;}
}

<div></div>

Start describing CSS from one end (Either biggest-screen size) OR (Smallest screen-size) and go to the other end. Never try add min-width and max-width in same CSS defination. Its confusing and inappropriate.

Also, use something like @media screen and (min-width:520px) and (max-width:560px) when after all CSS you've written, only for certain width-zone, you specifically want to change something or add a unique CSS. Otherwise don't use the mix of (min-width) and (max-width) in same CSS code ever. That's not a good practise.

Go with flow in uni-direction, either from Wide-screens then keep using (max-widths) OR starting from 0px or smallest-mobiles and then keep using (min-width) to keep defining new CSS till you reach other end.


问:
MySQL Workbench 8.0 WbAdmin.testInstanceSettingByName
Has this issue been addressed?  I have complete access with new user after creation. But when I go through configure local management on workbench, it locates my config file but throws the same error:

Operation failed: error calling Python module function WbAdmin.testInstanceSettingByName.  I would like to know what is happening and resolve it rather than going backwards to a previous release.

答:
I had the same issue,
the problem was that there was some weird characters in my.ini file that causes the decode error.Bug Report

Solution is

Open my.ini File

Delete all the comments above server-id as shown here

Save & Restart Workbench


问:
Websocket - Should client send ping frames?
As the title suggests, should Ping Frames only be sent from a server or it is better to have both endpoints send them? As mentioned in the Websocket RFC:

NOTE: A Ping frame may serve either as a keepalive...

So by by having one endpoint sending a ping request it should keep the connection open, right?

The second part of above line is this:

or as a means to verify that the remote endpoint is still responsive.

I'm new to the concept of websockets but if the connection closes from the server won't the client be notified?

答: Both variants has ways of implementation. For example in case if server sends ping to client, then client can get information that server disconnected by have a loop with deadline timer which is reset every time when ping is received. If the timer reaches dealine, then it's mean that server disconnected.</p>

ContentLicense: CC BY-SA 3.0


问:
Typing in the firt input without focusing
I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers

My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers

const maxLength = 7;
const firstInput = document.querySelector("#pin");
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")

let activeInput;

firstInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
  console.log("i'm changing!");
  if (firstInput.value.length >= maxLength) {
    activeInput = secondInput;
    secondInput.focus();
  }
});

secondInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
  // manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
  activeInput.dispatchEvent(changedEvent);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>
    <br />
        <input type="text" id="pin" />
        <input type="text" id="key" /></code>```

答:
<button id="reset" onclick="resetNumber()">Reset</button>

<input type="text" id="pin" />
<input type="text" id="key" />

```

Body:
I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers

My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers

const maxLength = 7;
const firstInput = document.querySelector("#pin");
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")

let activeInput;

firstInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
  console.log("i'm changing!");
  if (firstInput.value.length >= maxLength) {
    activeInput = secondInput;
    secondInput.focus();
  }
});

secondInput.addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("pin");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
  // manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
  activeInput.dispatchEvent(changedEvent);
}

    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>

        <input type="text" id="pin" />
        <input type="text" id="key" />

Body:
<button id="reset" onclick="resetNumber()">Reset</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />

<script>
    const maxLength = 7;
    const firstInput = document.querySelector('#pin');
    const secondInput = document.querySelector('#key');

    const resetBtn = document.querySelector('#reset');

    for (let i = 9; i >= 0; i--) {
        const numBtn = document.createElement('button');
        numBtn.className = 'number';
        numBtn.innerText = i;
        resetBtn.parentElement.insertBefore(numBtn, resetBtn.nextSibling);
    }

    const numberBtns = document.querySelectorAll('.number');

    const resetNumber = () => {
        firstInput.setAttribute('value', '');
        secondInput.setAttribute('value', '');
    };

    const setVal = (e) => {
        const num = parseInt(e.target.innerText, 10);
        if (firstInput.value.length <= maxLength) return firstInput.setAttribute('value', firstInput.value + num);
        secondInput.setAttribute('value', secondInput.value + num);
    };

    numberBtns.forEach((btn) => btn.addEventListener('click', setVal));
</script>


问:
Detect break point (changing point) in the profile-python code
I have 215 profiles like the attached figure with different index for the break point. How can I find the index of the break point (changing point)? I tried to find it based on the derivation approach but it can accurately detect the index of the break point because of the noise of the data. Is there any Pyhton package that can detect the index of the changing point more accurately?

答:
Here's a way to do it with geopandas. You'll just need to replace the coords variable values with your own data.

```<code>import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiLineString
import math
from math import atan2

def calc_line_bearing(gdf):

    firstpoint = gdf.geometry.coords[0]
    lastpoint = gdf.geometry.coords[-1]

    delta_x = lastpoint[0] - firstpoint[0]
    delta_y = lastpoint[1] - firstpoint[1]

    bearing = atan2(delta_x, delta_y) * 180 / math.pi

    if bearing < 180:
        bearing = bearing + 180
    else:
        bearing = bearing - 180

    if bearing > 180:
        bearing = bearing - 180

    return bearing

coords = [((0, 0), (0, 1)), ((0, 1), (0, 2)), ((0, 2), (1, 3))]

# create a gdf with MLS geometry type
gdf = gpd.GeoDataFrame(geometry=[MultiLineString(coords)])
# convert from MLS to LineString so we can calc bearing for each line segment

gdf = gdf.explode()
# get rid of the multi-index
gdf.reset_index(inplace=True, drop=True)
# add the bearings for each line
gdf['bearing'] = gdf.apply(calc_line_bearing, axis=1)
# add a new column that will show us where the bearing value changes
shift = gdf["bearing"].shift(1)
gdf['break'] = (shift.ne(gdf['bearing']) & shift.notna())

print(gdf)

    geometry                                        bearing break
0   LINESTRING (0.00000 0.00000, 0.00000 1.00000)   180.0   False
1   LINESTRING (0.00000 1.00000, 0.00000 2.00000)   180.0   False
2   LINESTRING (0.00000 2.00000, 1.00000 3.00000)   45.0    True
</code>```

Body:
Here's a way to do it with geopandas. You'll just need to replace the coords variable values with your own data.

import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiLineString
import math
from math import atan2

def calc_line_bearing(gdf):

    firstpoint = gdf.geometry.coords[0]
    lastpoint = gdf.geometry.coords[-1]

    delta_x = lastpoint[0] - firstpoint[0]
    delta_y = lastpoint[1] - firstpoint[1]

    bearing = atan2(delta_x, delta_y) * 180 / math.pi

    if bearing < 180:
        bearing = bearing + 180
    else:
        bearing = bearing - 180

    if bearing > 180:
        bearing = bearing - 180

    return bearing

coords = [((0, 0), (0, 1)), ((0, 1), (0, 2)), ((0, 2), (1, 3))]

# create a gdf with MLS geometry type
gdf = gpd.GeoDataFrame(geometry=[MultiLineString(coords)])
# convert from MLS to LineString so we can calc bearing for each line segment

gdf = gdf.explode()
# get rid of the multi-index
gdf.reset_index(inplace=True, drop=True)
# add the bearings for each line
gdf['bearing'] = gdf.apply(calc_line_bearing, axis=1)
# add a new column that will show us where the bearing value changes
shift = gdf["bearing"].shift(1)
gdf['break'] = (shift.ne(gdf['bearing']) & shift.notna())

print(gdf)

    geometry                                        bearing break
0   LINESTRING (0.00000 0.00000, 0.00000 1.00000)   180.0   False
1   LINESTRING (0.00000 1.00000, 0.00000 2.00000)   180.0   False
2   LINESTRING (0.00000 2.00000, 1.00000 3.00000)   45.0    True


问:
How to find a name with the fourth highest score?
pardon this silly question but I need your help.

I have a list of name, let's say

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']

and their scores are

score = [75,60,80,79,90,30]

How to write the code in Python so if I want to know the fourth highest score the result is

The fourth highest score is Alpha.

Thanks in advance for your help.

答:
here is one way :

```<code>sorted(zip(score, name), reverse=True)[3]
</code>```

output:

```<code>>> (75, 'Alpha')
</code>```

Body:
here is one way :

sorted(zip(score, name), reverse=True)[3]

output:

>> (75, 'Alpha')


问:
c++20 handling of string literals
We’re updating a project to c++20, and are running into errors where we pass string literals into functions which take char *. I know this has been changed to make code more safe, but we are interfacing with libraries which we cannot change.

I’d rather not disable the strict treatment of literals via compiler flags, so is there a good way to wrap these literals just in these particular cases?

I was thinking of an inline function, that was named something specific to the library, that internally would use const_cast. That way later if we want to change the code because the library gets updated, we know exactly where to look.

Any other ideas?

答:
"Any other ideas?"

```<code>static char my_string[] = "string";
...
//elsewhere in the code
library_function(my_string);
</code>```

The only difference between passing a string like that, and passing a string literal is the section of the assembly the data is stored in.

A string literal is stored in .text, a non-modifiable section.

The non-const string will be stored in .data.

If you really, really care if you're passing a function a pointer to .text or a pointer to .data, and you really, really, trust the library to not modify the parameter now and for ever, then you can certainly cast away the const-ness of your string literals.

Ignoring the fact that documentation lags behind implementation, even if we could believe the documentation promise to not modify its inputs, if it doesn't enforce it through the interface, at any time, on purpose or on accident, that input could be modified.

Title: c++20 handling of string literals

Body:
"Any other ideas?"

static char my_string[] = "string";
...
//elsewhere in the code
library_function(my_string);

The only difference between passing a string like that, and passing a string literal is the section of the assembly the data is stored in.

A string literal is stored in .text, a non-modifiable section.

The non-const string will be stored in .data.

If you really, really care if you're passing a function a pointer to .text or a pointer to .data, and you really, really, trust the library to not modify the parameter now and for ever, then you can certainly cast away the const-ness of your string literals.

Ignoring the fact that documentation lags behind implementation, even if we could believe the documentation promise to not modify its inputs, if it doesn't enforce it through the interface, at any time, on purpose or on accident, that input could be modified.


问:
Cannot connect to Google RDP Virtual Machine
I have just created a Virtual Machine instance on GCP; I have a username, a password and a ip address.
I opened Remmina on my pc and I tried to connect.
Everything worked for 10 minutes then the screen turned black and I restarted it and, since then, connection doesn't work anymore. I get the "Lost connection" error.
I opened my terminal and I typed telnet 34.xx.xxx.xx and it hangs so I guess that the connection isn't working anymore.

I don't know why since I didn't touch anything.
I also tried to restart the machine and create a new instance but I get the same error.

Any suggestions?

答:
I had similar issues, cannot be sure unless I have seen the gcp account but here are my few guesses :

Was the account that you created a temperory account ( qwicklabs etc ) that could have expired ?

Did you change the OS to Core where the login is command prompt based black screen ?

I have just tried to login to the below configuration

To check if I was able to RDP sucessfully

Edit 1:
first try to telnet on the port 3389

```<code>telnet <ip-address> 3389
</code>```

if you are not able to connect try to enable the firewall for 3389

```<code>gcloud compute firewall-rules create allow-rdp --allow tcp:3389
</code>```

Here is the Google page for troubleshooting RDP connections

Body:
I had similar issues, cannot be sure unless I have seen the gcp account but here are my few guesses :

Was the account that you created a temperory account ( qwicklabs etc ) that could have expired ?

Did you change the OS to Core where the login is command prompt based black screen ?

I have just tried to login to the below configuration

To check if I was able to RDP sucessfully

Edit 1:
first try to telnet on the port 3389

telnet <ip-address> 3389

if you are not able to connect try to enable the firewall for 3389

gcloud compute firewall-rules create allow-rdp --allow tcp:3389

Here is the Google page for troubleshooting RDP connections


问:
trying to group individual students by their ID# in order to analyze student gender distribution , each student has multiple rows for each class taken
I got the aggregate function to work and group individual students by their ID# but it won't display their gender, just says N/A, im new at programming so if you can explain where I'm going wrong that would be greatly appreciated. I am trying to analyze student performance and want to see how many males vs females there are as a first step.

here is a sample of the code I am trying:

```<code>library(dplyr)
library(tidyr)
rm(list=ls())
fake.data <- data.frame(ID = c(1,1,1,1,2,2,2,3,3,3,4,4,4),
                    Gender = c("M","M","M","M","F","F",'F',"F","F","F", "M", "M", "M"),
                    RolledGrade = c("A", "A-", "A", "B", "C", "B", "C", "B", "B", "A", "A", "A-", "A-"),
                    InstructorCode = c("IO", "ED", "IA", "SA", "BA", "BA", "SA", "IA", "EA", "IO", "ED", "ED", "ED"),
                    stringsAsFactors = FALSE)

grouped_by_gender<- aggregate(fake.data$Gender, fake.data["ID"], FUN = "mean")
</code>```

答:
I am still having trouble understanding what you want as an output.

Maybe this is what you are looking for or a start to get you where you want.

```<code>library(dplyr)
grouped_by_gender <- fake.data %>%
group_by(ID, Gender) %>%
tally()
</code>```

Body:
I got the aggregate function to work and group individual students by their ID# but it won't display their gender, just says N/A, im new at programming so if you can explain where I'm going wrong that would be greatly appreciated. I am trying to analyze student performance and want to see how many males vs females there are as a first step.

here is a sample of the code I am trying:

library(dplyr)
library(tidyr)
rm(list=ls())
fake.data <- data.frame(ID = c(1,1,1,1,2,2,2,3,3,3,4,4,4),
                    Gender = c("M","M","M","M","F","F",'F',"F","F","F", "M", "M", "M"),
                    RolledGrade = c("A", "A-", "A", "B", "C", "B", "C", "B", "B", "A", "A", "A-", "A-"),
                    InstructorCode = c("IO", "ED", "IA", "SA", "BA", "BA", "SA", "IA", "EA", "IO", "ED", "ED", "ED"),
                    stringsAsFactors = FALSE)

grouped_by_gender<- aggregate(fake.data$Gender, fake.data["ID"], FUN = "mean")

Body:
I am still having trouble understanding what you want as an output.

Maybe this is what you are looking for or a start to get you where you want.

library(dplyr)
grouped_by_gender <- fake.data %>%
group_by(ID, Gender) %>%
tally()


问:
Must pass Data Frame with boolean values only error?
I have a data frame of various variables with numeric values (such as temp, speed, etc.) on which I am trying to run a few pieces of code, such as replacing outliers with the mean and creating a scatterplot. However, I keep getting the error I referenced in the title... I'm not sure where I'm going wrong, as this code has worked on other data frames.

Here's a example of my data frame:

```<code>import pandas as pd
df = pd.DataFrame({'temp': [.2, naN, .12],
                   'speed': [1, 1, 0],
                    'weekday': [1, 2, 3]})
</code>```

Here's the actual code I'm using (step #1 is just importing it and works fine):

```<code>import pandas as pd
cars = pd.read_csv("C:/Users/Downloads/file.csv")
</code>```

Step 2 is where I begin having issues:

```<code>import numpy as np

outliers = []
outliers.append(cars[['temp', 'speed']])

for j in outliers:
    upper_quartile = np.nanpercentile(cars[j], 75)
    lower_quartile = np.nanpercentile(cars[j], 25)
    iqr = upper_quartile - lower_quartile

    upper_whisker = upper_quartile + 1.5*iqr
    lower_whisker = np.maximum(lower_quartile - 1.5*iqr, 0)

    cars[j] = np.where((cars[j] <= lower_whisker) |
                      (cars[j] >= upper_whisker), np.nan, cars[j])

</code>```

This should be filling outliers with NaN, but when run I get the Boolean data frame error message. Same error message when running this next bit to replace those missing value's with the column's mean:

```<code>for v in outliers:
    cars[v].fillna(cars[v].mean(), True)
</code>```

答:
Not sure if this will solve your issue, but I was running into a similar issue where the ultimate problem ended up being that my specific dataframe of True/False values was being stored as an object dtype within Pandas.

In the error below, you can see where it's checking whether the values are bool types, and although all the values were in fact True/False values, the way in which I constructed the dataframe had the specific column stored as a generic object dtype.

```<code>/opt/conda/lib/python3.8/site-packages/pandas/core/frame.py in _setitem_frame(self, key, value)
   3204
   3205         if key.size and not is_bool_dtype(key.values):
-> 3206             raise TypeError(
   3207                 "Must pass DataFrame or 2-d ndarray with boolean values only"
   3208             )
</code>```

In the end, the solution was to simply cast that dataframe to bool dtype using:

Before

```<code>print(df.values)
array([[False],
       [False],
       [False],
       ...,
       [True],
       [True],
       [True]], dtype=object) # notice the object dtype
</code>```

After

```<code>print(df.astype(bool).values)
array([[False],
       [False],
       [False],
       ...,
       [ True],
       [ True],
       [ True]])
</code>```

Body:
I have a data frame of various variables with numeric values (such as temp, speed, etc.) on which I am trying to run a few pieces of code, such as replacing outliers with the mean and creating a scatterplot. However, I keep getting the error I referenced in the title... I'm not sure where I'm going wrong, as this code has worked on other data frames.

Here's a example of my data frame:

import pandas as pd
df = pd.DataFrame({'temp': [.2, naN, .12],
                   'speed': [1, 1, 0],
                    'weekday': [1, 2, 3]})

Here's the actual code I'm using (step #1 is just importing it and works fine):

import pandas as pd
cars = pd.read_csv("C:/Users/Downloads/file.csv")

Step 2 is where I begin having issues:

import numpy as np

outliers = []
outliers.append(cars[['temp', 'speed']])

for j in outliers:
    upper_quartile = np.nanpercentile(cars[j], 75)
    lower_quartile = np.nanpercentile(cars[j], 25)
    iqr = upper_quartile - lower_quartile

    upper_whisker = upper_quartile + 1.5*iqr
    lower_whisker = np.maximum(lower_quartile - 1.5*iqr, 0)

    cars[j] = np.where((cars[j] <= lower_whisker) |
                      (cars[j] >= upper_whisker), np.nan, cars[j])

This should be filling outliers with NaN, but when run I get the Boolean data frame error message. Same error message when running this next bit to replace those missing value's with the column's mean:

for v in outliers:
    cars[v].fillna(cars[v].mean(), True)

Body:
Not sure if this will solve your issue, but I was running into a similar issue where the ultimate problem ended up being that my specific dataframe of True/False values was being stored as an object dtype within Pandas.

In the error below, you can see where it's checking whether the values are bool types, and although all the values were in fact True/False values, the way in which I constructed the dataframe had the specific column stored as a generic object dtype.

/opt/conda/lib/python3.8/site-packages/pandas/core/frame.py in _setitem_frame(self, key, value)
   3204
   3205         if key.size and not is_bool_dtype(key.values):
-> 3206             raise TypeError(
   3207                 "Must pass DataFrame or 2-d ndarray with boolean values only"
   3208             )

In the end, the solution was to simply cast that dataframe to bool dtype using:

Before

print(df.values)
array([[False],
       [False],
       [False],
       ...,
       [True],
       [True],
       [True]], dtype=object) # notice the object dtype

After

print(df.astype(bool).values)
array([[False],
       [False],
       [False],
       ...,
       [ True],
       [ True],
       [ True]])


问:
Merge two numpy arrays
I am trying to merge two arrays with the same number of arguments.

Input:

```<code>first = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745]]

second = [[1],
          [2],
          [3]]
</code>```

My expected output:

```<code>final = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775, 1],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745, 2],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745, 3]]
</code>```

To do that I create simple loop:

```<code>for i in first:
        for j in second:
            final += np.append(j, i)
</code>```

I got i filling that i missing something. First of all my loop i extremely slow. Secondly my data is quite have i got more than 2 mlns rows to loop. So I tried to find faster way for example with this code:

```<code>final = [np.append(i, second[0]) for i in first]
</code>```

It working far more faster than previous loop but its appending only first value of second array.
Can you help me?

答:
For this case, hstack (because second is already 2D) and c_ (because it concatenates along the second axis) would also work. In fact c_ would work even if second is shape (3,), as long as its length matches the length of first.

Assuming first and second are already numpy array objects:

```<code>out = np.c_[first, second]
</code>```

or

```<code>out1 = np.hstack((first, second))
</code>```

Output:

```<code>assert (out == np.array(final)).all() & (out == out1).all()
</code>```

That being said, all are just different ways of using np.concatenate.

Title: Merge two numpy arrays

Body:
I am trying to merge two arrays with the same number of arguments.

Input:

first = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745]]

second = [[1],
          [2],
          [3]]

My expected output:

final = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775, 1],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745, 2],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745, 3]]

To do that I create simple loop:

for i in first:
        for j in second:
            final += np.append(j, i)

I got i filling that i missing something. First of all my loop i extremely slow. Secondly my data is quite have i got more than 2 mlns rows to loop. So I tried to find faster way for example with this code:

final = [np.append(i, second[0]) for i in first]

It working far more faster than previous loop but its appending only first value of second array.
Can you help me?

Body:
For this case, hstack (because second is already 2D) and c_ (because it concatenates along the second axis) would also work. In fact c_ would work even if second is shape (3,), as long as its length matches the length of first.

Assuming first and second are already numpy array objects:

out = np.c_[first, second]

or

out1 = np.hstack((first, second))

Output:

assert (out == np.array(final)).all() & (out == out1).all()

That being said, all are just different ways of using np.concatenate.


问:
How to switch all 1's and 0's in a string at once
I have a string of numbers made up of 1's and 0's and I'd like to switch all the 1's to 0's and 0's to 1's at the same time.

My main issue is I can only figure out how to do it one at a time so the result is always either 0000 or 1111.

答:
Another way to solve this Problem is to chain Pythons String.replace() function. To avoid a String with only 1 or 0 after two replacements, you have to replace one char with an completely diffrent char.

```<code>test = '10011110101'
test.replace('0', '_').replace('1', '0').replace('_', '1')
</code>```

Output:

```<code>'01100001010'
</code>```

Body:
Another way to solve this Problem is to chain Pythons String.replace() function. To avoid a String with only 1 or 0 after two replacements, you have to replace one char with an completely diffrent char.

test = '10011110101'
test.replace('0', '_').replace('1', '0').replace('_', '1')

Output:

'01100001010'


问:
Check all installed python versions on linux
I use conda(anaconda) environments and wanted to test some syntax in py3.8.
Is there a way in which I can check all the installed python versions in my pc(across all conda envs).

I have tried

ls -ls /usr/bin/python*

but this doesn't include python installations in conda envs.

答:
One can search all Conda environments for the python package with

conda search --envs python
```

For each entry, this will give version, build, channel of origin, and the absolute location of the environment.

Body:
One can search all Conda environments for the python package with

conda search --envs python

For each entry, this will give version, build, channel of origin, and the absolute location of the environment.


问:
How to execute AST or code object in a separate process without exceeding max recursion depth
I am trying to write a metamorphic quine. Without the "spawn" context, the subprocesses seem to inherit the stack, and so I ultimately exceed the max recursion depth. With the "spawn context," the subprocess doesn't seem to recurse. How would I go about executing the modified AST?</p>
```<code>def main():
    module  = sys.modules[__name__]
    source  = inspect.getsource(module)
    tree    = ast.parse(source)

    visitor = Visitor() # TODO mutate
    tree    = visitor.visit(tree)
    tree    = ast.fix_missing_locations(tree)

    ctx     = multiprocessing.get_context("spawn")
    process = ctx.Process(target=Y, args=(tree,))
    # Y() encapsulates these lines, since code objects can't be pickled
    #code    = compile(tree, filename="<ast>", mode='exec', optimize=2)
    #process = ctx.Process(target=exec, args=(code, globals())) # locals()

    process.daemon = True
    process.start()
    # TODO why do daemonized processes need to be joined in order to run?
    process.join()

    return 0

if __name__ == '__main__': exit(main())
</code>```

答:
It really is that easy. with daemon.DaemonContext(): foo()
Based on comments by @user2357112 supports Monica.

```<code>@trace
def spawn_child(f:Callable):
    with daemon.DaemonContext(stdin=sys.stdin, stdout=sys.stdout): return f()

I = TypeVar('I')
def ai(f:Callable[[int,], I])->Callable[[int,], I]:
    def g(*args, **kwargs)->int:
        # assuming we have a higher-order function morph()
        # that has a concept of eta-equivalence
        # (e.g., a probabilistic notion),
        # then the recursive call should be "metamorphic"
        O = [morph(f), status, partial(spawn_child, f),]
        i = random.randrange(0, len(O)) # TODO something magickal
        return O[i]()
    return g

def main()->int: return Y(ai)()

if __name__ == '__main__': exit(main())
</code>```

The next problem is compiling the source for a nested function definition, since f() is not a reference to ai() but to a function defined within Y().

Body:
I am trying to write a metamorphic quine. Without the "spawn" context, the subprocesses seem to inherit the stack, and so I ultimately exceed the max recursion depth. With the "spawn context," the subprocess doesn't seem to recurse. How would I go about executing the modified AST?

def main():
    module  = sys.modules[__name__]
    source  = inspect.getsource(module)
    tree    = ast.parse(source)

    visitor = Visitor() # TODO mutate
    tree    = visitor.visit(tree)
    tree    = ast.fix_missing_locations(tree)

    ctx     = multiprocessing.get_context("spawn")
    process = ctx.Process(target=Y, args=(tree,))
    # Y() encapsulates these lines, since code objects can't be pickled
    #code    = compile(tree, filename="<ast>", mode='exec', optimize=2)
    #process = ctx.Process(target=exec, args=(code, globals())) # locals()

    process.daemon = True
    process.start()
    # TODO why do daemonized processes need to be joined in order to run?
    process.join()

    return 0

if __name__ == '__main__': exit(main())

Body:
It really is that easy. with daemon.DaemonContext(): foo()
Based on comments by @user2357112 supports Monica.

@trace
def spawn_child(f:Callable):
    with daemon.DaemonContext(stdin=sys.stdin, stdout=sys.stdout): return f()

I = TypeVar('I')
def ai(f:Callable[[int,], I])->Callable[[int,], I]:
    def g(*args, **kwargs)->int:
        # assuming we have a higher-order function morph()
        # that has a concept of eta-equivalence
        # (e.g., a probabilistic notion),
        # then the recursive call should be "metamorphic"
        O = [morph(f), status, partial(spawn_child, f),]
        i = random.randrange(0, len(O)) # TODO something magickal
        return O[i]()
    return g

def main()->int: return Y(ai)()

if __name__ == '__main__': exit(main())

The next problem is compiling the source for a nested function definition, since f() is not a reference to ai() but to a function defined within Y().


问:
How to subtract one row value from another and assign the value to a different row all in the same column, by group, for multiple columns in R
I have a strangely structured data frame with a grouping variable as a factor, followed by a character variable identifying expected vs. actual values for a series of ongoing days (where the actual values are recorded each day in a new column), as well as cumulatively, and I'm trying to calculate the difference between the expected and the actual values.

However, given the structure of the data, I'm struggling to figure out how to do this without getting into a whole mess of reshaping the data only to have to put it back together like this.

Is there a way I can calculate the differences, for each group, across all 'daily' columns, and then store the output in each 'original' column?

Sample Data

```<code>df1 <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Variable = c("Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative"), Day1 = c("Sunday", "1", "1", "3", "3", NA, NA, "Sunday", "1", "1", "1", "1", NA, NA, "Sunday", "8", "8", "5", "5", NA, NA), Day2 = c("Monday", "4", "3", "7", "4", NA, NA, "Monday", "2", "1", "3", "2", NA, NA, "Monday", "17", "9", "10", "5", NA, NA), Day3 = c("Tuesday", "6", "2", "10", "3", NA, NA, "Tuesday", "3", "1", "4", "1", NA, NA, "Tuesday", "29", "12", "14", "4", NA, NA), Day4 = c("Wednesday", "11", "5", "12", "2", NA, NA, "Wednesday", "4", "1", "5", "1", NA, NA, "Wednesday", "32", "3", "17", "3", NA, NA)), row.names = c(NA, -21L), class = "data.frame")
df1
</code>```

What I would like to do is fill  in the Diff.Daily cells in each "Day" column (i.e. Day1, Day2, etc.) by taking the difference between the Actual.Daily and Expected.Daily values for each Group (A, B, C), and then do similarly for Diff.Cumulative (i.e. Actual.Cumulative - Expected.Cumulative).

Desired Output

```<code>df2 <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Variable = c("Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative"), Day1 = c("Sunday", "1", "1", "3", "3", "-2", "-2", "Sunday", "1", "1", "1", "1", "0", "0", "Sunday", "8", "8", "5", "5", "3", "3"), Day2 = c("Monday", "4", "3", "7", "4", "-1", "-3", "Monday", "2", "1", "3", "2", "-1", "-1", "Monday", "17", "9", "10", "5", "4", "7"), Day3 = c("Tuesday", "6", "2", "10", "3", "-1", "-4", "Tuesday", "3", "1", "4", "1", "0", "-1", "Tuesday", "29", "12", "14", "4", "8", "15"), Day4 = c("Wednesday", "11", "5", "12", "2", "3", "-1", "Wednesday", "4", "1", "5", "1", "0", "-1", "Wednesday", "32", "3", "17", "3", "0", "15")), row.names = c(NA, -21L), class = "data.frame")
df2
</code>```

Here you can see for Group A on Day 1, Diff.Daily = -2 as expected from Actual.Daily of 1 minus an Expected.Daily of 3.

My Attempts

As the "Day" columns are of character class because of their mixed nature, I know I need to wrap the calculations with as.numeric(), and I can calculate the values individually for each column:

```<code>Diff.Cumulative <- as.numeric(df1[df1$Variable == "Actual.Cumulative", "Day1"]) - as.numeric(df1[df1$Variable == "Expected.Cumulative", "Day1"])
</code>```

But I'm struggling with how to expand this to all "Day" columns and to fit it into the current data frame structure. I came across a similar but ultimately different question.

答:
Here's a way to do this with the help of a helper function.

```<code>library(dplyr)

change_values <- function(sub1, sub2, to, var, value) {
  x <- suppressWarnings(as.numeric(value))
  x[match(to, var)] <- x[match(sub1, var)] - x[match(sub2, var)]
  x[1] <- value[1]
  x
}

df1 %>%
  group_by(Group) %>%
  mutate(across(starts_with('Day'), ~change_values('Actual.Daily',
        'Expected.Daily', 'Diff.Daily', Variable, .)),
         across(starts_with('Day'), ~change_values('Actual.Cumulative',
        'Expected.Cumulative', 'Diff.Cumulative', Variable, .))) %>%
  ungroup
</code>```

This returns -

```<code>#   Group            Variable   Day1   Day2    Day3      Day4
#1      A                 Day Sunday Monday Tuesday Wednesday
#2      A   Actual.Cumulative      1      4       6        11
#3      A        Actual.Daily      1      3       2         5
#4      A Expected.Cumulative      3      7      10        12
#5      A      Expected.Daily      3      4       3         2
#6      A          Diff.Daily     -2     -1      -1         3
#7      A     Diff.Cumulative     -2     -3      -4        -1
#8      B                 Day Sunday Monday Tuesday Wednesday
#9      B   Actual.Cumulative      1      2       3         4
#10     B        Actual.Daily      1      1       1         1
#11     B Expected.Cumulative      1      3       4         5
#12     B      Expected.Daily      1      2       1         1
#13     B          Diff.Daily      0     -1       0         0
#14     B     Diff.Cumulative      0     -1      -1        -1
#15     C                 Day Sunday Monday Tuesday Wednesday
#16     C   Actual.Cumulative      8     17      29        32
#17     C        Actual.Daily      8      9      12         3
#18     C Expected.Cumulative      5     10      14        17
#19     C      Expected.Daily      5      5       4         3
#20     C          Diff.Daily      3      4       8         0
#21     C     Diff.Cumulative      3      7      15        15
</code>```

Body:
I have a strangely structured data frame with a grouping variable as a factor, followed by a character variable identifying expected vs. actual values for a series of ongoing days (where the actual values are recorded each day in a new column), as well as cumulatively, and I'm trying to calculate the difference between the expected and the actual values.

However, given the structure of the data, I'm struggling to figure out how to do this without getting into a whole mess of reshaping the data only to have to put it back together like this.

Is there a way I can calculate the differences, for each group, across all 'daily' columns, and then store the output in each 'original' column?

Sample Data

df1 <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Variable = c("Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative"), Day1 = c("Sunday", "1", "1", "3", "3", NA, NA, "Sunday", "1", "1", "1", "1", NA, NA, "Sunday", "8", "8", "5", "5", NA, NA), Day2 = c("Monday", "4", "3", "7", "4", NA, NA, "Monday", "2", "1", "3", "2", NA, NA, "Monday", "17", "9", "10", "5", NA, NA), Day3 = c("Tuesday", "6", "2", "10", "3", NA, NA, "Tuesday", "3", "1", "4", "1", NA, NA, "Tuesday", "29", "12", "14", "4", NA, NA), Day4 = c("Wednesday", "11", "5", "12", "2", NA, NA, "Wednesday", "4", "1", "5", "1", NA, NA, "Wednesday", "32", "3", "17", "3", NA, NA)), row.names = c(NA, -21L), class = "data.frame")
df1

What I would like to do is fill  in the Diff.Daily cells in each "Day" column (i.e. Day1, Day2, etc.) by taking the difference between the Actual.Daily and Expected.Daily values for each Group (A, B, C), and then do similarly for Diff.Cumulative (i.e. Actual.Cumulative - Expected.Cumulative).

Desired Output

df2 <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Variable = c("Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative", "Day", "Actual.Cumulative", "Actual.Daily", "Expected.Cumulative", "Expected.Daily", "Diff.Daily", "Diff.Cumulative"), Day1 = c("Sunday", "1", "1", "3", "3", "-2", "-2", "Sunday", "1", "1", "1", "1", "0", "0", "Sunday", "8", "8", "5", "5", "3", "3"), Day2 = c("Monday", "4", "3", "7", "4", "-1", "-3", "Monday", "2", "1", "3", "2", "-1", "-1", "Monday", "17", "9", "10", "5", "4", "7"), Day3 = c("Tuesday", "6", "2", "10", "3", "-1", "-4", "Tuesday", "3", "1", "4", "1", "0", "-1", "Tuesday", "29", "12", "14", "4", "8", "15"), Day4 = c("Wednesday", "11", "5", "12", "2", "3", "-1", "Wednesday", "4", "1", "5", "1", "0", "-1", "Wednesday", "32", "3", "17", "3", "0", "15")), row.names = c(NA, -21L), class = "data.frame")
df2

Here you can see for Group A on Day 1, Diff.Daily = -2 as expected from Actual.Daily of 1 minus an Expected.Daily of 3.

My Attempts

As the "Day" columns are of character class because of their mixed nature, I know I need to wrap the calculations with as.numeric(), and I can calculate the values individually for each column:

Diff.Cumulative <- as.numeric(df1[df1$Variable == "Actual.Cumulative", "Day1"]) - as.numeric(df1[df1$Variable == "Expected.Cumulative", "Day1"])

But I'm struggling with how to expand this to all "Day" columns and to fit it into the current data frame structure. I came across a similar but ultimately different question.

Body:
Here's a way to do this with the help of a helper function.

library(dplyr)

change_values <- function(sub1, sub2, to, var, value) {
  x <- suppressWarnings(as.numeric(value))
  x[match(to, var)] <- x[match(sub1, var)] - x[match(sub2, var)]
  x[1] <- value[1]
  x
}

df1 %>%
  group_by(Group) %>%
  mutate(across(starts_with('Day'), ~change_values('Actual.Daily',
        'Expected.Daily', 'Diff.Daily', Variable, .)),
         across(starts_with('Day'), ~change_values('Actual.Cumulative',
        'Expected.Cumulative', 'Diff.Cumulative', Variable, .))) %>%
  ungroup

This returns -

#   Group            Variable   Day1   Day2    Day3      Day4
#1      A                 Day Sunday Monday Tuesday Wednesday
#2      A   Actual.Cumulative      1      4       6        11
#3      A        Actual.Daily      1      3       2         5
#4      A Expected.Cumulative      3      7      10        12
#5      A      Expected.Daily      3      4       3         2
#6      A          Diff.Daily     -2     -1      -1         3
#7      A     Diff.Cumulative     -2     -3      -4        -1
#8      B                 Day Sunday Monday Tuesday Wednesday
#9      B   Actual.Cumulative      1      2       3         4
#10     B        Actual.Daily      1      1       1         1
#11     B Expected.Cumulative      1      3       4         5
#12     B      Expected.Daily      1      2       1         1
#13     B          Diff.Daily      0     -1       0         0
#14     B     Diff.Cumulative      0     -1      -1        -1
#15     C                 Day Sunday Monday Tuesday Wednesday
#16     C   Actual.Cumulative      8     17      29        32
#17     C        Actual.Daily      8      9      12         3
#18     C Expected.Cumulative      5     10      14        17
#19     C      Expected.Daily      5      5       4         3
#20     C          Diff.Daily      3      4       8         0
#21     C     Diff.Cumulative      3      7      15        15


问:
Array with undefined size as Class-member
I'm searching for a way to define an array as a class-member with an undefined size (which will be defined on initialization).

```<code>class MyArrayOfInts {
    private:
        int[] array;    // should declare the array with an (yet) undefined length

    public:
        MyArrayOfInts(int);
        int Get(int);
        void Set(int, int);
};
MyArrayOfInts::MyArrayOfInts(int length) {
    this->array = int[length];  // defines the array here
}
int MyArrayOfInts::Get(int index) {
    return this->array[index];
}
void MyArrayOfInts:Set(int index, int value) {
    this->array[index] = value;
}
</code>```

How can I achieve this behaviour ?

答:
I'm working on this too for solving a dynamic array problem - I found the answer provided was sufficient to resolve.

This is tricky because arrays in functions from my reading do not continue after function ends, arrays have a lot of strange nuance, however if trying to make a dynamic array without being allowed to use a vector, I believe this is the best approach..

Other approaches such as calling new and delete upon the same pointed to array can/will lead to double free pending the compiler as it causes some undefined behavior.

```<code>class arrayObject
{
public:
arrayObject();
~arrayObject();
int   createArray(int firstArray[]);
void  getSize();
void  getValue();
void  deleting();
// private:
int *array;
int size;
int counter;
int number;
};

arrayObject::arrayObject()
{
this->array = new int[size];
}

arrayObject::~arrayObject()
{
delete [] this->array;
}
</code>```

Body:
I'm searching for a way to define an array as a class-member with an undefined size (which will be defined on initialization).

class MyArrayOfInts {
    private:
        int[] array;    // should declare the array with an (yet) undefined length

    public:
        MyArrayOfInts(int);
        int Get(int);
        void Set(int, int);
};
MyArrayOfInts::MyArrayOfInts(int length) {
    this->array = int[length];  // defines the array here
}
int MyArrayOfInts::Get(int index) {
    return this->array[index];
}
void MyArrayOfInts:Set(int index, int value) {
    this->array[index] = value;
}

How can I achieve this behaviour ?

Body:
I'm working on this too for solving a dynamic array problem - I found the answer provided was sufficient to resolve.

This is tricky because arrays in functions from my reading do not continue after function ends, arrays have a lot of strange nuance, however if trying to make a dynamic array without being allowed to use a vector, I believe this is the best approach..

Other approaches such as calling new and delete upon the same pointed to array can/will lead to double free pending the compiler as it causes some undefined behavior.

class arrayObject
{
public:
arrayObject();
~arrayObject();
int   createArray(int firstArray[]);
void  getSize();
void  getValue();
void  deleting();
// private:
int *array;
int size;
int counter;
int number;
};

arrayObject::arrayObject()
{
this->array = new int[size];
}

arrayObject::~arrayObject()
{
delete [] this->array;
}