问:
Why is AContext->Data null in the OnExecute event?
I am implementing one of the solutions described in this question:

How to display messages in every Indy event?

Specifically, I am implementing solution number 2:

Don't perform a synchronous sync, perform an asynchronous sync instead (TIdNotify, TThread::Queue(), or equivalent). There is no good reason to block your server threads waiting for the main thread to perform UI status updates.

So I changed my class to inherit from TIdNotify, changed the Synchronize methods to Notify and removed the delete statements for my previous TIdSync objects (because TIdNotify does it internally)

So far so good, now I am implementing the OnExecute event with something like this:

    String sTemp;

    TIdBuffer *Buffer = static_cast<TIdBuffer*>(AContext->Data);
    Buffer->Write(static_cast<TIdMappedPortContext*>(AContext)->NetData);
    Buffer->CompactHead();

    TTextToDisplay *TextToDisplay = new TTextToDisplay;
    CDecoder *Decoder = new CDecoder();
    TStringList *slDecodedLines = NULL;
    TIdBytes ucBuffer;
    int offset = 0;
    while (ReadMessageData(Buffer, offset, ucBuffer)) {
        sTemp = String().sprintf(_D("%s"), ToHex(ucBuffer).c_str());
        slDecodedLines = Decoder->formatInput(sTemp);
        if(slDecodedLines)
        {
            TextToDisplay->AddStringList(slDecodedLines);
            TextToDisplay->Notify();
        }
    }

    // delete TextToDisplay;
    delete Decoder;
    delete slDecodedLines;

    if (offset > 0)
        Buffer->Remove(offset);
```

I am getting an exception on line 3 because Buffer is NULL, and Buffer is NULL because AContext->Data is NULL (AContext is not NULL).

What could I be doing wrong for this to happen?

I have implemented the events:

OnBeofreConnect

OnDisconnect

OnConnect

They "print" some messages, but even if I comment their internal code the error remains. Any hint will be highly appreciated.

Body:
I am implementing one of the solutions described in this question:

How to display messages in every Indy event?

Specifically, I am implementing solution number 2:

Don't perform a synchronous sync, perform an asynchronous sync instead (TIdNotify, TThread::Queue(), or equivalent). There is no good reason to block your server threads waiting for the main thread to perform UI status updates.

So I changed my class to inherit from TIdNotify, changed the Synchronize methods to Notify and removed the delete statements for my previous TIdSync objects (because TIdNotify does it internally)

So far so good, now I am implementing the OnExecute event with something like this:

    String sTemp;

    TIdBuffer *Buffer = static_cast<TIdBuffer*>(AContext->Data);
    Buffer->Write(static_cast<TIdMappedPortContext*>(AContext)->NetData);
    Buffer->CompactHead();

    TTextToDisplay *TextToDisplay = new TTextToDisplay;
    CDecoder *Decoder = new CDecoder();
    TStringList *slDecodedLines = NULL;
    TIdBytes ucBuffer;
    int offset = 0;
    while (ReadMessageData(Buffer, offset, ucBuffer)) {
        sTemp = String().sprintf(_D("%s"), ToHex(ucBuffer).c_str());
        slDecodedLines = Decoder->formatInput(sTemp);
        if(slDecodedLines)
        {
            TextToDisplay->AddStringList(slDecodedLines);
            TextToDisplay->Notify();
        }
    }

    // delete TextToDisplay;
    delete Decoder;
    delete slDecodedLines;

    if (offset > 0)
        Buffer->Remove(offset);

I am getting an exception on line 3 because Buffer is NULL, and Buffer is NULL because AContext->Data is NULL (AContext is not NULL).

What could I be doing wrong for this to happen?

I have implemented the events:

OnBeofreConnect

OnDisconnect

OnConnect

They "print" some messages, but even if I comment their internal code the error remains. Any hint will be highly appreciated.


来源: stackexchange

问:
What would the path to my font file (.ttf) be in an AWS Lambda thats hosted via an Image?
This is where the problem Lies:

```<code>txt_clip = TextClip(author, font='/var/task/RubikVinyl.ttf', fontsize = 35, color='white')
</code>```

It does not use the font, despite me passing the entire font path. I've tried different formats, saving the font file to different paths, but I've had no success. I'm also almost certain you can pass a font path to moviepy as I've see other users do it with success.

Any help would be much appreciated!

Background for context:

I've deployed an AWS Lambda with the package type being an Image, it uses moviepy to edit clips together. I'm trying to pass in a custom font for overlaying text on the video, but it doesn't recognize the font path I've passed in.

To copy the font file i'm using into the Lambda, I do this in my Dockerfile:

```<code>WORKDIR /var/task
COPY RubikVinyl.ttf ./
</code>```

Then, to confirm the Lambda has access to the file, I do:

```<code>os.path.exists("/var/task/RubikVinyl.ttf")
</code>```

which returns "True" so I know the path is correct and the file is there.

I've tried saving the file to different paths, but moviepy never uses the font path that I specify. It doesn't return any sort of error, but defaults the font to what looks like times new roman

ContentLicense: CC BY-SA 4.0

Body:
This is where the problem Lies:

txt_clip = TextClip(author, font='/var/task/RubikVinyl.ttf', fontsize = 35, color='white')

It does not use the font, despite me passing the entire font path. I've tried different formats, saving the font file to different paths, but I've had no success. I'm also almost certain you can pass a font path to moviepy as I've see other users do it with success.

Any help would be much appreciated!

Background for context:

I've deployed an AWS Lambda with the package type being an Image, it uses moviepy to edit clips together. I'm trying to pass in a custom font for overlaying text on the video, but it doesn't recognize the font path I've passed in.

To copy the font file i'm using into the Lambda, I do this in my Dockerfile:

WORKDIR /var/task
COPY RubikVinyl.ttf ./

Then, to confirm the Lambda has access to the file, I do:

os.path.exists("/var/task/RubikVinyl.ttf")

which returns "True" so I know the path is correct and the file is there.

I've tried saving the file to different paths, but moviepy never uses the font path that I specify. It doesn't return any sort of error, but defaults the font to what looks like times new roman


问:
Pine script code, moving stop loss to break even after TP2
i'm a pretty newbie at this topic and all my knowledge about pine script is diced together out of available open-source scripts and what i remind from school ;).
Right now i want to make an indicator where the stoploss (then for the hole position) moves after takeprofit2 to breakeven, but i got pretty big problems here and tried already several versions but don't get the result i want.
I would very appreciate if somebody can help me here!

`

```<code>TP1Perc = input.float(title="Long Take Profit 1 (%)", minval=0.0, step=0.1, defval=2, group="TP & SL")
TP2Perc = input.float(title="Long Take Profit 2 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")
TP3Perc = input.float(title="Long Take Profit 3 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")
TP4Perc = input.float(title="Long Take Profit 4 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")

TP1_Ratio = input.float(title="Sell Postion Size % @ TP1", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached")/100
TP2_Ratio = input.float(title="Sell Postion Size % @ TP2", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP2 is reached")/100
TP3_Ratio = input.float(title="Sell Postion Size % @ TP3", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP3 is reached")/100
TP4_Ratio = input.float(title="Sell Postion Size % @ TP4", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP4 is reached")/100

// Calculate moving averages
//fastSMA = ta.sma(close, FastPeriod)
//slowSMA = ta.sma(close, SlowPeriod)

// Calculate trading conditions
//enterLong  = ta.crossover(fastSMA, slowSMA)

// Plot moving averages
//plot(series=fastSMA, color=color.green, title="Fase MA")
//plot(series=slowSMA, color=color.red, title="Slow MA")

// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
    strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)

percentAsPrice(pcnt) =>
    strategy.position_size != 0 ? ((pcnt / 100.0) + 1.0) * strategy.position_avg_price : float(na)

current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))

TP1  = strategy.position_avg_price + percentAsPoints(TP1Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP2  = strategy.position_avg_price + percentAsPoints(TP2Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP3  = strategy.position_avg_price + percentAsPoints(TP3Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP4  = strategy.position_avg_price + percentAsPoints(TP4Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)

// Submit entry orders
if buySignal and in_date_range  == true
    strategy.entry('Long', strategy.long, when=buySignal, alert_message='Open Long Position')

if sellSignal and in_date_range  == true
    strategy.entry('Short', strategy.short, when=sellSignal, alert_message='Open Short Position')

// STEP 3:
// Submit exit orders based on take profit price

if strategy.position_size > 0
    strategy.exit("TP1", from_entry="Long", qty = initial_position_size * TP1_Ratio, limit = TP1)
    strategy.exit("TP2", from_entry="Long", qty = initial_position_size * TP2_Ratio, limit = TP2)
    strategy.exit("TP3", from_entry="Long", qty = initial_position_size * TP3_Ratio, limit = TP3)
    strategy.exit("TP4", from_entry="Long", qty = initial_position_size * TP4_Ratio, limit = TP4)
    strategy.close('Long', when=sellSignal, alert_message='Close Long Position')

if strategy.position_size < 0
    strategy.exit("TP1", from_entry="Short", qty = initial_position_size * TP1_Ratio, limit = TP1)
    strategy.exit("TP2", from_entry="Short", qty = initial_position_size * TP2_Ratio, limit = TP2)
    strategy.exit("TP3", from_entry="Short", qty = initial_position_size * TP3_Ratio, limit = TP3)
    strategy.exit("TP4", from_entry="Short", qty = initial_position_size * TP4_Ratio, limit = TP4)
    strategy.close('Short', when=buySignal, alert_message='Close Short Position')

// Plot take profit values for confirmation
plot(series=(strategy.position_size > 0) ? TP1 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 1")
plot(series=(strategy.position_size > 0) ? TP2 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 2")
plot(series=(strategy.position_size > 0) ? TP3 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 3")
plot(series=(strategy.position_size > 0) ? TP4 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 4")
</code>```

