问:
Live chart slowness
I am charting live data (ekg) from a vital sign monitor. The monitor outputs 500 data points per second which represent a single ekg waveform. I parse these in a backgroundWorker to display them in a chart without freezing the controls. The typical case lasts about an hour, which equals about 1.8 million data points that I have to display.

Here is the backgroundWorker code:

```<code>    private void BackgroundWorker1_DoWork (object sender, DoWorkEventArgs e) {
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.WorkerReportsProgress = true;
        if (backgroundWorker1.CancellationPending == true) {
            e.Cancel = true;
        }
        for (int i = 0; i <= 100; i++) {
            backgroundWorker1.ReportProgress(i);
            if (i % 25 == 1) {
                Thread.Sleep(500);
            }
        }
        try {
            Action action = () =>
            FillChartEKG();
            Invoke(action);

        }
        catch {
            backgroundWorker1.CancelAsync();
            MessageBox.Show("No EKG waveform data availaible to parse. Does your vital sign monitor support export of EKG wavedorm data?", "EKG waveform status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
</code>```

And here is the long running method that charts the EKG data points:

```<code>        public async void FillChartEKG() {
        List<AnesthWaveformData> waveformData = AnesthWaveformDatas.CreateWaveformObjects(anestheticRecordNum);
        var series1 = new Series {
            Name = "EKG",
            Color = Color.LawnGreen,
            IsVisibleInLegend = false,
            IsXValueIndexed = true,
            ChartType = SeriesChartType.Line,
        };
        chartEKG.Series.Clear();
        chartEKG.Series.Add(series1);
        string timeStamp = DateTime.Now.ToString();
        DateTime time = new DateTime();
        int counter = 0;
        int loopCount = 0;
        int loopToStopAt = 0;
        //await System.Threading.Tasks.Task.Run(() => {
            for (int j = 0; j < waveformData.Count; j++) {
                if (waveformData[j].EKGWaveform == String.Empty || waveformData[j].EKGWaveform.StartsWith("32767")) {
                    continue;
                }
                counter = counter + 1;  //there are 500 data points in each EKG waveform HL7 message; counter is the number of valid EKG waveforms in waveFormData
                try {
                    timeStamp = waveformData[j].VSTimeStamp + "000"; //get first VSTimeStamp in series
                    string format = "yyyyMMddHHmmssfff";
                    time = DateTime.ParseExact(timeStamp, format, CultureInfo.InvariantCulture);
                }
                catch { MessageBox.Show("No waveform data to display", "Waveform data status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
                string strEKG = String.Empty;
                strEKG = strEKG + "^" + string.Join("^", waveformData[j].EKGWaveform.ToString());
                strEKG = strEKG.Remove(0, 1); //remove leading ^
                string[] count = strEKG.Split('^');

                foreach (string point in count) {
                    try {
                        time = time.AddMilliseconds(2);
                        //await System.Threading.Tasks.Task.Run(() => {
                        chartEKG.Invoke(new Action(() => series1.Points.AddXY(time, Convert.ToDouble(point) * 0.61)));
                        //});
                    }
                    catch (ArgumentException) { }
                    loopCount = loopCount + 1;
                    string timeFormat = "yyyyMMddHHmmssfff";
                    string timeNow = DateTime.Now.ToString(timeFormat);
                    if (time == DateTime.ParseExact(DateTime.Now.ToString(timeNow), timeFormat, CultureInfo.InvariantCulture)) {
                        loopToStopAt = loopCount;
                    }
                }

                chartEKG.Invoke(new Action(() => chartEKG.ChartAreas[0].AxisX.Maximum = counter * 500));

            }
        //});
        chartEKG.Invoke(new Action(() => chartEKG.ChartAreas[0].AxisX.ScaleView.Scroll(chartEKG.ChartAreas[0].AxisX.Maximum - Convert.ToDouble(loopToStopAt))));

    }
</code>```

The problem is the chart draws reaalllly slowly. If I remove the async from the method it draws really rapidly (what I want) but freezes the GUI while the drawing is completing. I've tried adjusting the Thread.Sleep in the _DoWork eventhandler but doesn't make an appreciable difference in speed. Any suggestions are appreciated.

Here is a YouTube video that shows the output:

https://youtu.be/CmlIScjowFc

Thanks,

-Will

Title: Live chart slowness

Body:
I am charting live data (ekg) from a vital sign monitor. The monitor outputs 500 data points per second which represent a single ekg waveform. I parse these in a backgroundWorker to display them in a chart without freezing the controls. The typical case lasts about an hour, which equals about 1.8 million data points that I have to display.