`

Already tried:

Pine script code, stop to breakeven. but cant figure out
and
Pine Script (TradingView) - How to move a Stop Loss to the Take Profit level

without getting the result i want.

Body:
i'm a pretty newbie at this topic and all my knowledge about pine script is diced together out of available open-source scripts and what i remind from school ;).
Right now i want to make an indicator where the stoploss (then for the hole position) moves after takeprofit2 to breakeven, but i got pretty big problems here and tried already several versions but don't get the result i want.
I would very appreciate if somebody can help me here!

`

TP1Perc = input.float(title="Long Take Profit 1 (%)", minval=0.0, step=0.1, defval=2, group="TP & SL")
TP2Perc = input.float(title="Long Take Profit 2 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")
TP3Perc = input.float(title="Long Take Profit 3 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")
TP4Perc = input.float(title="Long Take Profit 4 (%)", minval=0.0, step=0.1, defval=4, group="TP & SL")

TP1_Ratio = input.float(title="Sell Postion Size % @ TP1", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached")/100
TP2_Ratio = input.float(title="Sell Postion Size % @ TP2", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP2 is reached")/100
TP3_Ratio = input.float(title="Sell Postion Size % @ TP3", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP3 is reached")/100
TP4_Ratio = input.float(title="Sell Postion Size % @ TP4", defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP4 is reached")/100

// Calculate moving averages
//fastSMA = ta.sma(close, FastPeriod)
//slowSMA = ta.sma(close, SlowPeriod)

// Calculate trading conditions
//enterLong  = ta.crossover(fastSMA, slowSMA)

// Plot moving averages
//plot(series=fastSMA, color=color.green, title="Fase MA")
//plot(series=slowSMA, color=color.red, title="Slow MA")

// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
    strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)

percentAsPrice(pcnt) =>
    strategy.position_size != 0 ? ((pcnt / 100.0) + 1.0) * strategy.position_avg_price : float(na)

current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))

TP1  = strategy.position_avg_price + percentAsPoints(TP1Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP2  = strategy.position_avg_price + percentAsPoints(TP2Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP3  = strategy.position_avg_price + percentAsPoints(TP3Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP4  = strategy.position_avg_price + percentAsPoints(TP4Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)

// Submit entry orders
if buySignal and in_date_range  == true
    strategy.entry('Long', strategy.long, when=buySignal, alert_message='Open Long Position')

if sellSignal and in_date_range  == true
    strategy.entry('Short', strategy.short, when=sellSignal, alert_message='Open Short Position')

// STEP 3:
// Submit exit orders based on take profit price

if strategy.position_size > 0
    strategy.exit("TP1", from_entry="Long", qty = initial_position_size * TP1_Ratio, limit = TP1)
    strategy.exit("TP2", from_entry="Long", qty = initial_position_size * TP2_Ratio, limit = TP2)
    strategy.exit("TP3", from_entry="Long", qty = initial_position_size * TP3_Ratio, limit = TP3)
    strategy.exit("TP4", from_entry="Long", qty = initial_position_size * TP4_Ratio, limit = TP4)
    strategy.close('Long', when=sellSignal, alert_message='Close Long Position')

if strategy.position_size < 0
    strategy.exit("TP1", from_entry="Short", qty = initial_position_size * TP1_Ratio, limit = TP1)
    strategy.exit("TP2", from_entry="Short", qty = initial_position_size * TP2_Ratio, limit = TP2)
    strategy.exit("TP3", from_entry="Short", qty = initial_position_size * TP3_Ratio, limit = TP3)
    strategy.exit("TP4", from_entry="Short", qty = initial_position_size * TP4_Ratio, limit = TP4)
    strategy.close('Short', when=buySignal, alert_message='Close Short Position')

// Plot take profit values for confirmation
plot(series=(strategy.position_size > 0) ? TP1 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 1")
plot(series=(strategy.position_size > 0) ? TP2 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 2")
plot(series=(strategy.position_size > 0) ? TP3 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 3")
plot(series=(strategy.position_size > 0) ? TP4 : na, color=color.green, style=plot.style_circles, linewidth=1, title="Take Profit 4")

`

Already tried:

Pine script code, stop to breakeven. but cant figure out
and
Pine Script (TradingView) - How to move a Stop Loss to the Take Profit level

without getting the result i want.


问:
Levenshtein distance between two columns of two different dataframes
Let's say i have two dataframes

Dataframe 1:

ID1
NAME1

1
JUANA

2
LUCAS

3
PEDRO

4
MATIAS

Dataframe 2:

ID2
NAME2

1
JUAN

2
JUANA

3
JUANITA

4
MATIAS

5
MATIA

6
MATIAS

7
MATIAZ

Each one don't have the same numbers of rows. I would like to create a third dataframe that compares each value of the first dataframe with the second.

Dataframe 3:

ID1
NAME1
NAME 2
Levenshtein

1
JUANA
JUANA
0

1
JUANA
JUAN
1

1
JUANA
JUANITA
3

2
LUCAS

5

3
PEDRO

5

4
MATIAS
MATIAS
0

4
MATIAS
MATIA
1

4
MATIAS
MATIAZ
1

Is there a way to accomplish that?

Thanks!


问:
Div content overflow
I tried to set position of v-container (a div element) to be absolute and scroll attribute to be scroll in hope that the content would not expand and display over other areas of the site but it did not work. v-container typically contains about 20 pilot-item. Any solutions?

Demo

My attempt at it:

setInterval(() => {
  container = document.getElementById("v-container");
  fetch("/report")
    .then((report) => report.json())
    .then((violates) => {
      container.innerHTML = "";
      violates.sort((a, b) => a.timestamp < b.timestamp);
      for (let i = 0; i < violates.length; ++i) {
        //if time stamp is not over 10 minutes yet
        if (Date.now() - violates[i].timestamp < 599000) {
          const infodiv = document.createElement("div");
          infodiv.className = "pilot-item";
          infodiv.innerHTML = `
Name: ${
                  violates[i].firstname + " " + violates[i].lastname
                }

Phone Number: ${
                                  violates[i].phone
                                }
Email: ${violates[i].email}
Time: ${msToMinutesAndSeconds(Date.now() - violates[i].timestamp)}
`;
          container.appendChild(infodiv);
        } else {
          console.log(violates[i]._id)
          fetch('/' + violates[i]._id, {
              method: 'DELETE',
              headers: {
                'Content-Type': 'application/json'
              }
            })
            .then(res => {
              if (res.status === 200) {
                infodiv.parentNode.removeChild(infodiv);
              } else {
                return Promise.reject(res.text());
              }
            })
            .catch(err => console.error(err));
        }

      }
    });
}, 2000);

function msToMinutesAndSeconds(ms) {
  let jn = true;
  let str = "";
  const tmp = Math.round(ms / 1000);
  const minutes = Math.trunc(tmp / 60);
  const seconds = tmp - minutes * 60;
  if (minutes !== 0) {
    jn = false;
    minutes === 1 ? str += "1 minute" : str += `${minutes} minutes`;
  }

  if (seconds !== 0) {
    jn = false
    if (minutes !== 0) str += " and "
    seconds === 1 ? str += "1 second" : str += `${seconds} seconds`;
  }

  if (jn) return "Just now"
  else str += " ago"

  return str;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: scroll;
}

#section-header {
  position: absolute;
  top: 60%;
  /* Center the element vertically */
  left: 50%;
  /* Center the element horizontally */
  transform: translate(-50%, -50%);
  /* Offset the element by half its width and height */
}

/* pilot divs container */

#v-container {
  position: absolute;
  left: 50%;
  top: 80%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background-color: lightblue;
  width: 80%;
  overflow: scroll;
  border-radius: 10px;
  border: 2px solid black;
}

/* pilot divs */

.pilot-item {
  position: relative;
  display: inline-block;
  height: 5%;
  width: 22%;
  background-color: bisque;
  border-radius: 5px;
  border: black solid 1.5px;
  margin: 5px;
  padding: 1em;
}

/* monitor area */

.map-container {
  height: 400px;
  width: 400px;
  background-color: green;
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
}

/* no drone zone circle */

#ndz {
  width: 160px;
  height: 160px;
  border: 1px solid black;
  border-radius: 50%;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}</code>```

Violators for the last 10 minutes:

```

Title: Div content overflow

Body:
I tried to set position of v-container (a div element) to be absolute and scroll attribute to be scroll in hope that the content would not expand and display over other areas of the site but it did not work. v-container typically contains about 20 pilot-item. Any solutions?

Demo

My attempt at it:

setInterval(() => {
  container = document.getElementById("v-container");
  fetch("/report")
    .then((report) => report.json())
    .then((violates) => {
      container.innerHTML = "";
      violates.sort((a, b) => a.timestamp < b.timestamp);
      for (let i = 0; i < violates.length; ++i) {
        //if time stamp is not over 10 minutes yet
        if (Date.now() - violates[i].timestamp < 599000) {
          const infodiv = document.createElement("div");
          infodiv.className = "pilot-item";
          infodiv.innerHTML = `
Name: ${
                  violates[i].firstname + " " + violates[i].lastname
                }

Phone Number: ${
                                  violates[i].phone
                                }
Email: ${violates[i].email}
Time: ${msToMinutesAndSeconds(Date.now() - violates[i].timestamp)}
`;
          container.appendChild(infodiv);
        } else {
          console.log(violates[i]._id)
          fetch('/' + violates[i]._id, {
              method: 'DELETE',
              headers: {
                'Content-Type': 'application/json'
              }
            })
            .then(res => {
              if (res.status === 200) {
                infodiv.parentNode.removeChild(infodiv);
              } else {
                return Promise.reject(res.text());
              }
            })
            .catch(err => console.error(err));
        }

      }
    });
}, 2000);

function msToMinutesAndSeconds(ms) {
  let jn = true;
  let str = "";
  const tmp = Math.round(ms / 1000);
  const minutes = Math.trunc(tmp / 60);
  const seconds = tmp - minutes * 60;
  if (minutes !== 0) {
    jn = false;
    minutes === 1 ? str += "1 minute" : str += `${minutes} minutes`;
  }

  if (seconds !== 0) {
    jn = false
    if (minutes !== 0) str += " and "
    seconds === 1 ? str += "1 second" : str += `${seconds} seconds`;
  }

  if (jn) return "Just now"
  else str += " ago"

  return str;
}

body {
  overflow: scroll;
}

#section-header {
  position: absolute;
  top: 60%;
  /* Center the element vertically */
  left: 50%;
  /* Center the element horizontally */
  transform: translate(-50%, -50%);
  /* Offset the element by half its width and height */
}

/* pilot divs container */

#v-container {
  position: absolute;
  left: 50%;
  top: 80%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background-color: lightblue;
  width: 80%;
  overflow: scroll;
  border-radius: 10px;
  border: 2px solid black;
}

/* pilot divs */

.pilot-item {
  position: relative;
  display: inline-block;
  height: 5%;
  width: 22%;
  background-color: bisque;
  border-radius: 5px;
  border: black solid 1.5px;
  margin: 5px;
  padding: 1em;
}

/* monitor area */

.map-container {
  height: 400px;
  width: 400px;
  background-color: green;
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
}

/* no drone zone circle */

#ndz {
  width: 160px;
  height: 160px;
  border: 1px solid black;
  border-radius: 50%;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Violators for the last 10 minutes:


问:
Wordpress how spread blog posts/reply from different categories across a web page?
I'm new to wordpress and have a question about blog post/reply. So I have a home page and on the home page I'd like to have the user read a blog post and then reply.  No problem here.  The question I have is suppose I'd like to spread my blog posts/reply across my page separated by text/images etc and then display another blog post/reply from a different category. So you have Blog Post/reply from category A, then text images etc, followed by another Blog Post/Reply from category B.  I just haven't been able to find a way to do this.
Thanks for your help.</p>


问:
JPA throwing EntityNotFoundException for thing I just deleted
Foo has this property:

```<code>@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
@OrderBy("index")
private List<FooItem> fooItems = new ArrayList<>();

public void setFooItems(List<FooItem> fooItems) {
  if (this.fooItems == null) {
    this.fooItems = new ArrayList<>();
  }

  this.fooItems.clear();
  if (fooItems != null) {
    fooItems.forEach(fi -> fi.setFoo(this));
    this.fooItems.addAll(fooItems);
  }
}
</code>```

FooItem has this corresponding property:
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "foo_id")
private Foo foo;

I have a constraint in the database that says no 2 FooItems can hold the same <Foo ID, Other ID> pair.

When I have a service make a change to a specific Foo to replace its FooItems, holding the same Other IDs as before but with some changes to other properties:

```<code>@Transactional
void makeChange() {
  ...
  final List<FooItem> newItems = makeNewItems();
  foo.setFooItems(newItems);
  ...
  repository.save(foo);
  ...
}
</code>```

then JPA/Hibernate causes a constraint violation exception. Even though there is really only ever going to be 1 row for a specific combination, I guess something in JPA/Hibernate/Postgres adapter orders operations badly.

So I try clearing out the old items before making the change:

```<code>final List<FooItem> oldItems = foo.getFooItems();
oldItems.stream().forEach(fi -> fi.setFoo(null));
fooItemRepository.deleteAll(oldItems);
fooItemRepository.flush();
foo.setFooItems(null);
repository.saveAndFlush(foo);
</code>```

And now when I do the last repository.save(foo), I get a EntityNotFoundException thrown from JpaEntityNotFoundDelegate. Why? I explicitly disconnected and deleted the thing!

Body:
Foo has this property:

@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
@OrderBy("index")
private List<FooItem> fooItems = new ArrayList<>();

public void setFooItems(List<FooItem> fooItems) {
  if (this.fooItems == null) {
    this.fooItems = new ArrayList<>();
  }

  this.fooItems.clear();
  if (fooItems != null) {
    fooItems.forEach(fi -> fi.setFoo(this));
    this.fooItems.addAll(fooItems);
  }
}

FooItem has this corresponding property:
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "foo_id")
private Foo foo;

I have a constraint in the database that says no 2 FooItems can hold the same <Foo ID, Other ID> pair.

When I have a service make a change to a specific Foo to replace its FooItems, holding the same Other IDs as before but with some changes to other properties:

@Transactional
void makeChange() {
  ...
  final List<FooItem> newItems = makeNewItems();
  foo.setFooItems(newItems);
  ...
  repository.save(foo);
  ...
}

then JPA/Hibernate causes a constraint violation exception. Even though there is really only ever going to be 1 row for a specific combination, I guess something in JPA/Hibernate/Postgres adapter orders operations badly.

So I try clearing out the old items before making the change:

final List<FooItem> oldItems = foo.getFooItems();
oldItems.stream().forEach(fi -> fi.setFoo(null));
fooItemRepository.deleteAll(oldItems);
fooItemRepository.flush();
foo.setFooItems(null);
repository.saveAndFlush(foo);

And now when I do the last repository.save(foo), I get a EntityNotFoundException thrown from JpaEntityNotFoundDelegate. Why? I explicitly disconnected and deleted the thing!


问:
portforwarding setup nginx to self-signed certificate
I have a bastion server that can allow me to connect to one private web server, this means I have set up double tunnel ssh where I allow to connect to my application in localhost:3000, so when I use this in my browser looks like localhost:8081 to connect to my private web server

ssh -L 8081:ip-x-x-x-x.ec2.internal:3000 -i "key.pem" ubuntu@ec2-X-X-X-X.compute-1.amazonaws.com

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

http://localhost:8081 => bastion(EC2) => (nodejs running in port 3000, nginx Aplication)

I need certificate my API with my own Self-Signed Certificate

My application running on nodejs with pm2.
I already try to use Nginx to apply my self-signed certificate on my API in the web server, But I don't know what missed, because when try to use mysite.com nothing happens

```<code>server{
    listen 443;
    server  mysite.com;
    ssl on;
    ssl_certificate /etc/ssl/server.crt;
    ssl_certificate_key /etc/ssl/server.key;
    location / {
       proxy_pass http://localhost:3000/;
    }
}
</code>```

Body:
I have a bastion server that can allow me to connect to one private web server, this means I have set up double tunnel ssh where I allow to connect to my application in localhost:3000, so when I use this in my browser looks like localhost:8081 to connect to my private web server

ssh -L 8081:ip-x-x-x-x.ec2.internal:3000 -i "key.pem" ubuntu@ec2-X-X-X-X.compute-1.amazonaws.com

       DIAGRAM

http://localhost:8081 => bastion(EC2) => (nodejs running in port 3000, nginx Aplication)

I need certificate my API with my own Self-Signed Certificate

My application running on nodejs with pm2.
I already try to use Nginx to apply my self-signed certificate on my API in the web server, But I don't know what missed, because when try to use mysite.com nothing happens

server{
    listen 443;
    server  mysite.com;
    ssl on;
    ssl_certificate /etc/ssl/server.crt;
    ssl_certificate_key /etc/ssl/server.key;
    location / {
       proxy_pass http://localhost:3000/;
    }
}


问:
Hover providers in case of multiple monaco editors
I have built a component ResizableMonacoEditor on top of Monaco Editor. In index.tsx, we have

import * as monaco from 'monaco-editor';
const MonacoEditor = lazy(() => import('react-monaco-editor'));

monaco.languages.register({ id: "mySpecialLanguage", extensions: [], aliases: [], mimetypes: [], });

class ResizableMonacoEditor extends React.Component {

  _handleEditorDidMount(editor, monaco) {
      ... ...
      monaco.languages.registerHoverProvider("mySpecialLanguage", {
        provideHover: (model, position, token) => {
            return {
                range: new monaco.Range(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount())),
                contents: [
                    { value: '**SOURCE**' }
                ]
            };
        }
    });
  }
  ... ...
  render() {
    return <MonacoEditor {...this.props} editorDidMount={this._handleEditorDidMount.bind(this)} />
  }
}
```

It works when we have only 1 ResizableMonacoEditor on a page. Now, I would like to have two ResizableMonacoEditor on a page. They are all supposed to hold programs in mySpecialLangauge.

Then, I realize that each editor registers one hoverProvider. As a consequence, when I hover on a text in one editor, two **SOURCE** are shown in the message. But, I think only the hoverProvider registered by the editor should be executed.

Does anyone know what is the correct way to organize language, editor, model, and registerHoverProvider in case of multiple monaco editors?

Body:
I have built a component ResizableMonacoEditor on top of Monaco Editor. In index.tsx, we have

import * as monaco from 'monaco-editor';
const MonacoEditor = lazy(() => import('react-monaco-editor'));

monaco.languages.register({ id: "mySpecialLanguage", extensions: [], aliases: [], mimetypes: [], });

class ResizableMonacoEditor extends React.Component {

  _handleEditorDidMount(editor, monaco) {
      ... ...
      monaco.languages.registerHoverProvider("mySpecialLanguage", {
        provideHover: (model, position, token) => {
            return {
                range: new monaco.Range(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount())),
                contents: [
                    { value: '**SOURCE**' }
                ]
            };
        }
    });
  }
  ... ...
  render() {
    return <MonacoEditor {...this.props} editorDidMount={this._handleEditorDidMount.bind(this)} />
  }
}

It works when we have only 1 ResizableMonacoEditor on a page. Now, I would like to have two ResizableMonacoEditor on a page. They are all supposed to hold programs in mySpecialLangauge.

Then, I realize that each editor registers one hoverProvider. As a consequence, when I hover on a text in one editor, two **SOURCE** are shown in the message. But, I think only the hoverProvider registered by the editor should be executed.

Does anyone know what is the correct way to organize language, editor, model, and registerHoverProvider in case of multiple monaco editors?


问:
Webpack's hot reload breaks images in .html file

The problem

After the hot replacement, Webpack doesn't include images which were insert into HTML file by relative paths into the bundle.

Code samples

index.html:

Relative path in .html file.

```
<p><code>webpack.config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  entry: path.resolve(__dirname, "src/index"),
  output: {
    filename: "[name].[contenthash].js",
    path: path.resolve(__dirname, "build/"),
    assetModuleFilename: "assets/[contenthash][ext][query]",
    clean: true
  },
  devServer: {
    compress: true,
    hot: true, // Pushes the plugin automatically
    port: 3000,
    // Allows Webpack to notice changes in index.html and do hot reloads
    watchFiles: [path.resolve(__dirname, "index.html")]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "index.html"),
      favicon: path.resolve(__dirname, "assets/favicon.jpg"),
      title: "Minimal, Reproducible Example",
      meta: {
        charset: "UTF-8",
        viewport: "width=device-width, initial-scale=1"
      }
    })
  ],
  module: {
    rules: [
      {
        test: /\.html$/i,
        use: ["html-loader"]
      },
      {
        test: /\.(png|jpe?g|webp)$/i,
        type: "asset/resource",
        generator: {
          filename: "assets/img/[contenthash][ext][query]"
        }
      }
    ]
  }
}
</code>```

Behavior

First load runs correctly. If one changes anything in (for example) index.js, the page reloads and the image from HTML disappears, and he sees a 404 instead. If one inspects the source, he sees that after the hot replacement the image isn't included into the bundle anymore.

If one changes index.html, the page reloads and the image returns back to the bundle. But, e. g. favicon inserted by HtmlWepbackPlugin disappears permanently, and only full stop and then staring the server helps.

Images from the Internet or loaded by Javascript always work fine.

I was searching the Internet for a long time, but couldn't find the appropriate solution. Many similar questions are about Webpack 4 with file-loader, url-loader, etc.

Importing index.html into index.js seems to work, but it's odd solution, isn't it?

index.js

import "../index.html"
import "./index.css"

// etc.
```

Repo: https://github.com/Object417/webpack-html-hot-reload

Body:
The problem

After the hot replacement, Webpack doesn't include images which were insert into HTML file by relative paths into the bundle.

Code samples

index.html:

Relative path in .html file.

webpack.config.js:

module.exports = {
  entry: path.resolve(__dirname, "src/index"),
  output: {
    filename: "[name].[contenthash].js",
    path: path.resolve(__dirname, "build/"),
    assetModuleFilename: "assets/[contenthash][ext][query]",
    clean: true
  },
  devServer: {
    compress: true,
    hot: true, // Pushes the plugin automatically
    port: 3000,
    // Allows Webpack to notice changes in index.html and do hot reloads
    watchFiles: [path.resolve(__dirname, "index.html")]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "index.html"),
      favicon: path.resolve(__dirname, "assets/favicon.jpg"),
      title: "Minimal, Reproducible Example",
      meta: {
        charset: "UTF-8",
        viewport: "width=device-width, initial-scale=1"
      }
    })
  ],
  module: {
    rules: [
      {
        test: /\.html$/i,
        use: ["html-loader"]
      },
      {
        test: /\.(png|jpe?g|webp)$/i,
        type: "asset/resource",
        generator: {
          filename: "assets/img/[contenthash][ext][query]"
        }
      }
    ]
  }
}

Behavior

First load runs correctly. If one changes anything in (for example) index.js, the page reloads and the image from HTML disappears, and he sees a 404 instead. If one inspects the source, he sees that after the hot replacement the image isn't included into the bundle anymore.

If one changes index.html, the page reloads and the image returns back to the bundle. But, e. g. favicon inserted by HtmlWepbackPlugin disappears permanently, and only full stop and then staring the server helps.

Images from the Internet or loaded by Javascript always work fine.

I was searching the Internet for a long time, but couldn't find the appropriate solution. Many similar questions are about Webpack 4 with file-loader, url-loader, etc.

Importing index.html into index.js seems to work, but it's odd solution, isn't it?

index.js

import "../index.html"
import "./index.css"

// etc.

Repo: https://github.com/Object417/webpack-html-hot-reload


问:
How to List Iceberg Tables in a Catalog
I'm trying to just list all tables in my Iceberg-enabled catalog.

Falling back to Spark-Sql works

```<code>    spark.sql(s"USE ${catalogName}.${databaseName}")
    val tables = spark.sql("SHOW TABLES")
</code>```

Is it possible to accomplish the same with meta classes like spark.catalog, specific SparkSessionCatalog().listTables(catalogName, databaseName), or the generic BaseMetastoreCatalog().listTables(Namespace.of(catalogName))

I have not had much luck with any. I have an environment fully configured to use Iceberg for catalogName. I can read/write to tables, but general data catalog inspection is beyond me.

Title: How to List Iceberg Tables in a Catalog

Body:
I'm trying to just list all tables in my Iceberg-enabled catalog.

Falling back to Spark-Sql works

    spark.sql(s"USE ${catalogName}.${databaseName}")
    val tables = spark.sql("SHOW TABLES")

Is it possible to accomplish the same with meta classes like spark.catalog, specific SparkSessionCatalog().listTables(catalogName, databaseName), or the generic BaseMetastoreCatalog().listTables(Namespace.of(catalogName))

I have not had much luck with any. I have an environment fully configured to use Iceberg for catalogName. I can read/write to tables, but general data catalog inspection is beyond me.


问:
Historical trend lines built with array and loop - strange issue with order of crossings of lines with varip counter - Tradingview - Pinescript
so I have an interesting issue. I put together a script, which draws historical trend lines using array and a loop. I then try to catch when each of the line is crossed and have an order of crosses, for that I use a varip counter. Everything works fine when there is one line crossing during 1 LIVE candle.

When there is multiple crossings during 1 LIVE candle - it becomes sort of random. Sometimes it works and shows me correct order of the crossings - 1) > 2) > 3), sometimes the order of crossings is opposite - 3) > 2) > 1), sometimes completely random -  2) > 1) > 3) > 4).

I opened a case with TradingVIew support and they suggested to revert the loop (for array_index = 0 to 24 >>> for array_index = 0 to 24) of the array, inside which everything happens. After I have done that - in some places the problem becomes fixed and the order becomes correct, while in other places the problem occurs...

It does not matter what direction the price is going or the color of the historical trend line that is crossed (red/green - red uses ta.pivothigh, green uses ta.pivotlow for pivot points to draw the trend lines in the beginning) and so far I cannot find what actually causes the issue...

If I could isolate the issue, I could add an if statement and then just run 2 loops per each condition so that such out of order issue would not happen, but so far I cannot determine the logic of the problem.

Here is a chart screenshot where you can clearly see the correct count for red candle on the left and incorrect(backwards) for both of the green candles on the right (the loop here is: for array_index = 0 to 24 | if I switch the loop to for array_index = 24 to 0: red candle count becomes incorrect and green candles become correct):
See Screenshot Here

Or here: https://www.tradingview.com/x/cIEEXSAZ/

Those are the same trend lines and the only difference is: price direction and I have verified identical issues, with both directions of the price, so direction of the price should not be the issue here...

Here is a full code:

```<code>//@version=5
indicator("auto-trend-lines-varIP-testing",
 overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_bars_back=1500, precision=5)

leftbars = input.int(5, minval=1, title='Auto TrendLines: pivot detection: Left Bars')
rightbars = input.int(5, minval=1, title='Auto TrendLines: pivot detection: Right Bars')

// Pivots
ph = ta.pivothigh(high, leftbars, rightbars)
pl = ta.pivotlow(low, leftbars, rightbars)
// High
phv1 = ta.valuewhen(ph, high[rightbars], 0)
phb1 = ta.valuewhen(ph, bar_index[rightbars], 0)
phv2 = ta.valuewhen(ph, high[rightbars], 1)
phb2 = ta.valuewhen(ph, bar_index[rightbars], 1)
// Low
plv1 = ta.valuewhen(pl, low[rightbars], 0)
plb1 = ta.valuewhen(pl, bar_index[rightbars], 0)
plv2 = ta.valuewhen(pl, low[rightbars], 1)
plb2 = ta.valuewhen(pl, bar_index[rightbars], 1)

// TRENDLINE CODE
// --------------
get_slope(x1, x2, y1, y2) =>
    m = (y2 - y1) / (x2 - x1)
    m

get_y_intercept(m, x1, y1) =>
    b = y1 - m * x1
    b

get_y(m, b, ts) =>
    Y = m * ts + b
    Y

// Resistance variables
int res_x1 = na
float res_y1 = na
int res_x2 = na
float res_y2 = na

// Support variables
int sup_x1 = na
float sup_y1 = na
int sup_x2 = na
float sup_y2 = na

// Resistance
res_x1 := ph ? phb1 : res_x1[1]
res_y1 := ph ? phv1 : res_y1[1]
res_x2 := ph ? phb2 : res_x2[1]
res_y2 := ph ? phv2 : res_y2[1]

res_m = get_slope(res_x1, res_x2, res_y1, res_y2)
res_b = get_y_intercept(res_m, res_x1, res_y1)
res_y = get_y(res_m, res_b, bar_index)

// Support
sup_x1 := pl ? plb1 : sup_x1[1]
sup_y1 := pl ? plv1 : sup_y1[1]
sup_x2 := pl ? plb2 : sup_x2[1]
sup_y2 := pl ? plv2 : sup_y2[1]

sup_m = get_slope(sup_x1, sup_x2, sup_y1, sup_y2)
sup_b = get_y_intercept(sup_m, sup_x1, sup_y1)
sup_y = get_y(sup_m, sup_b, bar_index)

//// ARRAY - history trend lines ////
var int [] phb1_arr = array.new_int(25, 2)
var float [] phv1_arr = array.new_float(25, 2)
var int [] res_x1_arr = array.new_int(25, 2)
var float [] res_y1_arr = array.new_float(25, 2)
var int [] res_x2_arr = array.new_int(25, 2)
var float [] res_y2_arr = array.new_float(25, 2)

var int [] plb1_arr = array.new_int(25, 2)
var float [] plv1_arr = array.new_float(25, 2)
var int [] sup_x1_arr = array.new_int(25, 2)
var float [] sup_y1_arr = array.new_float(25, 2)
var int [] sup_x2_arr = array.new_int(25, 2)
var float [] sup_y2_arr = array.new_float(25, 2)

// Push pivots high and low into an array every time new pivots appear, array.push pushes element at the end of the array every time it "happens"
if ph
    array.insert(phb1_arr, 0, phb1)
    array.insert(phv1_arr, 0, phv1)
    array.insert(res_x1_arr, 0, res_x1)
    array.insert(res_y1_arr, 0, res_y1)
    array.insert(res_x2_arr, 0, res_x2)
    array.insert(res_y2_arr, 0, res_y2)
if pl
    array.insert(plb1_arr, 0, plb1)
    array.insert(plv1_arr, 0, plv1)
    array.insert(sup_x1_arr, 0, sup_x1)
    array.insert(sup_y1_arr, 0, sup_y1)
    array.insert(sup_x2_arr, 0, sup_x2)
    array.insert(sup_y2_arr, 0, sup_y2)

// Declare the coordinates varibales which will be assigned coordinates from array
int phb1_from_array = 0
float phv1_from_array = 0.0
int res_x1_from_array = 0
float res_y1_from_array = 0.0
int res_x2_from_array = 0
float res_y2_from_array = 0.0

int plb1_from_array = 0
float plv1_from_array = 0.0
int sup_x1_from_array = 0
float sup_y1_from_array = 0.0
int sup_x2_from_array = 0
float sup_y2_from_array = 0.0

// Initiate the array loop
for array_index = 0 to 24
    if array.size(phb1_arr) > 0 and array.size(phv1_arr) > 0 and array.size(plb1_arr) > 0 and array.size(plv1_arr) > 0 and array.size(res_x1_arr) > 0 and
     array.size(res_y1_arr) > 0 and array.size(res_x2_arr) > 0 and array.size(res_y2_arr) > 0 and array.size(sup_x1_arr) > 0 and
     array.size(sup_y1_arr) > 0 and array.size(sup_x2_arr) > 0 and array.size(sup_y2_arr) > 0
        phb1_from_array := array.get(phb1_arr, array_index)
        phv1_from_array := array.get(phv1_arr, array_index)
        res_x1_from_array := array.get(res_x1_arr, array_index)
        res_y1_from_array := array.get(res_y1_arr, array_index)
        res_x2_from_array := array.get(res_x2_arr, array_index)
        res_y2_from_array := array.get(res_y2_arr, array_index)

        plb1_from_array := array.get(plb1_arr, array_index)
        plv1_from_array := array.get(plv1_arr, array_index)
        sup_x1_from_array := array.get(sup_x1_arr, array_index)
        sup_y1_from_array := array.get(sup_y1_arr, array_index)
        sup_x2_from_array := array.get(sup_x2_arr, array_index)
        sup_y2_from_array := array.get(sup_y2_arr, array_index)

    // Re-calculate the trend lines stuff per newly grabbed coordinates from array
    res_m_from_array = get_slope(res_x1_from_array, res_x2_from_array, res_y1_from_array, res_y2_from_array)
    res_b_from_array = get_y_intercept(res_m_from_array, res_x1_from_array, res_y1_from_array)
    res_y_from_array = get_y(res_m_from_array, res_b_from_array, bar_index)

    sup_m_from_array = get_slope(sup_x1_from_array, sup_x2_from_array, sup_y1_from_array, sup_y2_from_array)
    sup_b_from_array = get_y_intercept(sup_m_from_array, sup_x1_from_array, sup_y1_from_array)
    sup_y_from_array = get_y(sup_m_from_array, sup_b_from_array, bar_index)

    // Draw the trend lines per coordinates/calculations grabbed from array, previous and all the history ones captured by the array
    //high (red) | per ARRAY
    red_line_arr = line.new(phb1_from_array, phv1_from_array, bar_index, res_y_from_array, color=color.rgb(143, 54, 54, 50),
     extend=extend.none, width=5)
    //high (red) | per ARRAY | cross catch
    red_line_arr_coordinates = line.get_price(red_line_arr, bar_index)
    //line.delete(pivot_connector_high_arr[1])

    //low (green) | per ARRAY
    green_line_arr = line.new(plb1_from_array, plv1_from_array, bar_index, sup_y_from_array, color=color.rgb(9, 134, 36, 50),
     extend=extend.none, width=5)
    //low (green) | per ARRAY | cross catch
    green_line_arr_coordinates = line.get_price(green_line_arr, bar_index)
    //line.delete(pivot_connector_low_arr[1])

    varip int position_order_counter = 0
    ////////////////////////////////////////////////
    // POSITION OPEN | LONG (red)
    if open > red_line_arr_coordinates and low <= red_line_arr_coordinates and high > red_line_arr_coordinates
        red_line_arr_cross_lbl = label.new(bar_index, red_line_arr_coordinates, text="red(↑)|price:" +
         str.tostring(math.round(red_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_up,
         color=color.rgb(193, 122, 0), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    // POSITION OPEN | SHORT (red)
    if open < red_line_arr_coordinates and high >= red_line_arr_coordinates and low < red_line_arr_coordinates
        red_line_arr_cross_lbl = label.new(bar_index, red_line_arr_coordinates, text="red(↓)|price:" +
         str.tostring(math.round(red_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_down,
         color=color.rgb(193, 122, 0), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    // POSITION OPEN | LONG (green)
    if open > green_line_arr_coordinates and low <= green_line_arr_coordinates and high > green_line_arr_coordinates
        green_line_arr_cross_lbl = label.new(bar_index, green_line_arr_coordinates, text="grn(↑)|price:" +
         str.tostring(math.round(green_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_up,
         color=color.rgb(70, 112, 201), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    // POSITION OPEN | SHORT (green)
    if open < green_line_arr_coordinates and high >= green_line_arr_coordinates and low < green_line_arr_coordinates
        green_line_arr_cross_lbl = label.new(bar_index, green_line_arr_coordinates, text="grn(↓)|price:" +
         str.tostring(math.round(green_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_down,
         color=color.rgb(70, 112, 201), textcolor=color.white, size=size.normal)
        position_order_counter += 1
</code>```

Body:
so I have an interesting issue. I put together a script, which draws historical trend lines using array and a loop. I then try to catch when each of the line is crossed and have an order of crosses, for that I use a varip counter. Everything works fine when there is one line crossing during 1 LIVE candle.

When there is multiple crossings during 1 LIVE candle - it becomes sort of random. Sometimes it works and shows me correct order of the crossings - 1) > 2) > 3), sometimes the order of crossings is opposite - 3) > 2) > 1), sometimes completely random -  2) > 1) > 3) > 4).

I opened a case with TradingVIew support and they suggested to revert the loop (for array_index = 0 to 24 >>> for array_index = 0 to 24) of the array, inside which everything happens. After I have done that - in some places the problem becomes fixed and the order becomes correct, while in other places the problem occurs...

It does not matter what direction the price is going or the color of the historical trend line that is crossed (red/green - red uses ta.pivothigh, green uses ta.pivotlow for pivot points to draw the trend lines in the beginning) and so far I cannot find what actually causes the issue...

If I could isolate the issue, I could add an if statement and then just run 2 loops per each condition so that such out of order issue would not happen, but so far I cannot determine the logic of the problem.

Here is a chart screenshot where you can clearly see the correct count for red candle on the left and incorrect(backwards) for both of the green candles on the right (the loop here is: for array_index = 0 to 24 | if I switch the loop to for array_index = 24 to 0: red candle count becomes incorrect and green candles become correct):
See Screenshot Here

Or here: https://www.tradingview.com/x/cIEEXSAZ/

Those are the same trend lines and the only difference is: price direction and I have verified identical issues, with both directions of the price, so direction of the price should not be the issue here...

Here is a full code:

//@version=5
indicator("auto-trend-lines-varIP-testing",
 overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_bars_back=1500, precision=5)

leftbars = input.int(5, minval=1, title='Auto TrendLines: pivot detection: Left Bars')
rightbars = input.int(5, minval=1, title='Auto TrendLines: pivot detection: Right Bars')

// Pivots
ph = ta.pivothigh(high, leftbars, rightbars)
pl = ta.pivotlow(low, leftbars, rightbars)
// High
phv1 = ta.valuewhen(ph, high[rightbars], 0)
phb1 = ta.valuewhen(ph, bar_index[rightbars], 0)
phv2 = ta.valuewhen(ph, high[rightbars], 1)
phb2 = ta.valuewhen(ph, bar_index[rightbars], 1)
// Low
plv1 = ta.valuewhen(pl, low[rightbars], 0)
plb1 = ta.valuewhen(pl, bar_index[rightbars], 0)
plv2 = ta.valuewhen(pl, low[rightbars], 1)
plb2 = ta.valuewhen(pl, bar_index[rightbars], 1)

// TRENDLINE CODE
// --------------
get_slope(x1, x2, y1, y2) =>
    m = (y2 - y1) / (x2 - x1)
    m

get_y_intercept(m, x1, y1) =>
    b = y1 - m * x1
    b

get_y(m, b, ts) =>
    Y = m * ts + b
    Y

// Resistance variables
int res_x1 = na
float res_y1 = na
int res_x2 = na
float res_y2 = na

// Support variables
int sup_x1 = na
float sup_y1 = na
int sup_x2 = na
float sup_y2 = na

// Resistance
res_x1 := ph ? phb1 : res_x1[1]
res_y1 := ph ? phv1 : res_y1[1]
res_x2 := ph ? phb2 : res_x2[1]
res_y2 := ph ? phv2 : res_y2[1]

res_m = get_slope(res_x1, res_x2, res_y1, res_y2)
res_b = get_y_intercept(res_m, res_x1, res_y1)
res_y = get_y(res_m, res_b, bar_index)

// Support
sup_x1 := pl ? plb1 : sup_x1[1]
sup_y1 := pl ? plv1 : sup_y1[1]
sup_x2 := pl ? plb2 : sup_x2[1]
sup_y2 := pl ? plv2 : sup_y2[1]

sup_m = get_slope(sup_x1, sup_x2, sup_y1, sup_y2)
sup_b = get_y_intercept(sup_m, sup_x1, sup_y1)
sup_y = get_y(sup_m, sup_b, bar_index)

//// ARRAY - history trend lines ////
var int [] phb1_arr = array.new_int(25, 2)
var float [] phv1_arr = array.new_float(25, 2)
var int [] res_x1_arr = array.new_int(25, 2)
var float [] res_y1_arr = array.new_float(25, 2)
var int [] res_x2_arr = array.new_int(25, 2)
var float [] res_y2_arr = array.new_float(25, 2)

var int [] plb1_arr = array.new_int(25, 2)
var float [] plv1_arr = array.new_float(25, 2)
var int [] sup_x1_arr = array.new_int(25, 2)
var float [] sup_y1_arr = array.new_float(25, 2)
var int [] sup_x2_arr = array.new_int(25, 2)
var float [] sup_y2_arr = array.new_float(25, 2)

// Push pivots high and low into an array every time new pivots appear, array.push pushes element at the end of the array every time it "happens"
if ph
    array.insert(phb1_arr, 0, phb1)
    array.insert(phv1_arr, 0, phv1)
    array.insert(res_x1_arr, 0, res_x1)
    array.insert(res_y1_arr, 0, res_y1)
    array.insert(res_x2_arr, 0, res_x2)
    array.insert(res_y2_arr, 0, res_y2)
if pl
    array.insert(plb1_arr, 0, plb1)
    array.insert(plv1_arr, 0, plv1)
    array.insert(sup_x1_arr, 0, sup_x1)
    array.insert(sup_y1_arr, 0, sup_y1)
    array.insert(sup_x2_arr, 0, sup_x2)
    array.insert(sup_y2_arr, 0, sup_y2)

// Declare the coordinates varibales which will be assigned coordinates from array
int phb1_from_array = 0
float phv1_from_array = 0.0
int res_x1_from_array = 0
float res_y1_from_array = 0.0
int res_x2_from_array = 0
float res_y2_from_array = 0.0

int plb1_from_array = 0
float plv1_from_array = 0.0
int sup_x1_from_array = 0
float sup_y1_from_array = 0.0
int sup_x2_from_array = 0
float sup_y2_from_array = 0.0

// Initiate the array loop
for array_index = 0 to 24
    if array.size(phb1_arr) > 0 and array.size(phv1_arr) > 0 and array.size(plb1_arr) > 0 and array.size(plv1_arr) > 0 and array.size(res_x1_arr) > 0 and
     array.size(res_y1_arr) > 0 and array.size(res_x2_arr) > 0 and array.size(res_y2_arr) > 0 and array.size(sup_x1_arr) > 0 and
     array.size(sup_y1_arr) > 0 and array.size(sup_x2_arr) > 0 and array.size(sup_y2_arr) > 0
        phb1_from_array := array.get(phb1_arr, array_index)
        phv1_from_array := array.get(phv1_arr, array_index)
        res_x1_from_array := array.get(res_x1_arr, array_index)
        res_y1_from_array := array.get(res_y1_arr, array_index)
        res_x2_from_array := array.get(res_x2_arr, array_index)
        res_y2_from_array := array.get(res_y2_arr, array_index)

        plb1_from_array := array.get(plb1_arr, array_index)
        plv1_from_array := array.get(plv1_arr, array_index)
        sup_x1_from_array := array.get(sup_x1_arr, array_index)
        sup_y1_from_array := array.get(sup_y1_arr, array_index)
        sup_x2_from_array := array.get(sup_x2_arr, array_index)
        sup_y2_from_array := array.get(sup_y2_arr, array_index)

    // Re-calculate the trend lines stuff per newly grabbed coordinates from array
    res_m_from_array = get_slope(res_x1_from_array, res_x2_from_array, res_y1_from_array, res_y2_from_array)
    res_b_from_array = get_y_intercept(res_m_from_array, res_x1_from_array, res_y1_from_array)
    res_y_from_array = get_y(res_m_from_array, res_b_from_array, bar_index)

    sup_m_from_array = get_slope(sup_x1_from_array, sup_x2_from_array, sup_y1_from_array, sup_y2_from_array)
    sup_b_from_array = get_y_intercept(sup_m_from_array, sup_x1_from_array, sup_y1_from_array)
    sup_y_from_array = get_y(sup_m_from_array, sup_b_from_array, bar_index)

    // Draw the trend lines per coordinates/calculations grabbed from array, previous and all the history ones captured by the array
    //high (red) | per ARRAY
    red_line_arr = line.new(phb1_from_array, phv1_from_array, bar_index, res_y_from_array, color=color.rgb(143, 54, 54, 50),
     extend=extend.none, width=5)
    //high (red) | per ARRAY | cross catch
    red_line_arr_coordinates = line.get_price(red_line_arr, bar_index)
    //line.delete(pivot_connector_high_arr[1])

    //low (green) | per ARRAY
    green_line_arr = line.new(plb1_from_array, plv1_from_array, bar_index, sup_y_from_array, color=color.rgb(9, 134, 36, 50),
     extend=extend.none, width=5)
    //low (green) | per ARRAY | cross catch
    green_line_arr_coordinates = line.get_price(green_line_arr, bar_index)
    //line.delete(pivot_connector_low_arr[1])

    varip int position_order_counter = 0
    ////////////////////////////////////////////////
    // POSITION OPEN | LONG (red)
    if open > red_line_arr_coordinates and low <= red_line_arr_coordinates and high > red_line_arr_coordinates
        red_line_arr_cross_lbl = label.new(bar_index, red_line_arr_coordinates, text="red(↑)|price:" +
         str.tostring(math.round(red_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_up,
         color=color.rgb(193, 122, 0), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    // POSITION OPEN | SHORT (red)
    if open < red_line_arr_coordinates and high >= red_line_arr_coordinates and low < red_line_arr_coordinates
        red_line_arr_cross_lbl = label.new(bar_index, red_line_arr_coordinates, text="red(↓)|price:" +
         str.tostring(math.round(red_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_down,
         color=color.rgb(193, 122, 0), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    // POSITION OPEN | LONG (green)
    if open > green_line_arr_coordinates and low <= green_line_arr_coordinates and high > green_line_arr_coordinates
        green_line_arr_cross_lbl = label.new(bar_index, green_line_arr_coordinates, text="grn(↑)|price:" +
         str.tostring(math.round(green_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_up,
         color=color.rgb(70, 112, 201), textcolor=color.white, size=size.normal)
        position_order_counter += 1
    ////////////////////////////////////////////////
    // POSITION OPEN | SHORT (green)
    if open < green_line_arr_coordinates and high >= green_line_arr_coordinates and low < green_line_arr_coordinates
        green_line_arr_cross_lbl = label.new(bar_index, green_line_arr_coordinates, text="grn(↓)|price:" +
         str.tostring(math.round(green_line_arr_coordinates, 2)) + "|Count:" +
         str.tostring(position_order_counter), style=label.style_label_down,
         color=color.rgb(70, 112, 201), textcolor=color.white, size=size.normal)
        position_order_counter += 1


问:
Best practices to obtain peers from a torrent tracker?
Following the bittorrent protocol to write a bittorrent client and hit a wall: the announce request rarely returns with a single peer, and even that seems to ignore my handshake:

using the latest official Ubuntu torrent file (tried server, desktop, LTS - all same experience)

the first request to the announce URL comes back with a seemingly legit response, containing keys such as interval, complete, incomplete and peers

under peers every 4-8 attempt I get a single peer IP/port, the rest of the time it's empty

when initiating a handshake with the peer (using the <pstrlen><pstr><reserved><info_hash><peer_id> format), the socket connection (tried both TCP and UDP) can be established, writing the payload succeeds, but there is no response at all (not even with 3s TTL on it)

The torrent file - needless to say - works just fine with a proper torrent client, having many tens of peers at least.
My question is not to do a code review but rather if there is anything less known on what's a good practice on collecting reliable peers?

Should I poll the tracker for more peers and aggregate them through time? Is there a


问:
calculate user traffic and remaining free space in php

i m new to php.im using leecher script on my cpanel hosting account which doesn't have any database.

i can limit users  by time and traffic and space from config file .but users cant see how much they used of allowed traffic and how many days remained of their plan.

i decided to show them

days passed from creation time.
traffic used
remained traffic
disk in use
remained disk

the files that they send to host, is stored if ./file directory.
they can upload files to server and the delete files from their file manager page.
i want to calculate the traffic they use during the time the plan is active. and just print the results in filemanager page.

```<code>
<?php
$path = "./files";
$allowedtraffic = "10240"; //10gig
$creationdate = "01/02/2020"; for example this date the account is created for user
$remained_traffic = $allowedtraffic - $used_traffic;
    $units = explode(' ', 'B KB MB GB TB PB');
    $SIZE_LIMIT = 53687091200; // 5 GB
    $disk_used = foldersize("./file");
    $disk_remaining = $SIZE_LIMIT + $disk_used;

    echo("<html><body>");
    echo('traffic_consumed: ' ./// . ' .'GB'.<br>');
    echo('traffic_remained: ' . /// . ' .'GB'.<br>');
    echo( 'days passed: ' ./// . '<br>');
    echo('diskspace used: ' .///. MB'<br>');
    echo( 'diskspace left: ' ./// . MB'<br>');
    echo("</body></html>");

</code>```

i tried this code for showing the used disk and it works fine but i couldn't combine above code which i need,into single code

```<code><?php
    $units = explode(' ', 'B KB MB GB TB PB');
    $SIZE_LIMIT = 53687091200; // 5 GB
    $disk_used = foldersize("./hash");

    $disk_remaining = $SIZE_LIMIT + $disk_used;

    echo("<html><body>");
    echo('diskspace used: ' . format_size($disk_used) . '<br>');
    echo( 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>');
    echo("</body></html>");

function foldersize($path) {
    $total_size = 0;
    $files = scandir($path);
    $cleanPath = rtrim($path, '/'). '/';

    foreach($files as $t) {
        if ($t<>"." && $t<>"..") {
            $currentFile = $cleanPath . $t;
            if (is_dir($currentFile)) {
                $size = foldersize($currentFile);
                $total_size += $size;
            }
            else {
                $size = filesize($currentFile);
                $total_size += $size;
            }
        }
    }

    return $total_size;
}

function format_size($size) {
    global $units;

    $mod = 1024;

    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }

    $endIndex = strpos($size, ".")+3;

    return substr( $size, 0, $endIndex).' '.$units[$i];
}

?>
</code>```

Body:
i m new to php.im using leecher script on my cpanel hosting account which doesn't have any database.

i can limit users  by time and traffic and space from config file .but users cant see how much they used of allowed traffic and how many days remained of their plan.

i decided to show them

days passed from creation time.
traffic used
remained traffic
disk in use
remained disk

the files that they send to host, is stored if ./file directory.
they can upload files to server and the delete files from their file manager page.
i want to calculate the traffic they use during the time the plan is active. and just print the results in filemanager page.

<?php
$path = "./files";
$allowedtraffic = "10240"; //10gig
$creationdate = "01/02/2020"; for example this date the account is created for user
$remained_traffic = $allowedtraffic - $used_traffic;
    $units = explode(' ', 'B KB MB GB TB PB');
    $SIZE_LIMIT = 53687091200; // 5 GB
    $disk_used = foldersize("./file");
    $disk_remaining = $SIZE_LIMIT + $disk_used;

    echo("");
    echo('traffic_consumed: ' ./// . ' .'GB'.
');
    echo('traffic_remained: ' . /// . ' .'GB'.
');
    echo( 'days passed: ' ./// . '
');
    echo('diskspace used: ' .///. MB'
');
    echo( 'diskspace left: ' ./// . MB'
');
    echo("");

i tried this code for showing the used disk and it works fine but i couldn't combine above code which i need,into single code

<?php
    $units = explode(' ', 'B KB MB GB TB PB');
    $SIZE_LIMIT = 53687091200; // 5 GB
    $disk_used = foldersize("./hash");

    $disk_remaining = $SIZE_LIMIT + $disk_used;

    echo("");
    echo('diskspace used: ' . format_size($disk_used) . '
');
    echo( 'diskspace left: ' . format_size($disk_remaining) . '

');
    echo("");

function foldersize($path) {
    $total_size = 0;
    $files = scandir($path);
    $cleanPath = rtrim($path, '/'). '/';

    foreach($files as $t) {
        if ($t<>"." && $t<>"..") {
            $currentFile = $cleanPath . $t;
            if (is_dir($currentFile)) {
                $size = foldersize($currentFile);
                $total_size += $size;
            }
            else {
                $size = filesize($currentFile);
                $total_size += $size;
            }
        }
    }

    return $total_size;
}

function format_size($size) {
    global $units;

    $mod = 1024;

    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }

    $endIndex = strpos($size, ".")+3;

    return substr( $size, 0, $endIndex).' '.$units[$i];
}

?>


问:
what is the easist way to mimic pv in bash when using python subprocess?
I want to reduce the dependency on system package. thus I do not want to depend on pv. I tried with tqdm. However, I found the speed is much slower than pv. Currently I found it seems the stdout.read() is much slower than pv read from stdout. I did tests like following:

```<code>def test_pv_speed(path: str):
    with subprocess.Popen(['tar', '-c', path], stdout=subprocess.PIPE) as tar:
        t_st = timeit.default_timer()

        pv = subprocess.Popen(
            ["pv", "-f"],
            stdin=tar.stdout,
            stdout=subprocess.DEVNULL,
        )
        pv.wait()
        dt = timeit.default_timer() - t_st
        print(dt)

def test_stdout_read_speed(path: str):
    with subprocess.Popen(['tar', '-c', path], bufsize=-1, stdout=subprocess.PIPE) as tar:
        t_st = timeit.default_timer()
        block_size = 1024**3 # 1GB
        while _block:=tar.stdout.read(block_size):
            pass
        dt = timeit.default_timer() - t_st
        print(dt)

</code>```

I used 3GB data, the data are in a ram disk. The test_stdout_read_speed() need almost 2x time. Is this expected or there is something I can improve?

I tried different kind of bufsize: -1, 0, 4096, 100M or others, really do not make any difference. I think this is because PIPE actually is a buffer already. block_size also has no effect. So it cannot be the loop overhead. It seems like the read() itself is much slower.

Body:
I want to reduce the dependency on system package. thus I do not want to depend on pv. I tried with tqdm. However, I found the speed is much slower than pv. Currently I found it seems the stdout.read() is much slower than pv read from stdout. I did tests like following:

def test_pv_speed(path: str):
    with subprocess.Popen(['tar', '-c', path], stdout=subprocess.PIPE) as tar:
        t_st = timeit.default_timer()

        pv = subprocess.Popen(
            ["pv", "-f"],
            stdin=tar.stdout,
            stdout=subprocess.DEVNULL,
        )
        pv.wait()
        dt = timeit.default_timer() - t_st
        print(dt)

def test_stdout_read_speed(path: str):
    with subprocess.Popen(['tar', '-c', path], bufsize=-1, stdout=subprocess.PIPE) as tar:
        t_st = timeit.default_timer()
        block_size = 1024**3 # 1GB
        while _block:=tar.stdout.read(block_size):
            pass
        dt = timeit.default_timer() - t_st
        print(dt)

I used 3GB data, the data are in a ram disk. The test_stdout_read_speed() need almost 2x time. Is this expected or there is something I can improve?

I tried different kind of bufsize: -1, 0, 4096, 100M or others, really do not make any difference. I think this is because PIPE actually is a buffer already. block_size also has no effect. So it cannot be the loop overhead. It seems like the read() itself is much slower.


问:
Anaconda or/and PIP
I have installed my packages via Anaconda and pip so far. Unfortunately, this has often led to inconsistencies in the past and the installations were tedious and annoying. I want to improve something with my new computer and am now considering whether I should do everything via pip and do without anaconda completely.
How do you do it? Do you mix anaconda and pip?
Do you only create the environments with anaconda and then install everything with pip?
What would you advise me to do?

Thanks a lot!

masterkey

Title: Anaconda or/and PIP


问:
python mysql.connector returns none as function result
I've got a function on MySQL server (Percona 5.x) and it works fine:

```<code>SET @id := 15037051;
SELECT get90DaysCount(@id) as get90DaysCount;
</code>```

But when I try to invoke this function from python using mysql.connector:

```<code>query = "SELECT get90DaysCount(15037051) as get90DaysCount";
self.cursor.execute(query)
records = self.cursor.fetchone()
print(records)
</code>```

I get None:

```<code>((None,),)
</code>```

All other values in complex query in which this function is beeing called are fine.

Tried to invoke other functions, and they work fine too. For example:

```<code>query = "SELECT getAverageMonthlyPayment(15037051) as p"
self.cursor.execute(query)
records = self.cursor.fetchone()
print(records)
</code>```

Result:

```<code>(2795.1201171875,)
</code>```

UPD. Ta-da! An here is a result of this query in console mysql client:

```<code>MySQL > SELECT get90DaysCount(15037051) as get90DaysCount;
+----------------+
| get90DaysCount |
+----------------+
| NULL           |
+----------------+
1 row in set (0.098 sec)
</code>```

Would be grateful for any ideas.

UPD2. Function code:

```<code>create function get90DaysCount(contract_id int) returns date
BEGIN
        DECLARE r DATE DEFAULT NULL;

        SELECT
            DATE_ADD(s.action_date, INTERVAL 88 DAY),
                INTO r
        FROM status_changes AS s
        WHERE
            s.c_id=@contract_id
        AND (
                SELECT COUNT(id) as count
                FROM status_changes AS s1
                WHERE
                    s1.c_id=@contract_id
                AND s1.status_new IN ('closed')
                AND datediff(s1.action_date, s.action_date) < 90
                AND datediff(s1.action_date, s.action_date) > 0
            ) = 0
        LIMIT 1;
        RETURN r;
    END;
</code>```

UPD3:
May be this could help:

Server version: 5.7.34-37-log Percona Server (GPL), Revision 6081c95

mysql (local client) Ver 8.0.31-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu))

DataGrip 2022.3.1 (Build #DB-223.8214.6). Runtime version: 17.0.5+1-b653.14 amd64

Linux *** 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Body:
I've got a function on MySQL server (Percona 5.x) and it works fine:

SET @id := 15037051;
SELECT get90DaysCount(@id) as get90DaysCount;

But when I try to invoke this function from python using mysql.connector:

query = "SELECT get90DaysCount(15037051) as get90DaysCount";
self.cursor.execute(query)
records = self.cursor.fetchone()
print(records)

I get None:

((None,),)

All other values in complex query in which this function is beeing called are fine.

Tried to invoke other functions, and they work fine too. For example:

query = "SELECT getAverageMonthlyPayment(15037051) as p"
self.cursor.execute(query)
records = self.cursor.fetchone()
print(records)

Result:

(2795.1201171875,)

UPD. Ta-da! An here is a result of this query in console mysql client:

MySQL > SELECT get90DaysCount(15037051) as get90DaysCount;
+----------------+
| get90DaysCount |
+----------------+
| NULL           |
+----------------+
1 row in set (0.098 sec)

Would be grateful for any ideas.

UPD2. Function code:

create function get90DaysCount(contract_id int) returns date
BEGIN
        DECLARE r DATE DEFAULT NULL;

        SELECT
            DATE_ADD(s.action_date, INTERVAL 88 DAY),
                INTO r
        FROM status_changes AS s
        WHERE
            s.c_id=@contract_id
        AND (
                SELECT COUNT(id) as count
                FROM status_changes AS s1
                WHERE
                    s1.c_id=@contract_id
                AND s1.status_new IN ('closed')
                AND datediff(s1.action_date, s.action_date) < 90
                AND datediff(s1.action_date, s.action_date) > 0
            ) = 0
        LIMIT 1;
        RETURN r;
    END;

UPD3:
May be this could help:

Server version: 5.7.34-37-log Percona Server (GPL), Revision 6081c95

mysql (local client) Ver 8.0.31-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu))

DataGrip 2022.3.1 (Build #DB-223.8214.6). Runtime version: 17.0.5+1-b653.14 amd64

Linux *** 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux


问:
How do I import a spritesheet to Unity with inconsistent padding but included json metadata, so I can use its TileMap functionalites?
I am working with Unity for the first time, I want to use the TileMap system so I could easily script in parts of the map. I got a spritesheet map from an old HumbleBundle deal, I want to try to import the spritesheet into unity, each sprite is in a 16 by 16, but the padding differs a few times so I am not sure how to use it so each sprite is loaded in corrected from the same sheet.

Another thing to note, if it helps, is that the spritesheet did come included with a json file that has the sprite's metadata.

Example:

```<code>    "bg_chain_hanging": {
        "frame": {
            "x": 176,
            "y": 116,
            "width": 16,
            "height": 16
        },
        "sourceSize": {
            "width": 16,
            "height": 16
        },
        "rotated": false
    },
    "bg_chain_hanging_end_A": {
        "frame": {
            "x": 192,
            "y": 98,
            "width": 16,
            "height": 16
        },
        "sourceSize": {
            "width": 16,
            "height": 16
        },
        "rotated": false
    }
</code>```

I have imported the spritesheet into Unity, but when setting it to be multiple sprites, I don't see any option in the sprite editor to do any sort of way to import them all at once, even if I have to select a sprite one by one manually with the provided metadata. I am new to Unity, so it might be something obvious.

Body:
I am working with Unity for the first time, I want to use the TileMap system so I could easily script in parts of the map. I got a spritesheet map from an old HumbleBundle deal, I want to try to import the spritesheet into unity, each sprite is in a 16 by 16, but the padding differs a few times so I am not sure how to use it so each sprite is loaded in corrected from the same sheet.

Another thing to note, if it helps, is that the spritesheet did come included with a json file that has the sprite's metadata.

Example:

    "bg_chain_hanging": {
        "frame": {
            "x": 176,
            "y": 116,
            "width": 16,
            "height": 16
        },
        "sourceSize": {
            "width": 16,
            "height": 16
        },
        "rotated": false
    },
    "bg_chain_hanging_end_A": {
        "frame": {
            "x": 192,
            "y": 98,
            "width": 16,
            "height": 16
        },
        "sourceSize": {
            "width": 16,
            "height": 16
        },
        "rotated": false
    }

I have imported the spritesheet into Unity, but when setting it to be multiple sprites, I don't see any option in the sprite editor to do any sort of way to import them all at once, even if I have to select a sprite one by one manually with the provided metadata. I am new to Unity, so it might be something obvious.


问:
Setup Project custom action for folder permissions
I'm building a Setup Project so I can ship my WinUI/WPF application. In said applicaiton I use some NuGet packages that creat files on the executable's location (folder) -- these are for MSAL and WebView2. However, Windows sets only Read access to folders on the Program Files folder, so I wanted to create a custom action that gives write permission to the folder throughout the installation.

Most solutions out there are extremely outdated (.NET framework dependent) or tangents to the overall problem.

I have tried creating a Console Application, writing the following code, shipping it as a DLL/EXE and adding it as a Custom Action. My application installed but still did not have write permissions.

```<code>   static void Main(string[] args)
   {
        string directory = args[0];
        DirectoryInfo directoryInfo = new DirectoryInfo(directory);

        // This gets the "Authenticated Users" group, no matter what it's called
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

        // Create the rules
        FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);

        if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
        {
            // Get your file's ACL
            DirectorySecurity fsecurity = FileSystemAclExtensions.GetAccessControl(directoryInfo);

            // Add the new rule to the ACL
            fsecurity.AddAccessRule(writerule);

            // Set the ACL back to the file
            FileSystemAclExtensions.SetAccessControl(directoryInfo, fsecurity);
        }
    }
</code>```

This code was based on the following thread: https://stackoverflow.com/a/10540927/16751261

Body:
I'm building a Setup Project so I can ship my WinUI/WPF application. In said applicaiton I use some NuGet packages that creat files on the executable's location (folder) -- these are for MSAL and WebView2. However, Windows sets only Read access to folders on the Program Files folder, so I wanted to create a custom action that gives write permission to the folder throughout the installation.

Most solutions out there are extremely outdated (.NET framework dependent) or tangents to the overall problem.

I have tried creating a Console Application, writing the following code, shipping it as a DLL/EXE and adding it as a Custom Action. My application installed but still did not have write permissions.

   static void Main(string[] args)
   {
        string directory = args[0];
        DirectoryInfo directoryInfo = new DirectoryInfo(directory);

        // This gets the "Authenticated Users" group, no matter what it's called
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

        // Create the rules
        FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);

        if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
        {
            // Get your file's ACL
            DirectorySecurity fsecurity = FileSystemAclExtensions.GetAccessControl(directoryInfo);

            // Add the new rule to the ACL
            fsecurity.AddAccessRule(writerule);

            // Set the ACL back to the file
            FileSystemAclExtensions.SetAccessControl(directoryInfo, fsecurity);
        }
    }

This code was based on the following thread: https://stackoverflow.com/a/10540927/16751261