Here is the backgroundWorker code:

    private void BackgroundWorker1_DoWork (object sender, DoWorkEventArgs e) {
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.WorkerReportsProgress = true;
        if (backgroundWorker1.CancellationPending == true) {
            e.Cancel = true;
        }
        for (int i = 0; i <= 100; i++) {
            backgroundWorker1.ReportProgress(i);
            if (i % 25 == 1) {
                Thread.Sleep(500);
            }
        }
        try {
            Action action = () =>
            FillChartEKG();
            Invoke(action);

        }
        catch {
            backgroundWorker1.CancelAsync();
            MessageBox.Show("No EKG waveform data availaible to parse. Does your vital sign monitor support export of EKG wavedorm data?", "EKG waveform status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }

And here is the long running method that charts the EKG data points:

        public async void FillChartEKG() {
        List<AnesthWaveformData> waveformData = AnesthWaveformDatas.CreateWaveformObjects(anestheticRecordNum);
        var series1 = new Series {
            Name = "EKG",
            Color = Color.LawnGreen,
            IsVisibleInLegend = false,
            IsXValueIndexed = true,
            ChartType = SeriesChartType.Line,
        };
        chartEKG.Series.Clear();
        chartEKG.Series.Add(series1);
        string timeStamp = DateTime.Now.ToString();
        DateTime time = new DateTime();
        int counter = 0;
        int loopCount = 0;
        int loopToStopAt = 0;
        //await System.Threading.Tasks.Task.Run(() => {
            for (int j = 0; j < waveformData.Count; j++) {
                if (waveformData[j].EKGWaveform == String.Empty || waveformData[j].EKGWaveform.StartsWith("32767")) {
                    continue;
                }
                counter = counter + 1;  //there are 500 data points in each EKG waveform HL7 message; counter is the number of valid EKG waveforms in waveFormData
                try {
                    timeStamp = waveformData[j].VSTimeStamp + "000"; //get first VSTimeStamp in series
                    string format = "yyyyMMddHHmmssfff";
                    time = DateTime.ParseExact(timeStamp, format, CultureInfo.InvariantCulture);
                }
                catch { MessageBox.Show("No waveform data to display", "Waveform data status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
                string strEKG = String.Empty;
                strEKG = strEKG + "^" + string.Join("^", waveformData[j].EKGWaveform.ToString());
                strEKG = strEKG.Remove(0, 1); //remove leading ^
                string[] count = strEKG.Split('^');

                foreach (string point in count) {
                    try {
                        time = time.AddMilliseconds(2);
                        //await System.Threading.Tasks.Task.Run(() => {
                        chartEKG.Invoke(new Action(() => series1.Points.AddXY(time, Convert.ToDouble(point) * 0.61)));
                        //});
                    }
                    catch (ArgumentException) { }
                    loopCount = loopCount + 1;
                    string timeFormat = "yyyyMMddHHmmssfff";
                    string timeNow = DateTime.Now.ToString(timeFormat);
                    if (time == DateTime.ParseExact(DateTime.Now.ToString(timeNow), timeFormat, CultureInfo.InvariantCulture)) {
                        loopToStopAt = loopCount;
                    }
                }

                chartEKG.Invoke(new Action(() => chartEKG.ChartAreas[0].AxisX.Maximum = counter * 500));

            }
        //});
        chartEKG.Invoke(new Action(() => chartEKG.ChartAreas[0].AxisX.ScaleView.Scroll(chartEKG.ChartAreas[0].AxisX.Maximum - Convert.ToDouble(loopToStopAt))));

    }

The problem is the chart draws reaalllly slowly. If I remove the async from the method it draws really rapidly (what I want) but freezes the GUI while the drawing is completing. I've tried adjusting the Thread.Sleep in the _DoWork eventhandler but doesn't make an appreciable difference in speed. Any suggestions are appreciated.

Here is a YouTube video that shows the output:

https://youtu.be/CmlIScjowFc

Thanks,

-Will


来源: stackexchange

问:
Twitter API + OPENAI API status paramater not being passed into tweet function with tweepy API
for whatever reason, I can not convert the dictionary key that returns for response, into a string variable called tweetinpu that I can then run through my tweet function. I keep getting an error that the 'status' parameter has no value, when it should be the tweetinput string value generated by the api.

```<code>
`#!/bin/python3
import tweepy
import keys
import openai

openai.api_key = ('JUSTHIDINGMYREALKEY')

response = openai.Completion.create(
    model="text-davinci-003",
    prompt="Create an inspiring tweet",
    temperature=0,
    max_tokens=150,
    top_p=1.0,
    frequency_penalty=0.2,
    presence_penalty=0.0,
    stop=["\n"]
)

tweetinput = response["choices"][0]["text"]

def api():
    auth = tweepy.OAuthHandler(keys.api_key, keys.api_secret)
    auth.set_access_token(keys.access_token, keys.access_token_secret)

    return tweepy.API(auth)

def tweet(api: tweepy.API, message: str):
    api.update_status(message)

    print('Tweeted successfully!')

if __name__ == '__main__':
    api = api()
    tweet(api, tweetinput)`

</code>```

`

```<code></code>```

ContentLicense: CC BY-SA 4.0

Body:
for whatever reason, I can not convert the dictionary key that returns for response, into a string variable called tweetinpu that I can then run through my tweet function. I keep getting an error that the 'status' parameter has no value, when it should be the tweetinput string value generated by the api.

`#!/bin/python3
import tweepy
import keys
import openai

openai.api_key = ('JUSTHIDINGMYREALKEY')

response = openai.Completion.create(
    model="text-davinci-003",
    prompt="Create an inspiring tweet",
    temperature=0,
    max_tokens=150,
    top_p=1.0,
    frequency_penalty=0.2,
    presence_penalty=0.0,
    stop=["\n"]
)

tweetinput = response["choices"][0]["text"]

def api():
    auth = tweepy.OAuthHandler(keys.api_key, keys.api_secret)
    auth.set_access_token(keys.access_token, keys.access_token_secret)

    return tweepy.API(auth)

def tweet(api: tweepy.API, message: str):
    api.update_status(message)

    print('Tweeted successfully!')

if __name__ == '__main__':
    api = api()
    tweet(api, tweetinput)`

`


问:
Spring security, session concurrency control, expired-url cached in browser
There's configuration for Spring concurrent session control:

```<code><sec:session-management>
  <sec:concurrency-control max-sessions="1" expired-url="/error/concurrency" session-registry-alias="sessionRegistry" />
</sec:session-management>
</code>```

When I log into the application using two different browsers and then in first browser click some link requested url is redirected to the expired-url set into config. So far so good.

If I log in again into first browser and click link previously performed, expired url is retrieved from browser cache and error page displayed again instead original one. If I check disable cache in browser's developer tool original page finally appear.

There is no Cache-Control attribute into response header so the problem is how to set no-cache, no-store etc. in order to prevent browser caching when concurrency redirection occur.

I tried adding <sec:cache-control/> into <sec:headers> but without any success. I can see there is a Cache-Control header attribute for other spring security urls. Wondering why it doesn't exist in case of concurrency exceed exception.

Body:
There's configuration for Spring concurrent session control:

<sec:session-management>
  <sec:concurrency-control max-sessions="1" expired-url="/error/concurrency" session-registry-alias="sessionRegistry" />
</sec:session-management>

When I log into the application using two different browsers and then in first browser click some link requested url is redirected to the expired-url set into config. So far so good.

If I log in again into first browser and click link previously performed, expired url is retrieved from browser cache and error page displayed again instead original one. If I check disable cache in browser's developer tool original page finally appear.

There is no Cache-Control attribute into response header so the problem is how to set no-cache, no-store etc. in order to prevent browser caching when concurrency redirection occur.

I tried adding <sec:cache-control/> into <sec:headers> but without any success. I can see there is a Cache-Control header attribute for other spring security urls. Wondering why it doesn't exist in case of concurrency exceed exception.


问:
How to solve **TypeError : expected str, bytes or os.PathLike object, not WindowsPath** when importing matplotlib to python
I am trying use matplotlib within Autodesk Revit software from the PyRevit Project
In this project, Pyrevit brings an embedded CPython interpreter (3.8.5) to Revit.
Until now, I've managed to import some packages (e.g. numpy, pandas), but unfortunately import matplotlib has been a big challenge.

When I try to import matplotlib, I got the following error:

```<code>CPython Traceback:
TypeError : expected str, bytes or os.PathLike object, not WindowsPath
File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 886, in <module>
 rcParamsDefault = _rc_params_in_file(
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 789, in _rc_params_in_file
 with _open_file_or_url(fname) as fd:
 File "contextlib.py", line 113, in __enter__
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 765, in _open_file_or_url
 fname = os.path.expanduser(fname)
 File "ntpath.py", line 293, in expanduser
</code>```

...\matplotlib_init_.py

File ntpath.py

Doing the same, import matplotlib, from the Python 3.8.5 in the command line it works without any problem.
enter image description here

Thank you in advance for any suggestion from your side to solve this issue.

Body:
I am trying use matplotlib within Autodesk Revit software from the PyRevit Project
In this project, Pyrevit brings an embedded CPython interpreter (3.8.5) to Revit.
Until now, I've managed to import some packages (e.g. numpy, pandas), but unfortunately import matplotlib has been a big challenge.

When I try to import matplotlib, I got the following error:

CPython Traceback:
TypeError : expected str, bytes or os.PathLike object, not WindowsPath
File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 886, in <module>
 rcParamsDefault = _rc_params_in_file(
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 789, in _rc_params_in_file
 with _open_file_or_url(fname) as fd:
 File "contextlib.py", line 113, in __enter__
 File "C:\Users\carlo\pyproj\bimenv\Lib\site-packages\matplotlib\__init__.py", line 765, in _open_file_or_url
 fname = os.path.expanduser(fname)
 File "ntpath.py", line 293, in expanduser

...\matplotlib_init_.py

File ntpath.py

Doing the same, import matplotlib, from the Python 3.8.5 in the command line it works without any problem.
enter image description here

Thank you in advance for any suggestion from your side to solve this issue.


问:
How to dynamically split the dataframe based on column count in pandas?
I am trying to read an excel file with around 780 columns. Once I have read it, I want to split the dataframes dynamically based on the column count and insert it into sql table. As for now, I am able to do it by adding the dataframe manually inside a function. For example, if I want to split it by 250 columns, then I need to create dt variable 4 times to insert into a table.

How do I make it dynamically where it will split the dataframes based on the column count inside the excel file? Below is my code:

```<code> def sqlcol(dfparam):
     dtypedict = {}
     for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqla.types.NVARCHAR(length=255)})

        if "datetime" in str(j):
            dtypedict.update({i: sqla.types.DateTime()})

        if "float" in str(j):
           dtypedict.update({i: sqla.types.Float()})

        if "int" in str(j):
           dtypedict.update({i: sqla.types.BIGINT()})

        if "decimal" in str(j):
           dtypedict.update({i: sqla.types.DECIMAL()})

    return dtypedict

def import_varchar_to_hst03(db:str,tb_name:str,df):
    n= 1

    import pandas as pd
    import sqlalchemy as sqla
    import urllib
    import pyodbc
    t=sqlcol(df1)
    a=sqlcol(df2)
    c=sqlcol(df3)
    quoted = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE="+db+";Trusted_Connection=yes;")
engine = sqla.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), fast_executemany = True)
    df1.to_sql(tb_name, schema='dbo', con = engine, index=False,dtype=t,if_exists='replace')
    df2.to_sql(tb_name + ( "A" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')
    df3.to_sql(tb_name + ( "B" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')

import pandas as pd
import numpy as np

Ex=pd.read_excel(r'C:\Users\sriram.ramasamy\Desktop\Testsriram.xlsx',sheet_name=None)

for sh,v in Ex.items():
    df=pd.DataFrame(v)
    df1 = df.iloc[:,:255]
    df2 = df.iloc[:,np.r_[0:1,256:500]]
    df3 = df.iloc[:,np.r_[0:1,501:700]]
    import_varchar_to_hst03('InsightMaster',sh,df)

print('data imported to database')
</code>```

Body:
I am trying to read an excel file with around 780 columns. Once I have read it, I want to split the dataframes dynamically based on the column count and insert it into sql table. As for now, I am able to do it by adding the dataframe manually inside a function. For example, if I want to split it by 250 columns, then I need to create dt variable 4 times to insert into a table.

How do I make it dynamically where it will split the dataframes based on the column count inside the excel file? Below is my code:

 def sqlcol(dfparam):
     dtypedict = {}
     for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqla.types.NVARCHAR(length=255)})

        if "datetime" in str(j):
            dtypedict.update({i: sqla.types.DateTime()})

        if "float" in str(j):
           dtypedict.update({i: sqla.types.Float()})

        if "int" in str(j):
           dtypedict.update({i: sqla.types.BIGINT()})

        if "decimal" in str(j):
           dtypedict.update({i: sqla.types.DECIMAL()})

    return dtypedict

def import_varchar_to_hst03(db:str,tb_name:str,df):
    n= 1

    import pandas as pd
    import sqlalchemy as sqla
    import urllib
    import pyodbc
    t=sqlcol(df1)
    a=sqlcol(df2)
    c=sqlcol(df3)
    quoted = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE="+db+";Trusted_Connection=yes;")
engine = sqla.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted), fast_executemany = True)
    df1.to_sql(tb_name, schema='dbo', con = engine, index=False,dtype=t,if_exists='replace')
    df2.to_sql(tb_name + ( "A" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')
    df3.to_sql(tb_name + ( "B" * n), schema='dbo', con = engine, index=False,dtype=a,if_exists='replace')

import pandas as pd
import numpy as np

Ex=pd.read_excel(r'C:\Users\sriram.ramasamy\Desktop\Testsriram.xlsx',sheet_name=None)

for sh,v in Ex.items():
    df=pd.DataFrame(v)
    df1 = df.iloc[:,:255]
    df2 = df.iloc[:,np.r_[0:1,256:500]]
    df3 = df.iloc[:,np.r_[0:1,501:700]]
    import_varchar_to_hst03('InsightMaster',sh,df)

print('data imported to database')


问:
Finding exact match with equal sign with append function in SQL
sqlQueryString.append(" and upper(username) like upper(:searchString) ");

This code returns data like exampleusername, exampleusername1, exampleusername12...

I want it to return data with an exact match to the username that is being searched.

For example when I put in bobJacobs (an example username), I want it to return only bobJacobs records, not other records that may contain bobJacobs in them, for example samandbobJacobs24, bobJacobs23, etc.

I've tried:
sqlQueryString.append(" and upper(username) = upper(:searchString) ");

But it doesn't work. Any solutions?


问:
Delayed Unauthorized responses from AKS
We use AKS's kube-apiserver for leader-election from a VM, external to k8s cluster but in the same VNET. We use a k8s client from the client-go package. The client tries to get/update the lease object every 2 sec. We observe occasional failures (every few hours) caused by delayed "Unauthorized" responses. The client-go HTTP client refreshes creds/tokens when it receives an Unauthorized response. However, when the Unauthorized response is extremely delayed (sometimes up to 30 sec!), the timeouts of HTTP client or leader-election mechanism kick in.
We could tune the HTTP client and leader-election timeouts but we do need a fast failover (e.g., up to 30 sec), so it would be great to eliminate these delays.
What is the reason these Unauthorized responses get so delayed?</p>

Title: Delayed Unauthorized responses from AKS


问:
PineScript won't compile this code for a trading indicator
I want to make a Trading Indicator for TradingView which does the following:
If there are at least three consecutive candles making a higher low in an uptrend and the following candle breaking the previous low AND the previous high, it should draw a green circle around the low. The exact opposite should happen in a downtrend but with a red circle around the high.

The code won't compile, does anyone have a fix for this?
(Please go easy on me I just got into PineScript)

```<code>//@version=4
study("MiniLQ")
// Version 1.0

// Define variables for trend direction and consecutive candle count
trendDirection = 0
consecCandleCount = 0

// Define a function to reset the consecutive candle count and trend direction
resetTrend() =>
    consecCandleCount = 0
    trendDirection = 0

// Define a function to draw circles around the relevant candles
drawCircle(direction, high, low) =>
    if direction == 1
        plot(high, color=red, style=circles, linewidth=5)
    else
        plot(low, color=green, style=circles, linewidth=5)

// Main loop to check for consecutive candles and reversal candles
for i = 1 to bar_count - 1
    // Check if current candle has higher low than previous and we are in an uptrend
    if low[i] > low[i - 1] and trendDirection == 1
        consecCandleCount = consecCandleCount + 1
        // Check if current candle is a reversal candle after 3 consecutive candles
        if low[i] < low[i + 1] and high[i] > high[i + 1] and consecCandleCount >= 3
            drawCircle(trendDirection, high[i + 1], low[i + 1])
            resetTrend()
    // Check if current candle has lower high than previous and we are in a downtrend
    else if high[i] < high[i - 1] and trendDirection == -1
        consecCandleCount = consecCandleCount + 1
        // Check if current candle is a reversal candle after 3 consecutive candles
        if high[i] > high[i + 1] and low[i] < low[i + 1] and consecCandleCount >= 3
            drawCircle(trendDirection, high[i + 1], low[i + 1])
            resetTrend()
    // If current candle does not match trend, reset trend and consecutive candle count
    else
        resetTrend()

// Set initial trend direction based on first candle
trendDirection := low[1] > low[0] ? 1 : -1

</code>```

Body:
I want to make a Trading Indicator for TradingView which does the following:
If there are at least three consecutive candles making a higher low in an uptrend and the following candle breaking the previous low AND the previous high, it should draw a green circle around the low. The exact opposite should happen in a downtrend but with a red circle around the high.

The code won't compile, does anyone have a fix for this?
(Please go easy on me I just got into PineScript)

//@version=4
study("MiniLQ")
// Version 1.0

// Define variables for trend direction and consecutive candle count
trendDirection = 0
consecCandleCount = 0

// Define a function to reset the consecutive candle count and trend direction
resetTrend() =>
    consecCandleCount = 0
    trendDirection = 0

// Define a function to draw circles around the relevant candles
drawCircle(direction, high, low) =>
    if direction == 1
        plot(high, color=red, style=circles, linewidth=5)
    else
        plot(low, color=green, style=circles, linewidth=5)

// Main loop to check for consecutive candles and reversal candles
for i = 1 to bar_count - 1
    // Check if current candle has higher low than previous and we are in an uptrend
    if low[i] > low[i - 1] and trendDirection == 1
        consecCandleCount = consecCandleCount + 1
        // Check if current candle is a reversal candle after 3 consecutive candles
        if low[i] < low[i + 1] and high[i] > high[i + 1] and consecCandleCount >= 3
            drawCircle(trendDirection, high[i + 1], low[i + 1])
            resetTrend()
    // Check if current candle has lower high than previous and we are in a downtrend
    else if high[i] < high[i - 1] and trendDirection == -1
        consecCandleCount = consecCandleCount + 1
        // Check if current candle is a reversal candle after 3 consecutive candles
        if high[i] > high[i + 1] and low[i] < low[i + 1] and consecCandleCount >= 3
            drawCircle(trendDirection, high[i + 1], low[i + 1])
            resetTrend()
    // If current candle does not match trend, reset trend and consecutive candle count
    else
        resetTrend()

// Set initial trend direction based on first candle
trendDirection := low[1] > low[0] ? 1 : -1


问:
How to get all commits that originated in a branch, from the GitLab API?
I am currently using the API to get all of the commits from the master branch like this:

```<code>https://gitlab.com/api/v4/projects/${projectID}/repository/commits?ref=master&per_page=50&page=1
</code>```

This works well except it's returning commits which didn't originate in the master branch, and then were committed to the master branch.

If I use the graph view in GitLab, this becomes quite clear: GraphView

It helps illustrate what I am interested in polling. Red is the master branch, and the green paths coming off of it were other various branches I created and merged back in. I want to receive a response with each of the commits that are red dots in this image I attached. I don't care for the green dots, or any other dot that was originating from outside of the master branch.

If anyone can help me understand how I can either:

Get a list of commits similar to what I'd described above using the GitLab API

Filter the commits from the repository/commits request to only show the ones which originated in the master branch, using the GitLab API

I would very much appreciate it! Thank you,

David

I tried adding ?ref=master to the API request to filter to the master branch, but it shows the parent commits of merged branches as being in master. This is fine, I get that this is probably the expected behaviour. I am just looking for a solution,

Body:
I am currently using the API to get all of the commits from the master branch like this:

https://gitlab.com/api/v4/projects/${projectID}/repository/commits?ref=master&per_page=50&page=1

This works well except it's returning commits which didn't originate in the master branch, and then were committed to the master branch.

If I use the graph view in GitLab, this becomes quite clear: GraphView

It helps illustrate what I am interested in polling. Red is the master branch, and the green paths coming off of it were other various branches I created and merged back in. I want to receive a response with each of the commits that are red dots in this image I attached. I don't care for the green dots, or any other dot that was originating from outside of the master branch.

If anyone can help me understand how I can either:

Get a list of commits similar to what I'd described above using the GitLab API

Filter the commits from the repository/commits request to only show the ones which originated in the master branch, using the GitLab API

I would very much appreciate it! Thank you,

David

I tried adding ?ref=master to the API request to filter to the master branch, but it shows the parent commits of merged branches as being in master. This is fine, I get that this is probably the expected behaviour. I am just looking for a solution,


问:
Using Queryselector to retrieve data from #document
I am new in using querySelector and I am stuck with a piece of html including a #document part. As you can see in the image, I got up to the iframe part by using a long string of querySelectors. Now I would need to proceed into the #document part, but I have no idea how to access it.

I would need the next part of the code so I can access the next html part:
....querySelector('iframe').querySelector('?#document?')?.querySelector(...)


问:
Not able to apply styles on Marker- React simple map
I'm attempting to style markers to my map, but nothing works.

```<code>const geoUrl = "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json";

const MapChart = () => {
return (
<ComposableMap projection="geoAlbersUsa">
      <Geographies geography={geoUrl}>
        {({ geographies }) => (
          <>
            {geographies.map(geo => (
              <Geography
                key={geo.rsmKey}
                stroke="#FFF"
                geography={geo}
                fill="#DDD"
              />
            ))}
          </>
        )}
      </Geographies>
      {airports.map((item, index) => {
           return <Marker key={index} coordinates={[marker.LONGITUDE, marker.LATITUDE]} onClick={handleClick.bind(this, marker)}

           style={{
                cursor: "pointer"
                default: { fill: "#06F" },
                hover: { fill: "#000" },
                pressed: { fill: "#02A" },
              }}
            >
              <circle r={5} fill="#F53" />
              </Marker>

      })}

    </ComposableMap>
)}
</code>```

The style part is not effective on the markers at all.
What I'm I missing?

Body:
I'm attempting to style markers to my map, but nothing works.

const geoUrl = "https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json";

const MapChart = () => {
return (
<ComposableMap projection="geoAlbersUsa">
      <Geographies geography={geoUrl}>
        {({ geographies }) => (
          <>
            {geographies.map(geo => (
              <Geography
                key={geo.rsmKey}
                stroke="#FFF"
                geography={geo}
                fill="#DDD"
              />
            ))}
          </>
        )}
      </Geographies>
      {airports.map((item, index) => {
           return <Marker key={index} coordinates={[marker.LONGITUDE, marker.LATITUDE]} onClick={handleClick.bind(this, marker)}

           style={{
                cursor: "pointer"
                default: { fill: "#06F" },
                hover: { fill: "#000" },
                pressed: { fill: "#02A" },
              }}
            >
              <circle r={5} fill="#F53" />
              </Marker>

      })}

    </ComposableMap>
)}

The style part is not effective on the markers at all.
What I'm I missing?


问:
Function adds "blank" 'option' into 'select' aside from the wanted 'option'
I have an big array of objects. I took all of the unique studentNames and put them into another array.

```<code>const unique = [...new Set(allStudentData.map(item => item.studentName))];
console.log(unique)
</code>```

And the console log gives me the correct output for that

The problem is as follows. I have created a 'select' and I want to push these names into the 'select' as 'options'.

It gives me the unique names as 'option'. But it also gives me a "blank" option after each name that seems to have the value of all names.

Here u can see the good 'option' and the "blank" ones

This is what happens when I click on "Evelyn", other names work as well

This is what happens when I click on a "blank", it sees it like all of the names.

Heres the code for adding the 'options'

```<code>const sss=
    <select id='sel' value={picked} onChange={x=>setPicked(x.target.value)}>
                <option disabled selected>Select a student</option>
    </select>

function Addsss(){
  useEffect(()=>
    unique.forEach(x=>{
       document.getElementById('sel').innerHTML += '<option value="' + x + '">' + x + "<option/>"
    }));
  }
</code>```

I was expecting the output to be like in the 2nd picture but without the "blanks".
And I havent mentioned it yet  but I am using React.js,

Body:
I have an big array of objects. I took all of the unique studentNames and put them into another array.

const unique = [...new Set(allStudentData.map(item => item.studentName))];
console.log(unique)

And the console log gives me the correct output for that

The problem is as follows. I have created a 'select' and I want to push these names into the 'select' as 'options'.

It gives me the unique names as 'option'. But it also gives me a "blank" option after each name that seems to have the value of all names.

Here u can see the good 'option' and the "blank" ones

This is what happens when I click on "Evelyn", other names work as well

This is what happens when I click on a "blank", it sees it like all of the names.

Heres the code for adding the 'options'

const sss=
    <select id='sel' value={picked} onChange={x=>setPicked(x.target.value)}>
                <option disabled selected>Select a student</option>
    </select>

function Addsss(){
  useEffect(()=>
    unique.forEach(x=>{
       document.getElementById('sel').innerHTML += '<option value="' + x + '">' + x + "<option/>"
    }));
  }

I was expecting the output to be like in the 2nd picture but without the "blanks".
And I havent mentioned it yet  but I am using React.js,


问:
How to prevent Tauri app from opening remote links
I made a Tauri Hello world app, using react-ts, and that contained logos for Tauri, Vite,  and React, that are clickable of course, it uses an a HTML tag like href="https://vitejs.dev" target="_blank">, which if I click on it, opens a new tab in my default browser that loads that URL.

So naturally, I wanted to test if Tauri apps would open that link (or any other remote URL actually) inside the app's webview, so I changed that to href="https://vitejs.dev"> which did just that.

What I want to know is: how to configure any Tauri app to not open / load any URLs unless I specifically allow it to?

What I tried already:

I tried changing the CSP option in the tauri.conf.json file to none to not allow any remote scripts or ....

```<code>"security": {
      "csp": {
        "default-src": ["'none'"]
      }
    },
</code>```

I also tried searching for some kind of allowed-navigation option that someone talked about

I also started looking into a before-navigate hook in the main.rs file but i don't know how to implement it

I would really appreciate it if you explain how to reach my objective, and I would be even more indebted to you if you can give me same better options or the ones more appropriate for a production ready app.

Regards,

zk.

Body:
I made a Tauri Hello world app, using react-ts, and that contained logos for Tauri, Vite,  and React, that are clickable of course, it uses an a HTML tag like , which if I click on it, opens a new tab in my default browser that loads that URL.

So naturally, I wanted to test if Tauri apps would open that link (or any other remote URL actually) inside the app's webview, so I changed that to  which did just that.

What I want to know is: how to configure any Tauri app to not open / load any URLs unless I specifically allow it to?

What I tried already:

I tried changing the CSP option in the tauri.conf.json file to none to not allow any remote scripts or ....

"security": {
      "csp": {
        "default-src": ["'none'"]
      }
    },

I also tried searching for some kind of allowed-navigation option that someone talked about

I also started looking into a before-navigate hook in the main.rs file but i don't know how to implement it

I would really appreciate it if you explain how to reach my objective, and I would be even more indebted to you if you can give me same better options or the ones more appropriate for a production ready app.

Regards,

zk.


问:
How to run a shell script with composer.json for a pre-commit git hook
I am using composer-git-hooks.
Anything I'll add to pre-commit array would be copied to .git/hooks/pre-commit

```<code>"extra": {
    "hooks": {
        "pre-commit": ['./pre_commit_hook_shell.sh']
    }
}
</code>```

Since my shell command is rather large and wouldn't look to good in the json file, I decided to have it in a separate file (pre_commit_hook_shell.sh which sits in the root of the project), yet nothing is being copied into .git/hooks/pre-commit.

I doubt I'm the only one trying to go at it this way and after investing time searching around for this issue and also looking into the source code of the package, I couldn't find a solution.

This is my new work account I just opened but I'll set the correct answer as an answer so you won't waste your time.
Thank you.

Body:
I am using composer-git-hooks.
Anything I'll add to pre-commit array would be copied to .git/hooks/pre-commit

"extra": {
    "hooks": {
        "pre-commit": ['./pre_commit_hook_shell.sh']
    }
}

Since my shell command is rather large and wouldn't look to good in the json file, I decided to have it in a separate file (pre_commit_hook_shell.sh which sits in the root of the project), yet nothing is being copied into .git/hooks/pre-commit.

I doubt I'm the only one trying to go at it this way and after investing time searching around for this issue and also looking into the source code of the package, I couldn't find a solution.

This is my new work account I just opened but I'll set the correct answer as an answer so you won't waste your time.
Thank you.


问:
Configure iRedMail to use Mysql instaed of MariaDB on Debian 10
I have a development server with Mysql. I need mysql specifically as I have used the C++ connector API extensively in my code and this API does not work with MariaDB. I need to install a very secure, easily configurable mail server on this server and have chosen to install iRedMail. The thing is, on Buster, mysql gets replaced by MariaDB when you run the iRedMail install script.
Is there a way to configure iRedMail to run with a mysql backend?

I have tried the following tutorial:
https://docs.iredmail.org/install.iredmail.with.remote.mysql.server.html

It did not work. That is the only one I have found.


问:
How to stream a dynamically created tar archive to a browser client as a single file download?
I am creating a server application to transfer many (could be 100+GB) files from discrete servers as a single tar archive to a browser client via a simple single file download.

Currently I settled on streaming in each file to the main server handling the web app's HTTP request, adding it to a dynamically created tar archive, and then streaming out the archive as it's created using chunked transfer encoding.

This works nicely but has 2 main downsides:

No download progress indicator for the browser client/user

Difficult to resume a failed/interrupted download

I'm looking for advice for either different techniques to implement this app or ways to address the shortcomings above.  Some of the constraints are that since the archive is generated on the fly, the server doesn't know exactly how large the final result will be (it does have a rough idea since it is not compressed currently, it's just total(file_size + file_padding), maybe this could be determined?).  And there is limited disk space available on the server along with limited memory on server & client so the download needs to occur in a streaming fashion; ie not storing it all in-memory or on-disk on server or client before writing it out to client's disk.

I've thought about implementing this by having the browser download chunks of known size and writing it out to a file as it goes, but it's not clear to me that this can be done with today's filesystem access limitations? And also without holding the entire archive in-memory on the client side.  Aand also while presenting it as a single download to the user instead of n separate downloads.  Kept running into hiccups like this so wanted to see what y'all think

Thanks for your help :)


问:
LTM Load Balancer drops connection while App waiting for big SQL query response
Newly implemented LTM Load Balancer drops connection while our App is waiting for big SQL query response.

Now I need to find some workaround because apparently extending timeouts on LB is not a way to go.

App runs on Django and MSSQL

Is there any possibility to lets say:

send query to DB

get some kind of transaction ID (JWT?)

close connection

create GET with some transaction ID to check if there is result of this query? (Not sure how this transaction ID would be stored on DB side though)

Is pagination doing something like this?

I would like to avoid making this like this:

Create API endpoint which runs queries to DB

Send request to API

DB process with query and put results in new table

send query to new table


问:
File Opening - Script still finds file in cwd even when absolute path specified
I have looked at How to open a list of files in Python This problem similar but not covered.

```<code>path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []

for f in files:
    fileNames.append(f)

for fileName in fileNames:
    pathFileName = path + fileName
    print(f"This is the path: {pathFileName}")
    fin = open(pathFileName, 'rt')

    texts = []

    with open(fileName) as file_in:
        # read file text lines into an array
        for text in file_in:
            texts.append(text)

        for text in texts:
            print(text)
</code>```

The file aaaatest.txt is in C:\test\test5 The output is:

```<code>This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'
</code>```

So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:

```<code>This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'
</code>```

The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again.
Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?

Body:
I have looked at How to open a list of files in Python This problem similar but not covered.

path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []

for f in files:
    fileNames.append(f)

for fileName in fileNames:
    pathFileName = path + fileName
    print(f"This is the path: {pathFileName}")
    fin = open(pathFileName, 'rt')

    texts = []

    with open(fileName) as file_in:
        # read file text lines into an array
        for text in file_in:
            texts.append(text)

        for text in texts:
            print(text)

The file aaaatest.txt is in C:\test\test5 The output is:

This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'

So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:

This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'

The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again.
Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?


问:
Has Chrome's temporary "Lax + POST" behaviour been removed?
I am troubleshooting a bug that involves a cookie that is sometimes missing from a cross-site POST request.

This page from The Chromium Projects (last updated Mar 18, 2021) describes a temporary intervention to SameSite cookie behaviour, whereby some cookies have a 2-minute window for certain top-level cross-site POST requests.

It is referred to as "Lax+POST".

It describes that this behaviour as a temporary intervention which would be removed.
I cannot find any reference that says it has been removed, nor any updates within the last year.

Is this 2-minute behaviour still in place today (Dec 16, 2022) ?


问:
What are common GIS filters that would be used in a spreadsheet-like interface
I have a spreadsheet-like application where a column may be a GEOGRAPPHY type, for example something like POINT(1 1). I haven't used GIS too much personally, and so was curious what is the most common filter that someone might apply to a GEO column. Giving a basic comparison, in Excel on a TEXT column, I would most commonly do something like =value, displaying the available values in a list of checkboxes:

My thought having zero experience other than using things like Google Maps or Kayak is that a user may want to see something like:

Value within [Distance] [units] of [Place]

For example, "Point is within 10 miles of Chicago, Illinois". And the reverse would be "outside of". Is this the most popular filter type, or are there others that are used frequently?


问:
How to check if conditional rendering is shown after selecting an option from a select list with React Testing Library?
I'm trying to test my component that has the following conditional rendering:

```<code>const MyComponent = () => {
  const [isVisible, setIsVisible] = (false);
  if(selectedOption == 'optionOne')
      setIsVisible(true);
  else
      setIsVisible(false);

  return (
    <div>
      <Select data-testid="select1" selectedOption={selectedOption} />
      {isVisible ? <Select data-testid="select2" selectedOption={anotherSelectedOption} /> : null }
    </div>
)}
</code>```

If selectedOption in select1 is 'optionOne', then select2 shows up.

Here is how I am testing it:

```<code>describe('Testing', () => {
  let container: ElementWrapper<HTMLElement>;
  const testState = {
  userChoice1: {
    selectedOption: ['optionOne'],
  },
  userChoice2: {
    selectedOption: ['test1', 'test2'],
  },
} as AppState;

beforeEach(() => {
  container = render(<MyComponent/>, testState);
});

it('should show select2 if optionOne is selected', async () => {
   const { getByTestId, getAllByTestId } = render(<MyComponent/>);
   expect(container.find('span').getElement().textContent).toBe("optionOne"); // this successfully finds select1 with optionOne selected, all good
   await screen.findAllByTestId('select2')
   expect(screen.getAllByTestId('select2')).toBeInTheDocument();
  });
</code>```

In the testing above, as select1 has optionOne selected, I expect to select2 to show up. However, I am getting an error Unable to find an element by: [data-testid="select2"]. It also returns the whole HTML body, where I see select1 element with optionOne selected, but no select2 at all as it seems to still be hidden.

What am I missing here? How can I unhide select2 within the unit test?

Body:
I'm trying to test my component that has the following conditional rendering:

const MyComponent = () => {
  const [isVisible, setIsVisible] = (false);
  if(selectedOption == 'optionOne')
      setIsVisible(true);
  else
      setIsVisible(false);

  return (

      <Select data-testid="select1" selectedOption={selectedOption} />
      {isVisible ? <Select data-testid="select2" selectedOption={anotherSelectedOption} /> : null }

)}

If selectedOption in select1 is 'optionOne', then select2 shows up.

Here is how I am testing it:

describe('Testing', () => {
  let container: ElementWrapper<HTMLElement>;
  const testState = {
  userChoice1: {
    selectedOption: ['optionOne'],
  },
  userChoice2: {
    selectedOption: ['test1', 'test2'],
  },
} as AppState;

beforeEach(() => {
  container = render(<MyComponent/>, testState);
});

it('should show select2 if optionOne is selected', async () => {
   const { getByTestId, getAllByTestId } = render(<MyComponent/>);
   expect(container.find('span').getElement().textContent).toBe("optionOne"); // this successfully finds select1 with optionOne selected, all good
   await screen.findAllByTestId('select2')
   expect(screen.getAllByTestId('select2')).toBeInTheDocument();
  });

In the testing above, as select1 has optionOne selected, I expect to select2 to show up. However, I am getting an error Unable to find an element by: [data-testid="select2"]. It also returns the whole HTML body, where I see select1 element with optionOne selected, but no select2 at all as it seems to still be hidden.

What am I missing here? How can I unhide select2 within the unit test?


问:
How can I alias ("typedef") a concrete instance of a generic class?
Let's say we have a generic container…

```<code>class GenericContainer<T> {
  constructor(val:T) {
    this.val = val;
  }
}
let numberContainer = new GenericContainer<number>();
</code>```

I would like to be able to create a "shorthand" alias: a concrete type of the generic class using number, called NumberContainer. I would like it to be usable as a drop-in replacement for GenericContainer<number>.

I would also like to avoid the type alias showing up in the built JavaScript. So references to NumberContainer in typescript should appear as GenericContainer.

```<code>// I have tried...
type NumberContainer = GenericContainer<number>;
interface NumberContainer extends GenericContainer<number>;
</code>```

But anytime I try to use it…

```<code>let numberContainer = new NumberContainer();
</code>```

I get an error: 'NumberContainer' only refers to a type, but is being used as a value here.

I notice I can extend with an empty class, which compiles. Like:

```<code>class NumberContainer extends GenericContainer<number> {}
// compiles to:
//   class NumberContainer extends GenericContainer {
//   }
</code>```

But this emits an actual JS class declaration into the build, which I want to avoid because it seems useless. I want to have NumberContainer be able to be instantiated (with the GenericContainer class implementation in JS), but otherwise have no purpose than type checking.

Is this kind of type-only "aliasing" possible in TypeScript? Or what am I not understanding?

Body:
Let's say we have a generic container…

class GenericContainer<T> {
  constructor(val:T) {
    this.val = val;
  }
}
let numberContainer = new GenericContainer<number>();

I would like to be able to create a "shorthand" alias: a concrete type of the generic class using number, called NumberContainer. I would like it to be usable as a drop-in replacement for GenericContainer<number>.

I would also like to avoid the type alias showing up in the built JavaScript. So references to NumberContainer in typescript should appear as GenericContainer.

// I have tried...
type NumberContainer = GenericContainer<number>;
interface NumberContainer extends GenericContainer<number>;

But anytime I try to use it…

let numberContainer = new NumberContainer();

I get an error: 'NumberContainer' only refers to a type, but is being used as a value here.

I notice I can extend with an empty class, which compiles. Like:

class NumberContainer extends GenericContainer<number> {}
// compiles to:
//   class NumberContainer extends GenericContainer {
//   }

But this emits an actual JS class declaration into the build, which I want to avoid because it seems useless. I want to have NumberContainer be able to be instantiated (with the GenericContainer class implementation in JS), but otherwise have no purpose than type checking.

Is this kind of type-only "aliasing" possible in TypeScript? Or what am I not understanding?


问:
ReactJs Routing not working and don't know why
When I click a button the new url will be shown in the browser address bar but strangely the content of the page is not changed . I see in the code that     ..history.push(url); is executed . So what could be the problem ??

I can further narrow down the problem.
I am on a SiteA and via button click I switch to SiteC. Now if I am on SiteB and again want via button also switch to  SiteC it does not work. Very strange.


问:
Spark: How to tune memory / cores given my cluster?
There are several threads with significant votes that I am having difficulty interpreting, perhaps due to jargon of 2016 being different of that today? (or I am just not getting it, too)

Apache Spark: The number of cores vs. the number of executors

How to tune spark executor number, cores and executor memory?

Azure/Databricks offers some best practices on cluster sizing: https://learn.microsoft.com/en-us/azure/databricks/clusters/cluster-config-best-practices

So for my workload, lets say I am interested in (using Databricks current jargon):

1 Driver: Comprised of 64gb of memory and 8 cores

1 Worker: Comprised of 256gb of memory and 64 cores

Drawing on the above Microsoft link, fewer workers should in turn lead to less shuffle; among the most costly Spark operations.

So, I have 1 driver and 1 worker. How, then, do I translate these terms into what is discussed here on SO in terms of "nodes" and "executors".

Ultimately, I would like to set my Spark config "correctly" such that cores and memory are, as optimized as possible.


问:
How to apply textwrap.wrap as ufunc on xarray.Dataarray
I am desperately trying to split strings within an xarray.Dataarray.
What should happen to every element of the array is e.g.

```<code>"aaabbbccc" --> [aaa, bbb, ccc]
</code>```

Fortunately, such a function already exists in the textwrap library, but applying it to my Dataarray is a different story:

```<code>xds = riox.open_rasterio(fp_output_tmp_mlsieved, chunks = "auto")

<xarray.DataArray (band: 1, y: 2, x: 2)>
dask.array<transpose, shape=(1, 2, 2), dtype=<U18, chunksize=(1, 2, 2), chunktype=numpy.ndarray>
Coordinates:
  * band         (band) int64 1
  * x            (x) float64 3.077e+06 3.077e+06 ... 3.077e+06 3.077e+06
  * y            (y) float64 1.865e+06 1.865e+06 ... 1.865e+06 1.865e+06
    spatial_ref  int64 0
</code>```

Loaded it looks like this:

```<code>array([[['000000000000000000', '000000000000000000'],
        ['000000000000000000', '000000000000000000']]], dtype='<U18')
</code>```

I think a solution is to apply it with xr.apply_ufunc(). I have managed to do that with a simpler numpy function before, but with wrap() all I get is a bunch of errors. I think the main issue is that it is not a vectorized numpy function and second that I can´t get the dimensions to work out. My latest try looks like that:

```<code>def decompressor(s, l):
return np.array(wrap(s.item(), l))

def ufunc_decompressor(s, l):
    return xr.apply_ufunc(
        decompressor,
        s, l,
        output_dtypes=[np.dtype(f"U{l}")],
        input_core_dims=[["band"],[]],
        output_core_dims=[["band"]],
        exclude_dims=set(("band",)),
        dask="parallelized",
        vectorize=True
        )

 xds_split = ufunc_decompressor(xds, 3).load()

</code>```

What I get is a cryptic error:

```<code>  File "/home/.../miniconda3/envs/postproc/lib/python3.10/site-packages/dask/array/gufunc.py", line 489, in <genexpr>
    core_output_shape = tuple(core_shapes[d] for d in ocd)
KeyError: 'dim0'
</code>```

Body:
I am desperately trying to split strings within an xarray.Dataarray.
What should happen to every element of the array is e.g.

"aaabbbccc" --> [aaa, bbb, ccc]

Fortunately, such a function already exists in the textwrap library, but applying it to my Dataarray is a different story:

xds = riox.open_rasterio(fp_output_tmp_mlsieved, chunks = "auto")

<xarray.DataArray (band: 1, y: 2, x: 2)>
dask.array<transpose, shape=(1, 2, 2), dtype=<U18, chunksize=(1, 2, 2), chunktype=numpy.ndarray>
Coordinates:
  * band         (band) int64 1
  * x            (x) float64 3.077e+06 3.077e+06 ... 3.077e+06 3.077e+06
  * y            (y) float64 1.865e+06 1.865e+06 ... 1.865e+06 1.865e+06
    spatial_ref  int64 0

Loaded it looks like this:

array([[['000000000000000000', '000000000000000000'],
        ['000000000000000000', '000000000000000000']]], dtype='<U18')

I think a solution is to apply it with xr.apply_ufunc(). I have managed to do that with a simpler numpy function before, but with wrap() all I get is a bunch of errors. I think the main issue is that it is not a vectorized numpy function and second that I can´t get the dimensions to work out. My latest try looks like that:

def decompressor(s, l):
return np.array(wrap(s.item(), l))

def ufunc_decompressor(s, l):
    return xr.apply_ufunc(
        decompressor,
        s, l,
        output_dtypes=[np.dtype(f"U{l}")],
        input_core_dims=[["band"],[]],
        output_core_dims=[["band"]],
        exclude_dims=set(("band",)),
        dask="parallelized",
        vectorize=True
        )

 xds_split = ufunc_decompressor(xds, 3).load()

What I get is a cryptic error:

  File "/home/.../miniconda3/envs/postproc/lib/python3.10/site-packages/dask/array/gufunc.py", line 489, in <genexpr>
    core_output_shape = tuple(core_shapes[d] for d in ocd)
KeyError: 'dim0'


问:
Basic syntax highlighting does not work in jupyter notebook
I installed anaconda3, and from there I launched Jupyter notebook 6.4.12. But even basic syntax highlighting does not work. Even for a simple print("Hello")

Even for a simple print("Hello") it does not show the syntax highlighting one would normally see.

Screenshot attached


问:
airflow db init error in WSL2 Ubuntu: "Additional properties are not allowed ('logo' was unexpected)"
I have the next visualization of the error:

```<code>  File "/home/tinmar/.local/lib/python3.10/site-packages/jsonschema/validators.py", line 353, in validate
    raise error
jsonschema.exceptions.ValidationError: Additional properties are not allowed ('**logo**' was unexpected)

Failed validating 'additionalProperties' in schema['properties']['integrations']['items']:
    {'additionalProperties': False,
     'properties': {'external-doc-url': {'description': 'URL to external '
                                                        'documentation for '
                                                        'the integration.',
                                         'type': 'string'},
                    'how-to-guide': {'description': 'List of paths to '
                                                    'how-to-guide for the '
                                                    'integration. The path '
                                                    'must start with '
                                                    "'/docs/'",
                                     'items': {'type': 'string'},
                                     'type': 'array'},
                    'integration-name': {'description': 'Name of the '
                                                        'integration.',
                                         'type': 'string'},
                    'tags': {'description': 'List of tags describing the '
                                            "integration. While we're "
                                            'using RST, only one tag is '
                                            'supported per integration.',
                             'items': {'enum': ['apache',
                                                'aws',
                                                'azure',
                                                'gcp',
                                                'gmp',
                                                'google',
                                                'protocol',
                                                'service',
                                                'software',
                                                'yandex'],
                                       'type': 'string'},
                             'maxItems': 1,
                             'minItems': 1,
                             'type': 'array'}},
     'required': ['integration-name', 'external-doc-url', 'tags'],
     'type': 'object'}

On instance['integrations'][0]:
    {'external-doc-url': 'https://www.sqlite.org/index.html',
     'how-to-guide': ['/docs/apache-airflow-providers-sqlite/operators.rst'],
     'integration-name': 'SQLite',
     **'logo': '/integration-logos/sql**,
     'tags': ['software']}
</code>```

I really don't know what the hell is happen here, I tried almost every solution I can find in the internet but nothing was usefull...

By the way, before this error, I have other one:

'''
ModuleNotFoundError: No module named 'wtforms.compat'
'''

Error that was solved by this code

```<code>pip install wtforms==2.3.3
pip install marsmallow==3.0.0
</code>```

I think that maybe the first error was the cause of all, but I'm not sure about it and I don't know how can be possible

This errors came when I try to uninstall airflow 2.5.0 in order to downgrade to airflow 2.0.0. I mean, this was the cause of the other two errors, I think so...

I also try to uninstall and reinstall WSL2, this threw me some errors but I solve it, I don't think this was the problem because before I trying this, the other errors already pop out.

I expect a local airflow env in Ubuntu with WSL2

I will appreciate if someone have any idea on how to solve it, thank you before it :)

Body:
I have the next visualization of the error:

  File "/home/tinmar/.local/lib/python3.10/site-packages/jsonschema/validators.py", line 353, in validate
    raise error
jsonschema.exceptions.ValidationError: Additional properties are not allowed ('**logo**' was unexpected)

Failed validating 'additionalProperties' in schema['properties']['integrations']['items']:
    {'additionalProperties': False,
     'properties': {'external-doc-url': {'description': 'URL to external '
                                                        'documentation for '
                                                        'the integration.',
                                         'type': 'string'},
                    'how-to-guide': {'description': 'List of paths to '
                                                    'how-to-guide for the '
                                                    'integration. The path '
                                                    'must start with '
                                                    "'/docs/'",
                                     'items': {'type': 'string'},
                                     'type': 'array'},
                    'integration-name': {'description': 'Name of the '
                                                        'integration.',
                                         'type': 'string'},
                    'tags': {'description': 'List of tags describing the '
                                            "integration. While we're "
                                            'using RST, only one tag is '
                                            'supported per integration.',
                             'items': {'enum': ['apache',
                                                'aws',
                                                'azure',
                                                'gcp',
                                                'gmp',
                                                'google',
                                                'protocol',
                                                'service',
                                                'software',
                                                'yandex'],
                                       'type': 'string'},
                             'maxItems': 1,
                             'minItems': 1,
                             'type': 'array'}},
     'required': ['integration-name', 'external-doc-url', 'tags'],
     'type': 'object'}

On instance['integrations'][0]:
    {'external-doc-url': 'https://www.sqlite.org/index.html',
     'how-to-guide': ['/docs/apache-airflow-providers-sqlite/operators.rst'],
     'integration-name': 'SQLite',
     **'logo': '/integration-logos/sql**,
     'tags': ['software']}

I really don't know what the hell is happen here, I tried almost every solution I can find in the internet but nothing was usefull...

By the way, before this error, I have other one:

'''
ModuleNotFoundError: No module named 'wtforms.compat'
'''

Error that was solved by this code

pip install wtforms==2.3.3
pip install marsmallow==3.0.0

I think that maybe the first error was the cause of all, but I'm not sure about it and I don't know how can be possible

This errors came when I try to uninstall airflow 2.5.0 in order to downgrade to airflow 2.0.0. I mean, this was the cause of the other two errors, I think so...

I also try to uninstall and reinstall WSL2, this threw me some errors but I solve it, I don't think this was the problem because before I trying this, the other errors already pop out.

I expect a local airflow env in Ubuntu with WSL2

I will appreciate if someone have any idea on how to solve it, thank you before it :)


问:
EDK2 Error 3FFF: Sources is not a valid section Name, Fix?
This is in my Dsc file

```<code>[Sources]
  UEFI.c

</code>```

This is my error while compiling  Error 3FFF: Sources is not a valid section Name

I tried moving My [Sources] Section checking for any errors But It still wont compile

Body:
This is in my Dsc file

[Sources]
  UEFI.c

This is my error while compiling  Error 3FFF: Sources is not a valid section Name

I tried moving My [Sources] Section checking for any errors But It still wont compile


问:
Dynamically adjust the location of table in PDF when the content of the table changes using report Lab in Python
I have to generate multiple  pdf in which i want to place a table fetching from SQL database,the size of the table varies in each pdf and the table has to come after a fixed location in the pdf as shown below ,may i know how to do this since when the table content changes the position also change

Case 1

enter image description here

Here as you can see the position of the table is from a specific distance from the logo but when the content becomes small then position is changing it has to be same

enter image description here
Here you can see the position is coming down

I am using below code

```<code>c_width=[2.5*inch] # width of the columns
t=Table(my_data,colWidths=c_width,repeatRows=1)
t.setStyle(TableStyle([('FONTSIZE',(0,0),(-1,-1),10),
                       ('BACKGROUND',(0,0),(-1,0),colors.black),
                       ('TEXTCOLOR',(0,0),(-1,0),colors.ghostwhite),

                       ('BACKGROUND',(0,1),(-1,-1),colors.darkgray),
                       ('TEXTCOLOR',(0,1),(-1,-1),colors.grey),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.ghostwhite),
                       ('ALIGN', (1,1), (-1,-1), 'LEFT')
                       ]))
elements=[]
elements.append(t)
my_doc.build(elements)
t.wrapOn(c,300,300)
t.drawOn(c, -0.5*inch,3*inch)

c.showPage()
c.save()
</code>```

I am expecting that the position of the table should be fixed irrespective of the content of the table become short or more

Body:
I have to generate multiple  pdf in which i want to place a table fetching from SQL database,the size of the table varies in each pdf and the table has to come after a fixed location in the pdf as shown below ,may i know how to do this since when the table content changes the position also change

Case 1

enter image description here

Here as you can see the position of the table is from a specific distance from the logo but when the content becomes small then position is changing it has to be same

enter image description here
Here you can see the position is coming down

I am using below code

c_width=[2.5*inch] # width of the columns
t=Table(my_data,colWidths=c_width,repeatRows=1)
t.setStyle(TableStyle([('FONTSIZE',(0,0),(-1,-1),10),
                       ('BACKGROUND',(0,0),(-1,0),colors.black),
                       ('TEXTCOLOR',(0,0),(-1,0),colors.ghostwhite),

                       ('BACKGROUND',(0,1),(-1,-1),colors.darkgray),
                       ('TEXTCOLOR',(0,1),(-1,-1),colors.grey),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.ghostwhite),
                       ('ALIGN', (1,1), (-1,-1), 'LEFT')
                       ]))
elements=[]
elements.append(t)
my_doc.build(elements)
t.wrapOn(c,300,300)
t.drawOn(c, -0.5*inch,3*inch)

c.showPage()
c.save()

I am expecting that the position of the table should be fixed irrespective of the content of the table become short or more


问:
Entity framework core and ChangeTracker memory consumption
Using entity framework core 6:

In my aspnet core project, my controllers get a DB context through dependency injection with service setup like the following:

```<code>...

builder.Services.AddDbContext<MyDBContext>(options => options.UseSqlServer(dbConnectionString));

...
</code>```

The controllers in the application do several database operations that are not inter-related. Means:

Step 1:

Query Table A, get a large result, then do CUD on it

_dbContect.SaveChanges();

Step 2:

Query Table B, get a large result, then do CUD on it

_dbContect.SaveChanges();

Step 3:

Query Table C, get a large result, then do CUD on it

_dbContect.SaveChanges();

Question:

1- Should I call _dbContect.ChangeTracker.Clear(); after each SaveChanges(); to save memory?

2- Is there a better way of handling _dbContect excess change tracking memory consumption?

3- Should I even be worry about  change tracking memory consumption?

Body:
Using entity framework core 6:

In my aspnet core project, my controllers get a DB context through dependency injection with service setup like the following:

...

builder.Services.AddDbContext<MyDBContext>(options => options.UseSqlServer(dbConnectionString));

...

The controllers in the application do several database operations that are not inter-related. Means:

Step 1:

Query Table A, get a large result, then do CUD on it

_dbContect.SaveChanges();

Step 2:

Query Table B, get a large result, then do CUD on it

_dbContect.SaveChanges();

Step 3:

Query Table C, get a large result, then do CUD on it

_dbContect.SaveChanges();

Question:

1- Should I call _dbContect.ChangeTracker.Clear(); after each SaveChanges(); to save memory?

2- Is there a better way of handling _dbContect excess change tracking memory consumption?

3- Should I even be worry about  change tracking memory consumption?


问:
Add Pull Tab/Button for Bootstrap 5 OffCanvas
Is there a way (html/css only - without using extra javascript) to add a little 'pull-tab' button that triggers a vanilla Bootstrap 5 offcanvas side menu?

I want to use the standard offcanvas demo like here (https://getbootstrap.com/docs/5.2/components/offcanvas/#live-demo) but with a little pulltab like the screenshot below.  The pulltab button should also slide out along with the offcanvas element.

Thanks for any help!


问:
Calculate breakout bands of Elliott wave oscillator
I am trying to calculate the values for the Elliott oscillator breakbands in python. I have the indicator logic in C#, which I will leave below.
In python I have already calculated and checked the value of the histogram, on which depends the calculation of the breakbands I want to calculate.

However, the values that the current logic gives are not the correct ones and I can't find what is the fault, since as I mentioned, I am replicating an existing logic in another language.

Actual logic in Python:

# For LowerBand, this return directly 0:
osc_fast = 5
osc_slow = 35
lens = osc_fast + osc_slow
pr = 2 / lens
strenght = 100

df = df.assign(Lwr_Line=0)
df['Lwr_Line'] = np.where(df["EWO_Std"] < 0, (df['EWO_Std']*pr) + (df['Lwr_Line'].shift(1)*(1-pr)), df['Lwr_Line'].shift(1))
df['LineEWOLwr'] = strenght / 100 * df['Lwr_Line']
df.drop(columns='Lwr_Line', inplace=True)

# For UpperBand:

df = df.assign(Upr_Line=0)
df['Upr_Line'] = np.where(df["EWO_Std"] > 0, (df['EWO_Std']*pr) + (df['Upr_Line'].shift(1)*(1-pr)), df['Upr_Line'].shift(1))
df['LineEWOUpr'] = strenght / 100 * df['Upr_Line']
df.drop(columns='Upr_Line', inplace=True)

```
<p>Logic checked in C#:</p>
<pre class="lang-cs prettyprint-override"><code>{

            MP[0]       =   ( High[0] + Low[0] ) / 2;

            UprLine[0]  =   0;
            LwrLine[0]  =   0;
            Lens        =   OscFast + OscSlow;
            Pr = 2.0/Lens;

            if(CurrentBar < OscSlow){
                OscAG = 0;
                if (OscAG > 0){
                    OscAGUpr[0] = OscAG;
                    if (OscAGUpr[0] > OscAGUpr[1]){
                        OscAGUprDiv[0] = OscAG;
                    }
                }
                else{
                    OscAGLwr[0] = OscAG;
                    OscAGLwrDiv[0] = OscAG;
                }
            }

            else{
                OscAG   =   SMA(MP,OscFast)[0] - SMA(MP,OscSlow)[0];
                if (OscAG > 0){
                        UprLine[0]  = (OscAG*Pr) + (UprLine[1]*(1-Pr));
                        LwrLine[0]  = LwrLine[1];
                    OscAGUpr[0] = OscAG;
                        if (OscAGUpr[0] > OscAGUpr[1])
                            {
                                OscAGUprDiv[0] = OscAG;
                            }

                }
                else{
                    UprLine[0]      = UprLine[1];
                    LwrLine[0]      = (OscAG*Pr) + (LwrLine[1]*(1-Pr));
                    OscAGLwr[0]     = OscAG;
                        if (OscAGLwr[0] > OscAGLwr[1])
                        {
                            OscAGLwrDiv[0] = OscAG;
                        }

                }
            }

            LineEWOUpr[0]   =   BOBStrength / 100 * UprLine[0];
            LineEWOLwr[0]   =   BOBStrength / 100 * LwrLine[0];

        }

</code>```

Does anyone know what the error could be?

Thanks!

I'm tried many combinations, but no one works

Body:
I am trying to calculate the values for the Elliott oscillator breakbands in python. I have the indicator logic in C#, which I will leave below.
In python I have already calculated and checked the value of the histogram, on which depends the calculation of the breakbands I want to calculate.

However, the values that the current logic gives are not the correct ones and I can't find what is the fault, since as I mentioned, I am replicating an existing logic in another language.

Actual logic in Python:

# For LowerBand, this return directly 0:
osc_fast = 5
osc_slow = 35
lens = osc_fast + osc_slow
pr = 2 / lens
strenght = 100

df = df.assign(Lwr_Line=0)
df['Lwr_Line'] = np.where(df["EWO_Std"] < 0, (df['EWO_Std']*pr) + (df['Lwr_Line'].shift(1)*(1-pr)), df['Lwr_Line'].shift(1))
df['LineEWOLwr'] = strenght / 100 * df['Lwr_Line']
df.drop(columns='Lwr_Line', inplace=True)

# For UpperBand:

df = df.assign(Upr_Line=0)
df['Upr_Line'] = np.where(df["EWO_Std"] > 0, (df['EWO_Std']*pr) + (df['Upr_Line'].shift(1)*(1-pr)), df['Upr_Line'].shift(1))
df['LineEWOUpr'] = strenght / 100 * df['Upr_Line']
df.drop(columns='Upr_Line', inplace=True)

Logic checked in C#:

{

            MP[0]       =   ( High[0] + Low[0] ) / 2;

            UprLine[0]  =   0;
            LwrLine[0]  =   0;
            Lens        =   OscFast + OscSlow;
            Pr = 2.0/Lens;

            if(CurrentBar < OscSlow){
                OscAG = 0;
                if (OscAG > 0){
                    OscAGUpr[0] = OscAG;
                    if (OscAGUpr[0] > OscAGUpr[1]){
                        OscAGUprDiv[0] = OscAG;
                    }
                }
                else{
                    OscAGLwr[0] = OscAG;
                    OscAGLwrDiv[0] = OscAG;
                }
            }

            else{
                OscAG   =   SMA(MP,OscFast)[0] - SMA(MP,OscSlow)[0];
                if (OscAG > 0){
                        UprLine[0]  = (OscAG*Pr) + (UprLine[1]*(1-Pr));
                        LwrLine[0]  = LwrLine[1];
                    OscAGUpr[0] = OscAG;
                        if (OscAGUpr[0] > OscAGUpr[1])
                            {
                                OscAGUprDiv[0] = OscAG;
                            }

                }
                else{
                    UprLine[0]      = UprLine[1];
                    LwrLine[0]      = (OscAG*Pr) + (LwrLine[1]*(1-Pr));
                    OscAGLwr[0]     = OscAG;
                        if (OscAGLwr[0] > OscAGLwr[1])
                        {
                            OscAGLwrDiv[0] = OscAG;
                        }

                }
            }

            LineEWOUpr[0]   =   BOBStrength / 100 * UprLine[0];
            LineEWOLwr[0]   =   BOBStrength / 100 * LwrLine[0];

        }

Does anyone know what the error could be?

Thanks!

I'm tried many combinations, but no one works


问:
Get source line of a struct definition in GDB python script?
There is gdb.lookup_type("SomeType") in GDB python API as listed blow, but I cannot find a way to get the source file and line number where the type is defined, much like what the GDB command info types ^SomeType$ does. Is it possible via GDB python API without invoking into the info types command?

https://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python


问:
How to add a custom field to the Django admin login page
To authenticate, 3 fields are needed:

user_id

password

account_id

Each account_id defines an isolated space and the user_id is unique only inside its respective account_id.

I've created a custom backend authentication and I can authenticate successfully. The problem is that the login Django Admin form has user_id and password fields by default.

I would like to add the account_id field in the original Django form template by only subclassing AuthenticationForm, is it possible?

There's a similar question here but he's using a custom login template:
Add custom field to Django Admin authentication form

Existing code..

Model:

```<code>class HeliosUser(AbstractUser, DateModelBase):
    username = None
    user_id = models.CharField(max_length=255)

    USERNAME_FIELD = "user_id"
    REQUIRED_FIELDS = ["account_id", "role", "email"]

    objects = HeliosUserManager()

    email = models.EmailField()
    account_id = models.ForeignKey(
        "agent.Agent",
        on_delete=models.RESTRICT,
    )
    ...
</code>```

Backend:

```<code>class SettingsBackend(BaseBackend):
    def authenticate(
        self, request, user_id=None, account_id=None, password=None, **kwargs
    ):
        try:
            user = HeliosUser.objects.get(
                user_id=user_id, account_id=account_id
            )
        except HeliosUser.DoesNotExist:
            return None
        if user.check_password(password):
            return user
        return None

    def get_user(self, user_id, account_id):
        try:
            return HeliosUser.objects.get(
                user_id=user_id, account_id=account_id
            )
        except HeliosUser.DoesNotExist:
            return None
</code>```

Admin site:

```<code>class HeliosUserAdmin(admin.AdminSite):
    site_title = "Helios Administration"
    site_header = "Helios Administration"
    index_title = "Helios Administration"
    login_form = HeliosAuthenticationForm

admin_site = HeliosUserAdmin()
</code>```

Authentication form:

```<code>class HeliosAuthenticationForm(AuthenticationForm):
    account_id = forms.ModelChoiceField(queryset=Agent.objects.all())
</code>```

Thank's in advance!

Body:
To authenticate, 3 fields are needed:

user_id

password

account_id

Each account_id defines an isolated space and the user_id is unique only inside its respective account_id.

I've created a custom backend authentication and I can authenticate successfully. The problem is that the login Django Admin form has user_id and password fields by default.

I would like to add the account_id field in the original Django form template by only subclassing AuthenticationForm, is it possible?

There's a similar question here but he's using a custom login template:
Add custom field to Django Admin authentication form

Existing code..

Model:

class HeliosUser(AbstractUser, DateModelBase):
    username = None
    user_id = models.CharField(max_length=255)

    USERNAME_FIELD = "user_id"
    REQUIRED_FIELDS = ["account_id", "role", "email"]

    objects = HeliosUserManager()

    email = models.EmailField()
    account_id = models.ForeignKey(
        "agent.Agent",
        on_delete=models.RESTRICT,
    )
    ...

Backend:

class SettingsBackend(BaseBackend):
    def authenticate(
        self, request, user_id=None, account_id=None, password=None, **kwargs
    ):
        try:
            user = HeliosUser.objects.get(
                user_id=user_id, account_id=account_id
            )
        except HeliosUser.DoesNotExist:
            return None
        if user.check_password(password):
            return user
        return None

    def get_user(self, user_id, account_id):
        try:
            return HeliosUser.objects.get(
                user_id=user_id, account_id=account_id
            )
        except HeliosUser.DoesNotExist:
            return None

Admin site:

class HeliosUserAdmin(admin.AdminSite):
    site_title = "Helios Administration"
    site_header = "Helios Administration"
    index_title = "Helios Administration"
    login_form = HeliosAuthenticationForm

admin_site = HeliosUserAdmin()

Authentication form:

class HeliosAuthenticationForm(AuthenticationForm):
    account_id = forms.ModelChoiceField(queryset=Agent.objects.all())

Thank's in advance!


问:
Program freezes when maximizing from custom window chrome snap
When Aero snapping to maximize with the Windows standard title bar, the program does not crash.

However, when Aero snapping to maximize with the effect of the GlassFrameThickness property in WindowChrome, the program freezes.

When opening Task Manager, it clearly states that the program isn't responding, but I am able to stop it via the debugger just fine, too.

Here is my current code for the extended window chrome:

<WindowChrome.WindowChrome>
    <WindowChrome UseAeroCaptionButtons="True" GlassFrameThickness="320,59,0,0"/>
</WindowChrome.WindowChrome>
```

Standard, but it has the maximize snapping issue.

Is there anything I can do to fix this?

What I tried:

I originally tried using Win32 APIs, but that gave the exact same result. In fact, they were so similar, taking a screenshot of both would be exactly the same.

What I expected:

I expected a glorious experience; snapping to maximize with the extended title bar wouldn't freeze the program.

What actually happened:

So far, that's great and all, but using Win32 APIs would still produce the exact same snapping issue as I described before.

I have to confess.

I actually used the Win32 APIs first, then I switched to WindowChrome, but they produced the same result, so it doesn't really matter.

Body:
When Aero snapping to maximize with the Windows standard title bar, the program does not crash.

However, when Aero snapping to maximize with the effect of the GlassFrameThickness property in WindowChrome, the program freezes.

When opening Task Manager, it clearly states that the program isn't responding, but I am able to stop it via the debugger just fine, too.

Here is my current code for the extended window chrome:

<WindowChrome.WindowChrome>
    <WindowChrome UseAeroCaptionButtons="True" GlassFrameThickness="320,59,0,0"/>
</WindowChrome.WindowChrome>

Standard, but it has the maximize snapping issue.

Is there anything I can do to fix this?

What I tried:

I originally tried using Win32 APIs, but that gave the exact same result. In fact, they were so similar, taking a screenshot of both would be exactly the same.

What I expected:

I expected a glorious experience; snapping to maximize with the extended title bar wouldn't freeze the program.

What actually happened:

So far, that's great and all, but using Win32 APIs would still produce the exact same snapping issue as I described before.

I have to confess.

I actually used the Win32 APIs first, then I switched to WindowChrome, but they produced the same result, so it doesn't really matter.


问:
How to filter rows in a dataframe using in and notin
I have the following problem

```<code>import pandas as pd
import numpy as np

data = {
  "ID": [420, 380, 390, 540,520],
  "duration": [50, 40, 45,33,19],
  "previous": [125  , 540 , 420 , 777 , 390  ],
  "next":[390,880  ,520  ,380   ,810   ]
}

#load data into a DataFrame object:
df = pd.DataFrame(data)

print(df)

#search for IDs where previous are not in IDs

#print(data[~data['previous'].isin(data['ID'])])

#print(data[~data.previous.isin(data.ID)])

print(data[~data.next.isin(data.ID)])
</code>```

As you can see I have a dataframe

```<code>    ID  duration  previous  next
0  420        50       125   390
1  380        40       540   880
2  390        45       420   520
3  540        33       777   380
4  520        19       390   810
</code>```

and I want to find the rows where the "next" (or the "previous") data is not in the IDs

for example the row 0 has a previous (125) which does not exist in IDs
or the row 4 has a next(810) which does not exist in IDs

I tried to apply this solution  but I get the error "AttributeError: 'dict' object has no attribute 'next'"

Body:
I have the following problem

import pandas as pd
import numpy as np

data = {
  "ID": [420, 380, 390, 540,520],
  "duration": [50, 40, 45,33,19],
  "previous": [125  , 540 , 420 , 777 , 390  ],
  "next":[390,880  ,520  ,380   ,810   ]
}

#load data into a DataFrame object:
df = pd.DataFrame(data)

print(df)

#search for IDs where previous are not in IDs

#print(data[~data['previous'].isin(data['ID'])])

#print(data[~data.previous.isin(data.ID)])

print(data[~data.next.isin(data.ID)])

As you can see I have a dataframe

    ID  duration  previous  next
0  420        50       125   390
1  380        40       540   880
2  390        45       420   520
3  540        33       777   380
4  520        19       390   810

and I want to find the rows where the "next" (or the "previous") data is not in the IDs

for example the row 0 has a previous (125) which does not exist in IDs
or the row 4 has a next(810) which does not exist in IDs

I tried to apply this solution  but I get the error "AttributeError: 'dict' object has no attribute 'next'"


问:
Inaccessible resource
I'm working through Petzold "Programming Windows" 5th edition, using Visual Studio 2015 Community Edition on a Windows 8.1 machine, and having problems with the PoePoem program on p. 432-437.

The program will compile, but throws an exception on execution.

Apparently, in the WM_CREATE message processing, while I can load the text of the poem as a resource and count the number of lines, the debugger reports an access violation in the last line of this code snippet when I attempt to write a '\0' character in place of the backslash '\\'.

Evidently things have changed sufficiently in 20 years that the program as written no longer works. Is there a workaround?

```<code>hResource = LoadResource (hInst,
                      FindResource (hInst, TEXT ("AnnabelLee"),
                                           TEXT ("TEXT"))) ;

          pText = (char *) LockResource (hResource) ;
          iNumLines = 0 ;

          while (*pText != '\\' && *pText != '\0')
          {
               if (*pText == '\n')
                    iNumLines ++ ;
               pText = AnsiNext (pText) ;
          }
          *pText = '\0' ;
</code>```

I had a long wrestle  with Visual Studio to get proper construction of the *.rc files and resource.h files, omitted the hInst declaration, misspelled the text several times. I finally got the program to compile, but I'm still missing something.

Title: Inaccessible resource

Body:
I'm working through Petzold "Programming Windows" 5th edition, using Visual Studio 2015 Community Edition on a Windows 8.1 machine, and having problems with the PoePoem program on p. 432-437.

The program will compile, but throws an exception on execution.

Apparently, in the WM_CREATE message processing, while I can load the text of the poem as a resource and count the number of lines, the debugger reports an access violation in the last line of this code snippet when I attempt to write a '\0' character in place of the backslash '\\'.

Evidently things have changed sufficiently in 20 years that the program as written no longer works. Is there a workaround?

hResource = LoadResource (hInst,
                      FindResource (hInst, TEXT ("AnnabelLee"),
                                           TEXT ("TEXT"))) ;

          pText = (char *) LockResource (hResource) ;
          iNumLines = 0 ;

          while (*pText != '\\' && *pText != '\0')
          {
               if (*pText == '\n')
                    iNumLines ++ ;
               pText = AnsiNext (pText) ;
          }
          *pText = '\0' ;

I had a long wrestle  with Visual Studio to get proper construction of the *.rc files and resource.h files, omitted the hInst declaration, misspelled the text several times. I finally got the program to compile, but I'm still missing something.


问:
Flutter dropdown keyboard input
I have a reactiveForm that has a few reactiveTextFields with validation and a reactive dropdown menu.

The goal is to allow the user through the browser(mobile will have different behavior) be able to tab through the fields and inside the drop down be able to type on their keyboard and have the drop down filter results.

The tabbing focus is working correctly i'm not sure the best approach to adding a gesture/key detector widget(What widget to even use here).

Any suggestions or links to docs would be helpful thanks!

Title: Flutter dropdown keyboard input


问:
What can I do to improve detection of a Datamatrix code with pyzbar/zbar
I am trying to detect a barcode with pyzbar.

If get the following image up on my computer screen and scan it with my mobile phone camera then it is instantly able to provide me with the qr code information.

However, if I use Pyzbar to analyse the raw image file then I am not able to get any results.

How can I improve the accuracy of pyzbar?


问:
Django signals pre_delete accessing request.user
Is there a way to access request.user within pre_delete signal?  I found an answer but that was 10 years ago and doesn't work with the current version of Django.</p>


问:
Paging not working with spring boot and mongodb
I saw several articles here on stackoverflow but I couldn't get my pagination working with mongodb and spring boot. The code always returns only one result when I change the value of the limit or skip variable  the result is always nothing.

My Repository:

```<code>public interface CategoryProductRepository extends MongoRepository<CategoryProduct, String> {

    @Aggregation(pipeline = {
        "{ '$match': { 'categories.category_id' : ?0 } }",
        "{ '$skip' : ?1 }",
        "{ '$limit' : ?2 }"
      })
    List<CategoryProduct> findCategoriesCategoryId(
        Long field0,
        Long skip,
        Long limit
    );

}
</code>```

My structure:

```<code>[
    {
        "product_id": 4,
        "id_colletion": 4,
        "product_tite": "Testar",
        "product_quant": 50,
        "product_slug": "slug6",
        "product_active": "ativo",
        "product_description": "description",
        "product_price_un": 50,
        "product_price_kg": 10.25,
        "star": 0,
        "photos": [
            {
                "photo": "url",
                "type": "mini",
                "title": "título",
                "active": "ativo"
            },
            {
                "photo": "url 2",
                "type": "mini",
                "title": "título 2",
                "active": "ativo"
            }
        ],
        "categories": [
            {
                "category_id": 1,
                "name": "categoria 1",
                "active": "ativo"
            },
            {
                "category_id": 2,
                "name": "categoria 2",
                "active": "ativo"
            }
        ]
    },
    {
        "product_id": 5,
        "id_colletion": 5,
        "product_tite": "new",
        "product_quant": 50,
        "product_slug": "slugnew",
        "product_active": "ativo",
        "product_description": "descriptionnew",
        "product_price_un": 50,
        "product_price_kg": 10.25,
        "star": 0,
        "photos": [
            {
                "photo_id": 13,
                "photo": "photo 11",
                "type": "mini",
                "title": "photo 11",
                "active": "ativo"
            }
        ],
        "categories": [
            {
                "category_id": 1,
                "name": "categoria 1",
                "active": "ativo"
            }
        ]
    },
    {
        "product_id": 9,
        "id_colletion": 9,
        "product_tite": "2",
        "product_quant": 2,
        "product_slug": "slugnew2",
        "product_active": "ativo",
        "product_description": "2",
        "product_price_un": 2,
        "product_price_kg": 2,
        "star": 0,
        "photos": [
            {
                "photo": "photo 2",
                "type": "mini",
                "title": "photo 2",
                "active": "desativo"
            }
        ],
        "categories": [
            {
                "category_id": 2,
                "name": "categoria 2",
                "active": "ativo"
            }
        ]
    }
]
</code>```

Does anyone have any idea where my mistake is?

[SOLVED]

I was inserting the limit and skip wrong but the code works fine

Body:
I saw several articles here on stackoverflow but I couldn't get my pagination working with mongodb and spring boot. The code always returns only one result when I change the value of the limit or skip variable  the result is always nothing.

My Repository:

public interface CategoryProductRepository extends MongoRepository<CategoryProduct, String> {

    @Aggregation(pipeline = {
        "{ '$match': { 'categories.category_id' : ?0 } }",
        "{ '$skip' : ?1 }",
        "{ '$limit' : ?2 }"
      })
    List<CategoryProduct> findCategoriesCategoryId(
        Long field0,
        Long skip,
        Long limit
    );

}

My structure:

[
    {
        "product_id": 4,
        "id_colletion": 4,
        "product_tite": "Testar",
        "product_quant": 50,
        "product_slug": "slug6",
        "product_active": "ativo",
        "product_description": "description",
        "product_price_un": 50,
        "product_price_kg": 10.25,
        "star": 0,
        "photos": [
            {
                "photo": "url",
                "type": "mini",
                "title": "título",
                "active": "ativo"
            },
            {
                "photo": "url 2",
                "type": "mini",
                "title": "título 2",
                "active": "ativo"
            }
        ],
        "categories": [
            {
                "category_id": 1,
                "name": "categoria 1",
                "active": "ativo"
            },
            {
                "category_id": 2,
                "name": "categoria 2",
                "active": "ativo"
            }
        ]
    },
    {
        "product_id": 5,
        "id_colletion": 5,
        "product_tite": "new",
        "product_quant": 50,
        "product_slug": "slugnew",
        "product_active": "ativo",
        "product_description": "descriptionnew",
        "product_price_un": 50,
        "product_price_kg": 10.25,
        "star": 0,
        "photos": [
            {
                "photo_id": 13,
                "photo": "photo 11",
                "type": "mini",
                "title": "photo 11",
                "active": "ativo"
            }
        ],
        "categories": [
            {
                "category_id": 1,
                "name": "categoria 1",
                "active": "ativo"
            }
        ]
    },
    {
        "product_id": 9,
        "id_colletion": 9,
        "product_tite": "2",
        "product_quant": 2,
        "product_slug": "slugnew2",
        "product_active": "ativo",
        "product_description": "2",
        "product_price_un": 2,
        "product_price_kg": 2,
        "star": 0,
        "photos": [
            {
                "photo": "photo 2",
                "type": "mini",
                "title": "photo 2",
                "active": "desativo"
            }
        ],
        "categories": [
            {
                "category_id": 2,
                "name": "categoria 2",
                "active": "ativo"
            }
        ]
    }
]

Does anyone have any idea where my mistake is?

[SOLVED]

I was inserting the limit and skip wrong but the code works fine