问:
Validating input in template-driven forms : Directive return true but submit button still invisible
```<code>`Validating input in template-driven forms : Directive return true but submit button still invisible
</code>```

<textarea class="form-control-textarea-pkgLfCle" formControlName="ACCtLifeCycleJson" hasACCtLifeCycleJson
[(ngModel)]="ACCtLifeCycleJsonValue" id="AcctLifeCycleTypeInput">

```<code>@Directive({
selector: '[hasACCtLifeCycleJson]',
 providers: [{
    provide: NG_VALIDATORS,
    useExisting: ValidateHasJsonStructure,
    multi: true
  }]
})
export class ValidateHasJsonStructure implements Validator {

  @Input() hasACCtLifeCycleJson;`
  //pass textarea as parameter in control
  validate(control: AbstractControl): { [key: string]: any } | null {
    console.log(control.value);
    if (typeof control.value !== 'string') {
        return { 'hasACCtLifeCycleJson': false };
    }
    try {
        const result = JSON.parse(control.value);
        if (result != null) {
            return { 'hasACCtLifeCycleJson': true};
        }
    } catch (err) {
        return { 'hasACCtLifeCycleJson': false };
    }
    return ;

}
</code>```

submit button should be shows as visible after inserting the valid json.`

Body:
`Validating input in template-driven forms : Directive return true but submit button still invisible

<textarea class="form-control-textarea-pkgLfCle" formControlName="ACCtLifeCycleJson" hasACCtLifeCycleJson
[(ngModel)]="ACCtLifeCycleJsonValue" id="AcctLifeCycleTypeInput">

@Directive({
selector: '[hasACCtLifeCycleJson]',
 providers: [{
    provide: NG_VALIDATORS,
    useExisting: ValidateHasJsonStructure,
    multi: true
  }]
})
export class ValidateHasJsonStructure implements Validator {

  @Input() hasACCtLifeCycleJson;`
  //pass textarea as parameter in control
  validate(control: AbstractControl): { [key: string]: any } | null {
    console.log(control.value);
    if (typeof control.value !== 'string') {
        return { 'hasACCtLifeCycleJson': false };
    }
    try {
        const result = JSON.parse(control.value);
        if (result != null) {
            return { 'hasACCtLifeCycleJson': true};
        }
    } catch (err) {
        return { 'hasACCtLifeCycleJson': false };
    }
    return ;

}

submit button should be shows as visible after inserting the valid json.`


来源: stackexchange

问:
error: failed processing manifest while creating release in android studio
While creating release version of app android studio showing this error

This is my manifest

Can anyone tell me what is the problem here. I've tried some solutions from stack overflow but they are not working!

Tried multiple solutions from stack overflow

ContentLicense: CC BY-SA 4.0


问:
MQL4 gets different data than the MT4 History Center shows
I'm quite new to MQL so this may be a misunderstanding.

This code:

Print( TimeToStr( iTime(NULL,PERIOD_M5,i), TIME_DATE|TIME_MINUTES), iOpen(NULL,PERIOD_M5,i),  iHigh(NULL,PERIOD_M5,i),  iLow(NULL,PERIOD_M5,i),  iClose(NULL,PERIOD_M5,i) );

Prints this:
2023.01.05 23:25, 0.91648, 0.91678, 0.91636, 0.91676

If I export data from the History Center I get slightly different numbers:

2023.01.05T23:25, 0.91646 ,0.91675, 0.91633 ,0.91675, 146

The values are just a tiny bit smaller. This is consistent - ALL of the values exported from the History Center are a bit lower than what I see when I examine the data with iOpen() etc. The difference seems to range from 0.1 to 0.3 pips.

I assume this is a Bid vs Ask thing. Is it? I understand the iOpen() etc returns Bid prices. But does the History database contain both Bid and Ask? Is there a way to see both prices?

Or it it just guessing? If so, it does not seem to be adjusting the prices consistently.

Edit: I am running in the Strategy Tester.

Edit2: Today I downloaded a bunch of M1 data from Dukascopy and imported it into MT4 History Center. Now I get exactly the results I expect from my program.

But my question stands, about the data MT4 downloads from the broker.


问:
Update Cache after POST and Update using Output Cache .net core 7
I have implemented a custom policy for my .net core 7 web api using Output Cache which serves as the base policy for all controllers

```<code>services.AddCors();
services.AddOutputCache(opt=>
{
   opt.AddBasePolicy(OutputCachePolicy.Instance);
});
</code>```

I want to update or refresh the cache whenever a new record is added or updated, but dont know how achieve this

Body:
I have implemented a custom policy for my .net core 7 web api using Output Cache which serves as the base policy for all controllers

services.AddCors();
services.AddOutputCache(opt=>
{
   opt.AddBasePolicy(OutputCachePolicy.Instance);
});

I want to update or refresh the cache whenever a new record is added or updated, but dont know how achieve this


问:
How do I install GTK+ 4 to work with Code::Blocks Windows 10
I have absolutely no clue how to install GTK+ 4 to work with Code::Blocks on Windows 10.

Can someone please write up some instructions on how to install GTK+ 4 and specifically how to connect everything to Code::Blocks.

I'm new to the program and would appreciate the help.

I installed the MSYS2 version of GTK+ 4 from the gtk.org website and can't find the files I need to configure GTK4+ to Code::Blocks


问:
Textblob tweets issue : TypeError: The `text` argument passed to `__init__(text)` must be a string, not <class 'float'>
I am loading a txt file containig news data. Here is a link to access that data: Dataset

Now, what I am trying to do is obtaining a time series of frequencies of some particular words, so I am using Textblob package. The code used for that purpose is the following:

```<code>import pandas as pd
import re
from datetime import datetime
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from textblob import TextBlob

df = pd.read_csv("diarios2011(lanacion) (1).csv")

df.columns = ['indice','date','id','text']
df.head(5)
df['new date'] = pd.to_datetime(df['date']).dt.to_period(freq = 'D')
</code>```
```<code>reindexed_data = df['text']
reindexed_data.index = df['new date']
reindexed_data.head()

import nltk
nltk.download('punkt')

Argentina = [0]*reindexed_data.shape[0]
Rofex = [0]*reindexed_data.shape[0]

for i in range(reindexed_data.shape[0]):
    words = TextBlob(reindexed_data[i]).words
    for word in words:
        if word == "argentina" or word == "Arg": Argentina[i]=1
        if word == "rofex": Rofex[i]=1

keywords = pd.DataFrame({'text':reindexed_data,
                        'Argentina':Argentina,
                        'Rofex':Rofex

                         },
                        index=reindexed_data.index)
</code>```

However I've got this error:

```<code>TypeError: The text argument passed to __init__(text) must be a string, not <class 'float'>
</code>```

Do you have any ideas? The dataset used is in link.

Thank you so much in advance!

Body:
I am loading a txt file containig news data. Here is a link to access that data: Dataset

Now, what I am trying to do is obtaining a time series of frequencies of some particular words, so I am using Textblob package. The code used for that purpose is the following:

import pandas as pd
import re
from datetime import datetime
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from textblob import TextBlob

df = pd.read_csv("diarios2011(lanacion) (1).csv")

df.columns = ['indice','date','id','text']
df.head(5)
df['new date'] = pd.to_datetime(df['date']).dt.to_period(freq = 'D')

reindexed_data = df['text']
reindexed_data.index = df['new date']
reindexed_data.head()

import nltk
nltk.download('punkt')

Argentina = [0]*reindexed_data.shape[0]
Rofex = [0]*reindexed_data.shape[0]

for i in range(reindexed_data.shape[0]):
    words = TextBlob(reindexed_data[i]).words
    for word in words:
        if word == "argentina" or word == "Arg": Argentina[i]=1
        if word == "rofex": Rofex[i]=1

keywords = pd.DataFrame({'text':reindexed_data,
                        'Argentina':Argentina,
                        'Rofex':Rofex

                         },
                        index=reindexed_data.index)

However I've got this error:

TypeError: The text argument passed to __init__(text) must be a string, not <class 'float'>

Do you have any ideas? The dataset used is in link.

Thank you so much in advance!


问:
No suitable user-defined conversion from "cv::Matx<double, 2, 1>" to "cv::Vec2d" exists
I have to perform the following per-element product:

```<code>out = dist * v1 * v2 / res;
</code>```

where:

dist is a scalar (double)

v1, v2, v3 are cv::Vec2d (vector of 2 double)

My very easy peasy code with opencv:

```<code> #include <opencv2/core.hpp>
 cv::Vec2d test() {
     double dist = 1.0;
     cv::Vec2d v1(1.0, 1.0), v2(1.0, 1.0);
     return (dist * v1).mul(v2).div(v3);
 }
</code>```

The error I got (compiling with cl.exe under VC17):

```<code>E0312   no suitable user-defined conversion from "cv::Matx<double, 2, 1>" to "cv::Vec2d" exists
</code>```

Breaking down the operations, the problem is with .div, while .mul works fine.

Now, looking at the doc, I can note:

cv::Vec<_Tp,cn> is inherited from cv::Matx<_Tp,cn,1>, thus cv::Vec2d should be the same as cv::Matx<double,2,1>. Am I missing something?

cv::Vec<_Tp,cn> is cited into the doc, but I've not found either the declaration of cv::Vec<_Tp,cn>::div nor a mention to it or to the per-element division operation in general. However the method does exists.

Any idea where I'm wrong and how to (easily) fix?

Side Notes

Cross-posted on OpenCV Forum

Issue opened on GitHub

Body:
I have to perform the following per-element product:

out = dist * v1 * v2 / res;

where:

dist is a scalar (double)

v1, v2, v3 are cv::Vec2d (vector of 2 double)

My very easy peasy code with opencv:

 #include <opencv2/core.hpp>
 cv::Vec2d test() {
     double dist = 1.0;
     cv::Vec2d v1(1.0, 1.0), v2(1.0, 1.0);
     return (dist * v1).mul(v2).div(v3);
 }

The error I got (compiling with cl.exe under VC17):

E0312   no suitable user-defined conversion from "cv::Matx<double, 2, 1>" to "cv::Vec2d" exists

Breaking down the operations, the problem is with .div, while .mul works fine.

Now, looking at the doc, I can note:

cv::Vec<_Tp,cn> is inherited from cv::Matx<_Tp,cn,1>, thus cv::Vec2d should be the same as cv::Matx<double,2,1>. Am I missing something?

cv::Vec<_Tp,cn> is cited into the doc, but I've not found either the declaration of cv::Vec<_Tp,cn>::div nor a mention to it or to the per-element division operation in general. However the method does exists.

Any idea where I'm wrong and how to (easily) fix?

Side Notes

Cross-posted on OpenCV Forum

Issue opened on GitHub


问:
Proper way to upload markdown to a field in NetBox
I am trying to upload a comment to a device's comment field in NetBox which takes markdown language.

With the below file content, the comment gets inserted and displays the comment in NetBox as just text (the lines in the file are doublespaced otherwise the text only comes out in one continuous line):

File Contents:

```<code>User Name: user

Password: password

IPv4: x.x.x.x

IPv6: x::x
</code>```

The resulting comment field in NetBox is this:

When I try to add markdown like below, the upload becomes an empty string and fails with curl stderr       :  /bin/sh: 1: nUser: not found

This results in the comment field having None for a value:

The curl command I am using is this:

```<code>curl
--insecure \
--verbose \
--request PATCH \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--header "Authorization:Token token" \
--user "user:password" \
--url "https://x.x.x.x/api/dcim/devices/{device_id}/" \
--data-binary @input_file
</code>```

What is the proper way to format the file / string to insert into a markdown field in NetBox?

Body:
I am trying to upload a comment to a device's comment field in NetBox which takes markdown language.

With the below file content, the comment gets inserted and displays the comment in NetBox as just text (the lines in the file are doublespaced otherwise the text only comes out in one continuous line):

File Contents:

User Name: user

Password: password

IPv4: x.x.x.x

IPv6: x::x

The resulting comment field in NetBox is this:

When I try to add markdown like below, the upload becomes an empty string and fails with curl stderr       :  /bin/sh: 1: nUser: not found

This results in the comment field having None for a value:

The curl command I am using is this:

curl
--insecure \
--verbose \
--request PATCH \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--header "Authorization:Token token" \
--user "user:password" \
--url "https://x.x.x.x/api/dcim/devices/{device_id}/" \
--data-binary @input_file

What is the proper way to format the file / string to insert into a markdown field in NetBox?


问:
Xcode Swift Error: Framework not found FirebaseAnalytics
I tried adding FirebaseAnalytics now in getting this error.

This is my pod file:

And this is the error:

Framework not found FirebaseAnalytics

tried adding $(inherited) in the build settings. tried deleting everything and redoing it.


问:
How can I replace the text in a .pptx file with the phppresentation library?
I try to replace the text with another one with the phppresentation library, but it replaced my text in my file with empty $text_element_v->setText($new_text);

Here is my code:

```<code>$pptx = 'test/example.pptx';
if (!file_exists('lorem.pptx')) {
    copy($pptx, 'lorem.pptx');
}
$pptReader = IOFactory::createReader('PowerPoint2007'); // PowerPoint97, PowerPoint2007
$oPHPPresentation = $pptReader->load('lorem.pptx');
$property = $oPHPPresentation->getDocumentProperties();
$slides = $oPHPPresentation->getAllSlides();

foreach ($slides as $slide_k => $slide_v) {
  $shapes = $slides[$slide_k]->getShapeCollection();
  foreach ($shapes as $shape_k => $shape_v) {
    $shape = $shapes[$shape_k];
    // echo get_class($shape).'</br>';

    if($shape instanceof PhpOffice\PhpPresentation\Shape\RichText){
        $paragraphs = $shapes[$shape_k]->getParagraphs();
        foreach ($paragraphs as $paragraph_k => $paragraph_v) {
            $text_elements = $paragraph_v->getRichTextElements();
            foreach ($text_elements as $text_element_k => $text_element_v) {

                $text = $text_element_v->getText();
                $new_text = str_replace('Lorem', 'Esfera', $text);
                $text_element_v->setText($new_text);

            }
       }
    }
  }
}

</code>```

Here is the file that is empty :

What should I do please?

Body:
I try to replace the text with another one with the phppresentation library, but it replaced my text in my file with empty $text_element_v->setText($new_text);

Here is my code:

$pptx = 'test/example.pptx';
if (!file_exists('lorem.pptx')) {
    copy($pptx, 'lorem.pptx');
}
$pptReader = IOFactory::createReader('PowerPoint2007'); // PowerPoint97, PowerPoint2007
$oPHPPresentation = $pptReader->load('lorem.pptx');
$property = $oPHPPresentation->getDocumentProperties();
$slides = $oPHPPresentation->getAllSlides();

foreach ($slides as $slide_k => $slide_v) {
  $shapes = $slides[$slide_k]->getShapeCollection();
  foreach ($shapes as $shape_k => $shape_v) {
    $shape = $shapes[$shape_k];
    // echo get_class($shape).'
';

    if($shape instanceof PhpOffice\PhpPresentation\Shape\RichText){
        $paragraphs = $shapes[$shape_k]->getParagraphs();
        foreach ($paragraphs as $paragraph_k => $paragraph_v) {
            $text_elements = $paragraph_v->getRichTextElements();
            foreach ($text_elements as $text_element_k => $text_element_v) {

                $text = $text_element_v->getText();
                $new_text = str_replace('Lorem', 'Esfera', $text);
                $text_element_v->setText($new_text);

            }
       }
    }
  }
}

Here is the file that is empty :

What should I do please?


问:
Converting generative transformer model from keras to PyTorch
I would like to re-create the following keras model in PyTorch.

```<code>vocab_size = 22
maxlen = 200
embed_dim = 256
num_heads = 2
feed_forward_dim = 256
batch_size = 128
decoders = 5

def create_model():
    inputs = layers.Input(shape=(maxlen,), dtype=tf.int32)
    embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
    x = embedding_layer(inputs)

    decoder_blocks = []
    for i in range(decoders):
      decoder_blocks.append(DecoderBlock(embed_dim, num_heads, feed_forward_dim))

    for i in range(len(decoder_blocks)):
      x = decoder_blocks[i](x)

    outputs = layers.Dense(vocab_size)(x)
    model = keras.Model(inputs=inputs, outputs=[outputs, x])
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=lr_schedule),
        loss=[loss_fn, None],
    )
    return model

model = create_model()
</code>```

Here are the Decoder and the TokenAndPositionEmbedding layers along with the Causal Attention Mask

```<code>def causal_attention_mask(batch_size, n_dest, n_src, dtype):
    i = tf.range(n_dest)[:, None]
    j = tf.range(n_src)
    m = i >= j - n_src + n_dest
    mask = tf.cast(m, dtype)
    mask = tf.reshape(mask, [1, n_dest, n_src])
    mult = tf.concat(
        [tf.expand_dims(batch_size, -1), tf.constant([1, 1], dtype=tf.int32)], 0
    )
    return tf.tile(mask, mult)

class DecoderBlock(layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
        super(DecoderBlock, self).__init__()
        self.att = layers.MultiHeadAttention(num_heads, embed_dim)
        self.ffn = keras.Sequential(
            [layers.Dense(ff_dim, activation="relu"), layers.Dense(embed_dim),]
        )
        self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
        self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
        self.dropout1 = layers.Dropout(rate)
        self.dropout2 = layers.Dropout(rate)

    def call(self, inputs):
        input_shape = tf.shape(inputs)
        batch_size = input_shape[0]
        seq_len = input_shape[1]
        causal_mask = causal_attention_mask(batch_size, seq_len, seq_len, tf.bool)
        attention_output = self.att(inputs, inputs, attention_mask=causal_mask)
        attention_output = self.dropout1(attention_output)
        out1 = self.layernorm1(inputs + attention_output)
        ffn_output = self.ffn(out1)
        ffn_output = self.dropout2(ffn_output)
        return self.layernorm2(out1 + ffn_output)

class TokenAndPositionEmbedding(layers.Layer):
    def __init__(self, maxlen, vocab_size, embed_dim):
        super(TokenAndPositionEmbedding, self).__init__()
        self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim)
        self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)

    def call(self, x):
        maxlen = tf.shape(x)[-1]
        positions = tf.range(start=0, limit=maxlen, delta=1)
        positions = self.pos_emb(positions)
        x = self.token_emb(x)
        return x + positions
</code>```

For reference, this code is copied directly from: https://keras.io/examples/generative/text_generation_with_miniature_gpt/

I have tried to create equivalent architecture in PyTorch using nn.TransformerDecoderLayer. Apologies for not including my own code, but I have been completely unsuccessful.

Body:
I would like to re-create the following keras model in PyTorch.

vocab_size = 22
maxlen = 200
embed_dim = 256
num_heads = 2
feed_forward_dim = 256
batch_size = 128
decoders = 5

def create_model():
    inputs = layers.Input(shape=(maxlen,), dtype=tf.int32)
    embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
    x = embedding_layer(inputs)

    decoder_blocks = []
    for i in range(decoders):
      decoder_blocks.append(DecoderBlock(embed_dim, num_heads, feed_forward_dim))

    for i in range(len(decoder_blocks)):
      x = decoder_blocks[i](x)

    outputs = layers.Dense(vocab_size)(x)
    model = keras.Model(inputs=inputs, outputs=[outputs, x])
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=lr_schedule),
        loss=[loss_fn, None],
    )
    return model

model = create_model()

Here are the Decoder and the TokenAndPositionEmbedding layers along with the Causal Attention Mask

def causal_attention_mask(batch_size, n_dest, n_src, dtype):
    i = tf.range(n_dest)[:, None]
    j = tf.range(n_src)
    m = i >= j - n_src + n_dest
    mask = tf.cast(m, dtype)
    mask = tf.reshape(mask, [1, n_dest, n_src])
    mult = tf.concat(
        [tf.expand_dims(batch_size, -1), tf.constant([1, 1], dtype=tf.int32)], 0
    )
    return tf.tile(mask, mult)

class DecoderBlock(layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
        super(DecoderBlock, self).__init__()
        self.att = layers.MultiHeadAttention(num_heads, embed_dim)
        self.ffn = keras.Sequential(
            [layers.Dense(ff_dim, activation="relu"), layers.Dense(embed_dim),]
        )
        self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
        self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
        self.dropout1 = layers.Dropout(rate)
        self.dropout2 = layers.Dropout(rate)

    def call(self, inputs):
        input_shape = tf.shape(inputs)
        batch_size = input_shape[0]
        seq_len = input_shape[1]
        causal_mask = causal_attention_mask(batch_size, seq_len, seq_len, tf.bool)
        attention_output = self.att(inputs, inputs, attention_mask=causal_mask)
        attention_output = self.dropout1(attention_output)
        out1 = self.layernorm1(inputs + attention_output)
        ffn_output = self.ffn(out1)
        ffn_output = self.dropout2(ffn_output)
        return self.layernorm2(out1 + ffn_output)

class TokenAndPositionEmbedding(layers.Layer):
    def __init__(self, maxlen, vocab_size, embed_dim):
        super(TokenAndPositionEmbedding, self).__init__()
        self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim)
        self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)

    def call(self, x):
        maxlen = tf.shape(x)[-1]
        positions = tf.range(start=0, limit=maxlen, delta=1)
        positions = self.pos_emb(positions)
        x = self.token_emb(x)
        return x + positions

For reference, this code is copied directly from: https://keras.io/examples/generative/text_generation_with_miniature_gpt/

I have tried to create equivalent architecture in PyTorch using nn.TransformerDecoderLayer. Apologies for not including my own code, but I have been completely unsuccessful.


问:
Prediction function in R
I am working on a data set of employed and unemployed people. After estimation of parameters for (log)wages I am trying to predict values of (log)wages for unemployed people that would correspond with results that I have (in data set values for unemployed are N/A).

After using function predict I still get predictions only for employed people. Does anyone know how to get the full column of "predML"? Thank you in advance!!

```<code>ml_restricted <- selection(employed ~ schooling + age + agesq + married, logwage ~ schooling + age + agesq, data)
summary(ml_restricted)

# find predicted values

predML <- predict(ml_restricted)

data <- cbind(data, predML)

employed2 <- ifelse(data$employed == 1, "employed", "unemployed")

data <- cbind(data, employed2)
</code>```

Title: Prediction function in R

Body:
I am working on a data set of employed and unemployed people. After estimation of parameters for (log)wages I am trying to predict values of (log)wages for unemployed people that would correspond with results that I have (in data set values for unemployed are N/A).

After using function predict I still get predictions only for employed people. Does anyone know how to get the full column of "predML"? Thank you in advance!!

ml_restricted <- selection(employed ~ schooling + age + agesq + married, logwage ~ schooling + age + agesq, data)
summary(ml_restricted)

# find predicted values

predML <- predict(ml_restricted)

data <- cbind(data, predML)

employed2 <- ifelse(data$employed == 1, "employed", "unemployed")

data <- cbind(data, employed2)


问:
Tell WolframAlpha to show data field?
I'm trying to find an approximation for a function that's near y = x^(1/5).

Unfortunately, polynomial approximations for functions below degree 1 don't work. These work if I specify the form manually, but are off by about 5% in the ranges I care about:

```<code>FindFit[{{1,1},{1.6875,2},{4.234567901,3},{10.71875,4},{25,5},{53.1797839,6},{104.142857,7},{190.10937,8},{327.189300,9},{535.9375,10}},{a*x^(1/5) + b*x^(1/3) + c*x + d*(1/x) + e},{a,b,c,d,e},x]
1.6616*x^(1/5) + 0.570547*x^(1/3) + -0.00136863*x + -1.445*(1/x) + 0.251113

NonlinearModelFit[{{1,1},{1.6875,2},{4.234567901,3},{10.71875,4},{25,5},{53.1797839,6},{104.142857,7},{190.10937,8},{327.189300,9},{535.9375,10}},{a*x^(1/5)+b*x^(1/3)+c*x+d*(1/x)+e},{a,b,c,d,e},x]
0.251113 - 0.00136863 x + 0.570547 x^(1/3) + 1.6616 x^(1/5) - 1.445/x
</code>```

FindFit example see https://reference.wolfram.com/language/ref/FindFit.html

NonlinearModelFit example see https://reference.wolfram.com/language/ref/NonlinearModelFit.html

The problem is that I need to explore more forms or provide more data, but I'm limited to 200 characters.

How do I tell it to show the data field beneath the prompt so that I can enter the points {{1,1},{1.6875,2},..} separately? For example:

https://www.wolframalpha.com/input?i=polynomial+fit

https://www.wolframalpha.com/input?i=cubic+fit+calculator

I've tried:

```<code>FindFit[%,{a*x^(1/5) + b*x^(1/3) + c*x + d*(1/x) + e},{a,b,c,d,e},x]
find fit
<a_whole_bunch_of_other_stuff_over_a_few_days>
</code>```

But they don't work and I'm tearing my hair out.. this feels like a huge oversight or even a bug. Does anyone know the magic incantation to show the data field for any query? Or to submit the data and reference it in the next query? Similar to these, but allowing me to enter the form of the equation:

https://www.wolframalpha.com/input/?i=curve%20fitting

Title: Tell WolframAlpha to show data field?

Body:
I'm trying to find an approximation for a function that's near y = x^(1/5).

Unfortunately, polynomial approximations for functions below degree 1 don't work. These work if I specify the form manually, but are off by about 5% in the ranges I care about:

FindFit[{{1,1},{1.6875,2},{4.234567901,3},{10.71875,4},{25,5},{53.1797839,6},{104.142857,7},{190.10937,8},{327.189300,9},{535.9375,10}},{a*x^(1/5) + b*x^(1/3) + c*x + d*(1/x) + e},{a,b,c,d,e},x]
1.6616*x^(1/5) + 0.570547*x^(1/3) + -0.00136863*x + -1.445*(1/x) + 0.251113

NonlinearModelFit[{{1,1},{1.6875,2},{4.234567901,3},{10.71875,4},{25,5},{53.1797839,6},{104.142857,7},{190.10937,8},{327.189300,9},{535.9375,10}},{a*x^(1/5)+b*x^(1/3)+c*x+d*(1/x)+e},{a,b,c,d,e},x]
0.251113 - 0.00136863 x + 0.570547 x^(1/3) + 1.6616 x^(1/5) - 1.445/x

FindFit example see https://reference.wolfram.com/language/ref/FindFit.html

NonlinearModelFit example see https://reference.wolfram.com/language/ref/NonlinearModelFit.html

The problem is that I need to explore more forms or provide more data, but I'm limited to 200 characters.

How do I tell it to show the data field beneath the prompt so that I can enter the points {{1,1},{1.6875,2},..} separately? For example:

https://www.wolframalpha.com/input?i=polynomial+fit

https://www.wolframalpha.com/input?i=cubic+fit+calculator

I've tried:

FindFit[%,{a*x^(1/5) + b*x^(1/3) + c*x + d*(1/x) + e},{a,b,c,d,e},x]
find fit
<a_whole_bunch_of_other_stuff_over_a_few_days>

But they don't work and I'm tearing my hair out.. this feels like a huge oversight or even a bug. Does anyone know the magic incantation to show the data field for any query? Or to submit the data and reference it in the next query? Similar to these, but allowing me to enter the form of the equation:

https://www.wolframalpha.com/input/?i=curve%20fitting


问:
monitoring server reachability
i want to monitor server reachability through port if it connected or not like

```<code>telnet 10.0.0.0 5000
</code>```

Prometheus.yml

```<code>- job_name: 'test'
          scrape_interval: 5m
          metrics_path: /probe
          params:
            module: [tcp_connect]
          static_configs:
            - targets:['10.0.0.0:5000']
          relabel_configs:
            - source_labels: [__address__]
              target_label: __param_target
            - source_labels: [__param_target]
              target_label: instance
            - target_label: __address__
              replacement: monitoring-prometheus-blackbox-exporter:9115
</code>```

and it's working fine
my question is can i rely on

```<code>probe_success # if = 1 means reachable if = 0 unreachable ?
</code>```

thanks

Title: monitoring server reachability

Body:
i want to monitor server reachability through port if it connected or not like

telnet 10.0.0.0 5000

Prometheus.yml

- job_name: 'test'
          scrape_interval: 5m
          metrics_path: /probe
          params:
            module: [tcp_connect]
          static_configs:
            - targets:['10.0.0.0:5000']
          relabel_configs:
            - source_labels: [__address__]
              target_label: __param_target
            - source_labels: [__param_target]
              target_label: instance
            - target_label: __address__
              replacement: monitoring-prometheus-blackbox-exporter:9115

and it's working fine
my question is can i rely on

probe_success # if = 1 means reachable if = 0 unreachable ?

thanks


问:
Is it possible to create an icon that executes a python code with the current file with JupyterLab?
I know I can convert an ipynb file to a .py file with the command jupyter nbconvert --to python file.py --output-dir=/home/path/myfile.py. However, I'd like to create an icon on the top bar that executes this command on the current ipynb file... Something like the following:

Is there any way of doing it? How can I create an icon on the top bar that will execute a python file and send the absolute path of the current file as an argument?

In my case it'd have to run the following command while clicking the icon:

```<code>python3 /home/user/convert-file.py "$fileIAmEditing"
</code>```

Body:
I know I can convert an ipynb file to a .py file with the command jupyter nbconvert --to python file.py --output-dir=/home/path/myfile.py. However, I'd like to create an icon on the top bar that executes this command on the current ipynb file... Something like the following:

Is there any way of doing it? How can I create an icon on the top bar that will execute a python file and send the absolute path of the current file as an argument?

In my case it'd have to run the following command while clicking the icon:

python3 /home/user/convert-file.py "$fileIAmEditing"


问:
kubeflow new notebook fails with "failed calling webhook"
I installed kubeflow on Ubuntu 22.04.1 LTS using this guide. After installation, in the dashboard I try and start a new notebook server which leads to the following error - see image below . Could anyone advise on a fix?


问:
Typescript - generic type becomes unkown
I'm trying to create a decorator function but I can't seem to get the types right.
The decorator returns a function that retries a function and returns a Result which contains a value or an error.

For the retry I'm using the package ts-retry-promise, and more specifically, the following function:

```<code>function retryDecorator<T, F extends (...args: any[]) => Promise<T>>(func: F, config?: Partial<RetryConfig<T>>): (...funcArgs: Parameters<F>) => ReturnType<F>;

</code>```

This is my first attempt:

```<code>export function retryWithResultDecorator<T, F extends (...args: any[]) => Promise<T>>(fn: F, maxAttempts: number): (...fnArgs: Parameters<F>) => Promise<Result<T, Error>> {
    return async (...args: Parameters<F>) => {
        const fnWithRetries = retryDecorator(fn, { retries: maxAttempts });
        const safeFnWithRetries: ResultAsync<T, Error> = ResultAsync.fromPromise(
            fnWithRetries(...args),
            () => new Error()
        );
        const res = await safeFnWithRetries
        return res;
    }
}

async function foo(a: string): Promise<string> {
    return a;
}

const bar = retryWithResultDecorator(foo, 5) // bar is of type: (a: string) => Promise<Result<unknown, Error>>
</code>```

Second attempt:

```<code>export function retryWithResultDecorator2<F extends (...args: any[]) => Promise<any>>(fn: F, maxAttempts: number): (...fnArgs: Parameters<F>) => Promise<Result<ReturnType<F>, Error>> {
    return async (...args: Parameters<F>) => {
        const fnWithRetries = retryDecorator(fn, { retries: maxAttempts });
        const safeFnWithRetries: ResultAsync<ReturnType<F>, Error> = ResultAsync.fromPromise(
            fnWithRetries(...args),
            () => new Error()
        );
        const res = await safeFnWithRetries
        return res;
    }
}

async function foo(a: string): Promise<string> {
    return a;
}

const bar = retryWithResultDecorator2(foo, 5) // bar is of type (a: string) => Promise<Result<Promise<string>, Error>>
</code>```

The desired return type is: Promise<Result<T, Error>>

I understand why the two things doesn't work, but I have no idea how to solve it.

Edit:

Here's a link to CodeSandBox with the dependencies:
https://codesandbox.io/s/typescript-forked-6pr478?file=/src/index.ts

Thanks :)

Body:
I'm trying to create a decorator function but I can't seem to get the types right.
The decorator returns a function that retries a function and returns a Result which contains a value or an error.

For the retry I'm using the package ts-retry-promise, and more specifically, the following function:

function retryDecorator<T, F extends (...args: any[]) => Promise<T>>(func: F, config?: Partial<RetryConfig<T>>): (...funcArgs: Parameters<F>) => ReturnType<F>;

This is my first attempt:

export function retryWithResultDecorator<T, F extends (...args: any[]) => Promise<T>>(fn: F, maxAttempts: number): (...fnArgs: Parameters<F>) => Promise<Result<T, Error>> {
    return async (...args: Parameters<F>) => {
        const fnWithRetries = retryDecorator(fn, { retries: maxAttempts });
        const safeFnWithRetries: ResultAsync<T, Error> = ResultAsync.fromPromise(
            fnWithRetries(...args),
            () => new Error()
        );
        const res = await safeFnWithRetries
        return res;
    }
}

async function foo(a: string): Promise<string> {
    return a;
}

const bar = retryWithResultDecorator(foo, 5) // bar is of type: (a: string) => Promise<Result<unknown, Error>>

Second attempt:

export function retryWithResultDecorator2<F extends (...args: any[]) => Promise<any>>(fn: F, maxAttempts: number): (...fnArgs: Parameters<F>) => Promise<Result<ReturnType<F>, Error>> {
    return async (...args: Parameters<F>) => {
        const fnWithRetries = retryDecorator(fn, { retries: maxAttempts });
        const safeFnWithRetries: ResultAsync<ReturnType<F>, Error> = ResultAsync.fromPromise(
            fnWithRetries(...args),
            () => new Error()
        );
        const res = await safeFnWithRetries
        return res;
    }
}

async function foo(a: string): Promise<string> {
    return a;
}

const bar = retryWithResultDecorator2(foo, 5) // bar is of type (a: string) => Promise<Result<Promise<string>, Error>>

The desired return type is: Promise<Result<T, Error>>

I understand why the two things doesn't work, but I have no idea how to solve it.

Edit:

Here's a link to CodeSandBox with the dependencies:
https://codesandbox.io/s/typescript-forked-6pr478?file=/src/index.ts

Thanks :)


问:
OKI pdf printing problem - different font and symbols
I have an OKI MC352dn printer.

Printing images and image pdfs works fine and the results are satisfactory.

However when I print certain pdf files, for example some mathematical articles, the font changes, and the output is completely different from the original pdf. Also, some QR-looking codes are also printed as a garbled mess.

Changing a .pdf to a .png fixes the problem, however this is tedious and I'd prefer not to do it.

I noticed that the font used was Courier which is the PCL emulation default font.

I honestly have no idea what that means, and what PCL emulation is, but I found it in the printer admin settings.

Is it possible to change the settings so that the printer always prints the pdf correctly, and doesn't use any of it's default settings?

I have updated the firmware and installed all drivers, but the problem persists, even if sending the print job from a different device.

EDIT:
Here's a preview of the a .pdf file

And here's the printed output


问:
Tradingview - Only one Alert but based on multiple conditions
I have two conditions to be met in Tradingview before I entry a reversal-trade:

1.RSI >75 if I enter a short position and RSI <25 if I enter a long position
2.Current price should be inside parallel channel working as support or resistance zone

Today I have set the alert on the first condition and then manually check if the second one is met. How to combine these two conditions in one single alert using pinescript?

The current alert on the first condition is working fine. The parallel channels are updated by me on a daily basis but I can set an alert also on the channels using Tradingviews built in alert-function. It is the combination of the two conditions that is the challenge.


问:
View StackExchange-like git diff online
How can I show the diff between two commits in an inline fashion, such that it looks like StackExchange's edit diffs, on GitHub's website?

At the moment GitHub is showing me linewise diffs. I only get to see the lines that are changed, it's less obvious which words were swapped out.

I guess like git --color-words=. but online instead of locally.

Instead of this

I want this

Title: View StackExchange-like git diff online


问:
UnhandledPromiseRejectionWarning: TypeError: Cannot read properties of undefined (reading 'includes') at Guild.fetchVanityData Discord.js v14
I am trying to get the vanities of the servers the bot is in, and it is responding with this error.

```<code>var vanity = await guild.fetchVanityData()
console.log(vanity)
</code>```

also tried docs method (same error):

```<code>var vanity = guild.fetchVanityData().then(res => console.log(`Vanity URL: https://discord.gg/${res.code} with ${res.uses} uses`));
</code>```

If there's another method of getting the vanity URL and I'm missing it or I'm using this wrong, then please inform me. Thanks!

Body:
I am trying to get the vanities of the servers the bot is in, and it is responding with this error.

var vanity = await guild.fetchVanityData()
console.log(vanity)

also tried docs method (same error):

var vanity = guild.fetchVanityData().then(res => console.log(`Vanity URL: https://discord.gg/${res.code} with ${res.uses} uses`));

If there's another method of getting the vanity URL and I'm missing it or I'm using this wrong, then please inform me. Thanks!


问:
how to access the list of downloads with their statuses in tampermonkey/greasemonkey
Is there a way to access the list of downloads with their statuses in tampermonkey or greasemonkey? Need to do some condition testing based on the statuses and wonder how one may be able to obtain such info.

Thank you.


问:
Calling a Function from the main Module in a Submodule in Go
Is there a way to call a function from the main module in a sub module?

I have a primary module with a submodule, such that my go.work is

go 1.19

use ./
use ./db
```
<p>I would like to call a function from main, such as</p>
<pre class="lang-golang prettyprint-override"><code>package db

import "main"

func DatabaseCall() {
    main.FooBar("lorem")
}
</code>```

I have tried reworking my module structure to

go 1.19

use ./main
use ./db
```
<p>but I was still unable to call it. Is there something special about main, or am I just doing something wrong?</p>
<p>I have been able to pass the full function as a handler by redefining it like this:</p>
<pre class="lang-golang prettyprint-override"><code>// db
type FooBar func(ipsum string)

func DatabaseCall(handler FooBar) {
    handler("lorem")
}

// main
db.DatabaseCall(db.FooBar(FooBar))
</code>```

but unless I am mistaken this means the entire function is copied in memory, which is not something I would want to do. You can pass it as a pointer, but must dereference it before calling which would copy it regardless.

Body:
Is there a way to call a function from the main module in a sub module?

I have a primary module with a submodule, such that my go.work is

go 1.19

use ./
use ./db

I would like to call a function from main, such as

package db

import "main"

func DatabaseCall() {
    main.FooBar("lorem")
}

I have tried reworking my module structure to

go 1.19

use ./main
use ./db

but I was still unable to call it. Is there something special about main, or am I just doing something wrong?

I have been able to pass the full function as a handler by redefining it like this:

// db
type FooBar func(ipsum string)

func DatabaseCall(handler FooBar) {
    handler("lorem")
}

// main
db.DatabaseCall(db.FooBar(FooBar))

but unless I am mistaken this means the entire function is copied in memory, which is not something I would want to do. You can pass it as a pointer, but must dereference it before calling which would copy it regardless.


问:
Pyqt crash widget QTableView
i have a problem with pyqt. When clicking on a row in the table, the GroupBox loads and it is correct to load the data. When selecting a different row, all widgets are not properly loaded. Clicking a row again refreshes the tables but does not correctly display the other widgets

```<code>

class Zlecenia(QWidget):
    def __init__(self):
        super(Zlecenia, self).__init__()

        self.zlecenia = self.pobierz_numery_zlecen()
        self.vbox_zlecenia = QVBoxLayout()
        self.tabela_widok_zlecenia = QTableView()

        self.header_zlecenia = ['Numer zlecenia', 'Klient']

        self.tabela_wybrane_zlecenie = QTableView()

        self.tabela_wybrane_zlecenie_model = TabelaWybraneZlecenieModel()

        self.tabela_widok_zlecenia_model = TabelaZleceniaModel(self.zlecenia, self.header_zlecenia)
        self.tabela_widok_zlecenia.setModel(self.tabela_widok_zlecenia_model)

        self.tabela_widok_zlecenia.setColumnWidth(0, 400)
        self.tabela_widok_zlecenia.horizontalHeader().setStretchLastSection(True)
        self.tes = self.tabela_widok_zlecenia.setSelectionBehavior(QTableView.SelectRows)
        self.tabela_widok_zlecenia.doubleClicked.connect(self.clicked_zlecenie)

        self.groupBox_zleceni = QGroupBox()

        self.groupBox_zleceni.setVisible(False)
        self.vbox_zlecenia.addWidget(self.tabela_widok_zlecenia)

        self.vbox_zlecenia.addWidget(self.groupBox_zleceni)

    def clicked_zlecenie(self):
        self.index = self.tabela_widok_zlecenia.selectionModel().currentIndex()

        self.numer_zlecenia = self.index.siblingAtColumn(0).data()
        klient = self.index.siblingAtColumn(1).data()

        numer_zlecenia = str(self.numer_zlecenia)

        self.groupBox_zleceni.setTitle(klient + ': ' + numer_zlecenia)

        hbox_zlecenia = QHBoxLayout()

        self.nazwa_klienta_do_zlecenia = klient
        self.numer_zlecenia_do_zlecenia = numer_zlecenia

        import sqlCommand
        self.lista_detali_poj = sqlCommand.DB()
        self.lista_detali_poj = self.lista_detali_poj.wczytanie_detali_do_zlecenia(self.numer_zlecenia_do_zlecenia)

        self.lista_detali_zlozenie = sqlCommand.DB()
        self.lista_detali_zlozenie = self.lista_detali_zlozenie.wczytanie_zlozen_do_zlecenia(self.numer_zlecenia_do_zlecenia)

        self.cala_lista = self.lista_detali_poj + self.lista_detali_zlozenie

        self.tabela_wybrane_zlecenie_model = TabelaWybraneZlecenieModel(self.cala_lista)

        self.tabela_wybrane_zlecenie.setModel(self.tabela_wybrane_zlecenie_model)
        self.tabela_wybrane_zlecenie.setColumnWidth(0, 600)
        self.tabela_wybrane_zlecenie.horizontalHeader().setStretchLastSection(True)

        hbox_zlecenia.addWidget(self.tabela_wybrane_zlecenie)

        vbox_zlecenie_button = QVBoxLayout()
        button_dodaj_detale = QPushButton('Dodaj \ndetale')
        button_dodaj_detale.setFixedSize(180,50)
        button_dodaj_detale.clicked.connect(self.dodaj_detale)
        vbox_zlecenie_button.addWidget(button_dodaj_detale)
        self.button_usun_detal_ze_zlecenia = QPushButton('Usuń \ndetal')
        self.button_usun_detal_ze_zlecenia.setFixedSize(180, 50)
        self.button_usun_detal_ze_zlecenia.clicked.connect(self.usun_detal_ze_zlecenia)
        vbox_zlecenie_button.addWidget(self.button_usun_detal_ze_zlecenia)
        self.button_kopiuj_pliki = QPushButton('Kopiuj \npliki')
        self.button_kopiuj_pliki.setFixedSize(180, 50)
        vbox_zlecenie_button.addWidget(self.button_kopiuj_pliki)
        hbox_zlecenia.addLayout(vbox_zlecenie_button)

        self.groupBox_zleceni.setLayout(hbox_zlecenia)

        self.tabela_widok_zlecenia.setVisible(False)
        self.groupBox_zleceni.setVisible(True)
</code>```

How to properly display widgets after clicking on a table row again?

Title: Pyqt crash widget QTableView

Body:
i have a problem with pyqt. When clicking on a row in the table, the GroupBox loads and it is correct to load the data. When selecting a different row, all widgets are not properly loaded. Clicking a row again refreshes the tables but does not correctly display the other widgets

class Zlecenia(QWidget):
    def __init__(self):
        super(Zlecenia, self).__init__()

        self.zlecenia = self.pobierz_numery_zlecen()
        self.vbox_zlecenia = QVBoxLayout()
        self.tabela_widok_zlecenia = QTableView()

        self.header_zlecenia = ['Numer zlecenia', 'Klient']

        self.tabela_wybrane_zlecenie = QTableView()

        self.tabela_wybrane_zlecenie_model = TabelaWybraneZlecenieModel()

        self.tabela_widok_zlecenia_model = TabelaZleceniaModel(self.zlecenia, self.header_zlecenia)
        self.tabela_widok_zlecenia.setModel(self.tabela_widok_zlecenia_model)

        self.tabela_widok_zlecenia.setColumnWidth(0, 400)
        self.tabela_widok_zlecenia.horizontalHeader().setStretchLastSection(True)
        self.tes = self.tabela_widok_zlecenia.setSelectionBehavior(QTableView.SelectRows)
        self.tabela_widok_zlecenia.doubleClicked.connect(self.clicked_zlecenie)

        self.groupBox_zleceni = QGroupBox()

        self.groupBox_zleceni.setVisible(False)
        self.vbox_zlecenia.addWidget(self.tabela_widok_zlecenia)

        self.vbox_zlecenia.addWidget(self.groupBox_zleceni)

    def clicked_zlecenie(self):
        self.index = self.tabela_widok_zlecenia.selectionModel().currentIndex()

        self.numer_zlecenia = self.index.siblingAtColumn(0).data()
        klient = self.index.siblingAtColumn(1).data()

        numer_zlecenia = str(self.numer_zlecenia)

        self.groupBox_zleceni.setTitle(klient + ': ' + numer_zlecenia)

        hbox_zlecenia = QHBoxLayout()

        self.nazwa_klienta_do_zlecenia = klient
        self.numer_zlecenia_do_zlecenia = numer_zlecenia

        import sqlCommand
        self.lista_detali_poj = sqlCommand.DB()
        self.lista_detali_poj = self.lista_detali_poj.wczytanie_detali_do_zlecenia(self.numer_zlecenia_do_zlecenia)

        self.lista_detali_zlozenie = sqlCommand.DB()
        self.lista_detali_zlozenie = self.lista_detali_zlozenie.wczytanie_zlozen_do_zlecenia(self.numer_zlecenia_do_zlecenia)

        self.cala_lista = self.lista_detali_poj + self.lista_detali_zlozenie

        self.tabela_wybrane_zlecenie_model = TabelaWybraneZlecenieModel(self.cala_lista)

        self.tabela_wybrane_zlecenie.setModel(self.tabela_wybrane_zlecenie_model)
        self.tabela_wybrane_zlecenie.setColumnWidth(0, 600)
        self.tabela_wybrane_zlecenie.horizontalHeader().setStretchLastSection(True)

        hbox_zlecenia.addWidget(self.tabela_wybrane_zlecenie)

        vbox_zlecenie_button = QVBoxLayout()
        button_dodaj_detale = QPushButton('Dodaj \ndetale')
        button_dodaj_detale.setFixedSize(180,50)
        button_dodaj_detale.clicked.connect(self.dodaj_detale)
        vbox_zlecenie_button.addWidget(button_dodaj_detale)
        self.button_usun_detal_ze_zlecenia = QPushButton('Usuń \ndetal')
        self.button_usun_detal_ze_zlecenia.setFixedSize(180, 50)
        self.button_usun_detal_ze_zlecenia.clicked.connect(self.usun_detal_ze_zlecenia)
        vbox_zlecenie_button.addWidget(self.button_usun_detal_ze_zlecenia)
        self.button_kopiuj_pliki = QPushButton('Kopiuj \npliki')
        self.button_kopiuj_pliki.setFixedSize(180, 50)
        vbox_zlecenie_button.addWidget(self.button_kopiuj_pliki)
        hbox_zlecenia.addLayout(vbox_zlecenie_button)

        self.groupBox_zleceni.setLayout(hbox_zlecenia)

        self.tabela_widok_zlecenia.setVisible(False)
        self.groupBox_zleceni.setVisible(True)

How to properly display widgets after clicking on a table row again?


问:
High render usage with animations on mouse move
I found some interesting behavior when testing the performance of some CSS animations. For example, I can animate these 1,000 elements and on my PC they are barely using any resources.

It's honestly impressive that it preforms that well, but if I'm moving the mouse, it's a completely different story.

The only difference is that I am constantly moving my mouse. I want to know why this happens, and if there is anything I can do to improve it. None of these elements have any mouse interaction, no JavaScript listeners, no CSS hover effects or anything like that. I am confused why moving the mouse would then have such a major effect. This high resource usage also happens even when the elements aren't visible and are scrolled past. The window is focused for all benchmarks.

The animation that I am talking about are using transforms and opacity. When using other properties like width, height, margin I get high resource usage no matter what.

Here are several things that I have tried to change this with no noticeable difference in performance.

pointer-events: none, unsurprisingly no effect. I didn't think it worked like that.

will-change

display: inline-block vs position: absolute layout

transform vs opacity animations

translate3d vs translate

Elements outside of the viewport (scrolled past)

I'm guessing this has to do with a GPU and as soon as the mouse moves, it requires the CPU to do something. This would explain the lack of difference on properties that require to CPU to calculate, and properties that can use the GPU are effected so dramatically.

I'm noticing this using Brave and Edge for sure. I don't under the Firefox tool enough to confidently say the same for them, although it appears to happen as well.

How can I make this always run as in the first case? I am never using any mouse interaction, so these elements could careless what it happening with the mouse from my perspective.

Here is a code snippet that should be able to produce the effect. I also have here on a GitHub pages site.

https://jack-stoller.github.io/so_demo.html

```<code><style>
    body {
      padding-bottom: 150vw;
    }

    div {
      position: absolute;

      height: 50px;
      width: 50px;
      pointer-events: none;
      will-change: transform;
      background-color: red;
      animation: Animation 2s ease infinite;
    }

    @keyframes Animation {
      from {
        transform: scale(0);
      }

      to {
        transform: scale(1);
      }
    }
</style>
<body></body>
<script>
    const size = 50 + 8 + 8;
    const count = Math.floor(window.innerWidth / size);

    [...Array(1000)].forEach((_, i) => {
      let div = document.createElement('div');
      div.style.top = Math.floor(i / count) * size + 'px';
      div.style.left = Math.floor(i % count) * size + 'px';
      document.body.appendChild(div);
    });
</script>
</code>```


问:
What is the difference between filter masks and the 'query' method in python pandas?
So, i have started learning pandas recently and i just can`t figure out why people use filter masks while there is a 'query'  method. They seem for me exactly the same, but query is more convenient to use at least for me

i have done a couple of comparisons between them


问:
AWS EC2 Instance Security Group - All traffic
I am trying to launch an EC2 instance with security as 'all traffic' to create the jupyter notebook for personal practice. However I notice that the UI changed in AWS and where is this selection now? Should choose all the selections as in the attached file?

I followed the set-up instruction (a bit out-dated): https://www.udemy.com/course/spark-and-python-for-big-data-with-pyspark/learn/lecture/7005606#questions, but cannot launch the jupyter notebook (error showing page cannot be loaded)

Anyone can suggest? Thanks!!!

My setting in the ./jupyter/jupyter_notebook_config.py is as below:


问:
Python to excel
I created a script to pull data from a website and paste it in excel. The script works, however when I extract the Name from the website and it paste in excel for some reason its very small. But when you click in the cell its normal size. See image here.

I tried to show a snip it as an example but stack won't allow me.

Here is the current code

from openpyxl import load_workbook
from bs4 import BeautifulSoup
import requests

# Fetch the HTML page

url = 'https://esearch.mobilecopropertytax.com/Property/View/466089'
response = requests.get(url)
html = response.text

# Parse the HTML page
soup = BeautifulSoup(html, 'lxml')

# Find the element containing the Parcel Number
element = soup.find('th', text='Parcel Number:')

# Extract the Parcel Number from the element
parcel_number = element.find_next_sibling().text

# Find the element containing the Name
element = soup.find('th', text='Name:')

# Extract the Name from the element
name = element.find_next_sibling().text

# Load the workbook
wb = load_workbook(r'C:\Users\user\EJW Test\EJWtest.xlsx')

# Select the sheet
ws = wb['Justification Worksheet']

# Select the cells
cell1 = ws['C7'] # Parcel Number
cell2 = ws['C10'] # Name

# Set the values of the cells
cell1.value = parcel_number
cell2.value = name

# Save the workbook
wb.save('completetest.xlsx')
```

Unsure why it puts the parcel info in just fine but inserts the name into excel and it looks completely different.

Title: Python to excel

Body:
I created a script to pull data from a website and paste it in excel. The script works, however when I extract the Name from the website and it paste in excel for some reason its very small. But when you click in the cell its normal size. See image here.

I tried to show a snip it as an example but stack won't allow me.

Here is the current code

from openpyxl import load_workbook
from bs4 import BeautifulSoup
import requests

# Fetch the HTML page

url = 'https://esearch.mobilecopropertytax.com/Property/View/466089'
response = requests.get(url)
html = response.text

# Parse the HTML page
soup = BeautifulSoup(html, 'lxml')

# Find the element containing the Parcel Number
element = soup.find('th', text='Parcel Number:')

# Extract the Parcel Number from the element
parcel_number = element.find_next_sibling().text

# Find the element containing the Name
element = soup.find('th', text='Name:')

# Extract the Name from the element
name = element.find_next_sibling().text

# Load the workbook
wb = load_workbook(r'C:\Users\user\EJW Test\EJWtest.xlsx')

# Select the sheet
ws = wb['Justification Worksheet']

# Select the cells
cell1 = ws['C7'] # Parcel Number
cell2 = ws['C10'] # Name

# Set the values of the cells
cell1.value = parcel_number
cell2.value = name

# Save the workbook
wb.save('completetest.xlsx')

Unsure why it puts the parcel info in just fine but inserts the name into excel and it looks completely different.


问:
Docker/Django/Gunicorn/Nginx Websockets not connecting
Dockerized Django chat app using gunicorn, nginx for reverse proxy (static files). I managed to get stuck trying to get the websockets to work, but I can't connect to daphne: daphne -p 8001 project.asgi:application. The app only says, "Connection refusesed for upstream localhost:8001". I'm using django-channels and redis and on local everything is working fine.

Am I missing something?

Here are some files:

nginx.conf

upstream project {
    server web:8000;
}

upstream websocket {
 server localhost:8001;
}
server {

    listen 80;

    location /ws/ {

        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }

    location / {
        proxy_pass http://project;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /home/app/web/staticfiles/;
    }

}```
</div>
</div>
</p>
<p><strong>asgi.py</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
import scrumboard.routing

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    'websocket': AuthMiddlewareStack(
        URLRouter(
            scrumboard.routing.websocket_urlpatterns
        )
    )
})</code>```

settings.py

"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 4.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
from django.template.context_processors import media

BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
SECRET_KEY = config("SECRET_KEY")

DEBUG = int(config("DEBUG", default=0))

# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a space between each.
# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'
ALLOWED_HOSTS = config("DJANGO_ALLOWED_HOSTS").split(" ")
CSRF_TRUSTED_ORIGINS = ['http://localhost:1337']
CORS_ALLOWED_HOSTS = ['http://localhost:1337']

# Application definition

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'scrumboard',
    'rest_framework'
]

ASGI_APPLICATION = 'project.asgi.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer'
    }
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
        "NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"),
        "USER": os.environ.get("SQL_USER", "user"),
        "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
        "HOST": os.environ.get("SQL_HOST", "localhost"),
        "PORT": os.environ.get("SQL_PORT", "5432"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''```
</div>
</div>
</p>
<p><strong>routing.py</strong></p>
```from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi())
]
```
<p><strong>docker-compose.yml</strong></p>
```version: '3.8'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.prod
    command: gunicorn project.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/app/web/staticfiles
    expose:
      - "8000:8000"
    env_file:
      - ./.env.prod
    depends_on:
      - db
    container_name: "chat_app_prod"

  db:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - ./.env.prod.db
    container_name: "db_prod"

  nginx:
    build: nginx
    volumes:
      - static_volume:/home/app/web/staticfiles
      - ./nginx/chat-app-cert.pem:/etc/nginx/chat-app-cert.pem
      - ./nginx/chat-app-key.pem:/etc/nginx/chat-app-key.pem
    ports:
      - "1337:80"
      - "443:443"
    depends_on:
      - web

  redis:
    image: redis
    ports:
      - "6379:6379"

volumes:
  postgres_data:
  static_volume:
```

Body:
Dockerized Django chat app using gunicorn, nginx for reverse proxy (static files). I managed to get stuck trying to get the websockets to work, but I can't connect to daphne: daphne -p 8001 project.asgi:application. The app only says, "Connection refusesed for upstream localhost:8001". I'm using django-channels and redis and on local everything is working fine.

Am I missing something?

Here are some files:

nginx.conf

upstream project {
    server web:8000;
}

upstream websocket {
 server localhost:8001;
}
server {

    listen 80;

    location /ws/ {

        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }

    location / {
        proxy_pass http://project;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /home/app/web/staticfiles/;
    }

}

asgi.py

import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
import scrumboard.routing

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    'websocket': AuthMiddlewareStack(
        URLRouter(
            scrumboard.routing.websocket_urlpatterns
        )
    )
})

settings.py

"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 4.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
from django.template.context_processors import media

BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
SECRET_KEY = config("SECRET_KEY")

DEBUG = int(config("DEBUG", default=0))

# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a space between each.
# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'
ALLOWED_HOSTS = config("DJANGO_ALLOWED_HOSTS").split(" ")
CSRF_TRUSTED_ORIGINS = ['http://localhost:1337']
CORS_ALLOWED_HOSTS = ['http://localhost:1337']

# Application definition

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'scrumboard',
    'rest_framework'
]

ASGI_APPLICATION = 'project.asgi.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer'
    }
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
        "NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"),
        "USER": os.environ.get("SQL_USER", "user"),
        "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
        "HOST": os.environ.get("SQL_HOST", "localhost"),
        "PORT": os.environ.get("SQL_PORT", "5432"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

routing.py

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi())
]

docker-compose.yml

version: '3.8'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.prod
    command: gunicorn project.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/app/web/staticfiles
    expose:
      - "8000:8000"
    env_file:
      - ./.env.prod
    depends_on:
      - db
    container_name: "chat_app_prod"

  db:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - ./.env.prod.db
    container_name: "db_prod"

  nginx:
    build: nginx
    volumes:
      - static_volume:/home/app/web/staticfiles
      - ./nginx/chat-app-cert.pem:/etc/nginx/chat-app-cert.pem
      - ./nginx/chat-app-key.pem:/etc/nginx/chat-app-key.pem
    ports:
      - "1337:80"
      - "443:443"
    depends_on:
      - web

  redis:
    image: redis
    ports:
      - "6379:6379"

volumes:
  postgres_data:
  static_volume:


问:
Response Time seems high when Traefik is used
I have an application who run inside a docker, just behind a traefik proxy. I made some benchmarks. First form the server, I got a response time of 12ms if I use the IP of the docker. But when I used the ndd my response time escalated to 90ms!

Why I have so much difference ?

I made the same test from my machine and I got 198ms in response time !!!.

Test from the server, with the docker IP :

```<code>> time curl -w "@curl-format.txt" -o /dev/null -s "172.23XXXXX"

   time namelookup: 0.0000425
      time connect: 0.0000005
   time_appconnect: 0.0000005
  time pretransfer: 0.0000005
     time redirect: 0.0000005
time starttransfer: 0.0000005
        time total: 0.0002795

real 0m0.0125
user 0m0.0085
sys  0m0.004s

</code>```

Test from the server, with the NDD :

```<code>>time curl -w "@cur1-format.txt" -0 /dev/null-s "https://api.XXXXXX"

   time namelookup: 0.0012755
      time connect: 0.0014405
   time_appconnect: 0.0494675
  time pretransfer: 0.0497685
     time redirect: 0.0000005
time starttransfer: 0.0754535
        time total: 0.0756765

real 0m0.0905
user 0m0.0145
sys  0m0.014s
</code>```

Test from my machine, with the NDD :

```<code>❯ time curl -w "@curl-format.txt" -o /dev/null -s "https://api.XXXXXXX"
     time_namelookup:  0.010114s
        time_connect:  0.040455s
     time_appconnect:  0.125563s
    time_pretransfer:  0.125802s
       time_redirect:  0.000000s
  time_starttransfer:  0.183123s
                     ----------
          time_total:  0.183554s

________________________________________________________
Executed in  198.84 millis    fish           external
   usr time   26.63 millis   57.00 micros   26.57 millis
   sys time   13.68 millis  834.00 micros   12.85 millis
</code>```

My traefik config :

```<code>services:
  traefik:
    image: "traefik:v2.9"
    container_name: "traefik"
    restart: "always"
    networks:
      - "traefik"
    command:
      - "--api.dashboard=true"
      - "--api.insecure=true"
      - "--entryPoints.web.address=:80"
      - "--entryPoints.websecure.address=:443"
      - "--providers.docker=true"
      - "--providers.docker.endpoint=unix:///var/run/docker.sock"
      - "--certificatesresolvers.myresolver.acme.tlschallenge=true"
      - "--certificatesresolvers.myresolver.acme.email=XXXXXXXXX"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - "./letsencrypt:/letsencrypt"
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/root/shared:/root/shared"
    labels:
      - "traefik.http.services.dashboard.loadbalancer.server.port=80"
      - "traefik.http.middlewares.httpsonly.redirectscheme.scheme=https"
      - "traefik.http.middlewares.httpsonly.redirectscheme.permanent=true"
      - "traefik.http.routers.httpsonly.rule=HostRegexp(`{any:.*}`)"
      - "traefik.http.routers.httpsonly.middlewares=httpsonly"
      - "traefik.http.routers.dashboard.rule=Host(`tra.XXXXXXX`)"
      - "traefik.http.routers.dashboard.entrypoints=websecure"
      - "traefik.http.routers.dashboard.tls.certresolver=myresolver"
      - "traefik.http.routers.dashboard.service=dashboard@internal"
      - "traefik.http.routers.api.rule=Host(`tra.XXXXXXX`) && PathPrefix(`/api`)"
      - "traefik.http.routers.api.service=api@internal"
      - "traefik.http.routers.api.entrypoints=websecure"
      - "traefik.http.routers.api.tls.certresolver=myresolver"
      - "traefik.http.routers.dashboard.middlewares=traefik-auth"
      - "traefik.http.routers.api.middlewares=traefik-auth"
      - "traefik.http.middlewares.traefik-auth.basicauth.usersfile=/root/shared/users"
      - "traefik.http.middlewares.traefik-auth.basicauth.removeheader=true"
      - "com.centurylinklabs.watchtower.enable=false"
</code>```

The traefik config of my application :

```<code>services:
  geodude:
    image: "XXXXXXXX/geodude:main"
    container_name: "geodude"
    restart: "always"
    networks:
      - "traefik"
    environment:
      [...]
    volumes:
      - "/root/geodude/data:/data"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.geodude.rule=Host(`api.XXXXXX`)"
      - "traefik.http.routers.geodude.entrypoints=websecure"
      - "traefik.http.routers.geodude.tls.certresolver=myresolver"
networks:
    traefik:
        external: true
</code>```

Body:
I have an application who run inside a docker, just behind a traefik proxy. I made some benchmarks. First form the server, I got a response time of 12ms if I use the IP of the docker. But when I used the ndd my response time escalated to 90ms!

Why I have so much difference ?

I made the same test from my machine and I got 198ms in response time !!!.

Test from the server, with the docker IP :

> time curl -w "@curl-format.txt" -o /dev/null -s "172.23XXXXX"

   time namelookup: 0.0000425
      time connect: 0.0000005
   time_appconnect: 0.0000005
  time pretransfer: 0.0000005
     time redirect: 0.0000005
time starttransfer: 0.0000005
        time total: 0.0002795

real 0m0.0125
user 0m0.0085
sys  0m0.004s

Test from the server, with the NDD :

>time curl -w "@cur1-format.txt" -0 /dev/null-s "https://api.XXXXXX"

   time namelookup: 0.0012755
      time connect: 0.0014405
   time_appconnect: 0.0494675
  time pretransfer: 0.0497685
     time redirect: 0.0000005
time starttransfer: 0.0754535
        time total: 0.0756765

real 0m0.0905
user 0m0.0145
sys  0m0.014s

Test from my machine, with the NDD :

❯ time curl -w "@curl-format.txt" -o /dev/null -s "https://api.XXXXXXX"
     time_namelookup:  0.010114s
        time_connect:  0.040455s
     time_appconnect:  0.125563s
    time_pretransfer:  0.125802s
       time_redirect:  0.000000s
  time_starttransfer:  0.183123s
                     ----------
          time_total:  0.183554s

________________________________________________________
Executed in  198.84 millis    fish           external
   usr time   26.63 millis   57.00 micros   26.57 millis
   sys time   13.68 millis  834.00 micros   12.85 millis

My traefik config :

services:
  traefik:
    image: "traefik:v2.9"
    container_name: "traefik"
    restart: "always"
    networks:
      - "traefik"
    command:
      - "--api.dashboard=true"
      - "--api.insecure=true"
      - "--entryPoints.web.address=:80"
      - "--entryPoints.websecure.address=:443"
      - "--providers.docker=true"
      - "--providers.docker.endpoint=unix:///var/run/docker.sock"
      - "--certificatesresolvers.myresolver.acme.tlschallenge=true"
      - "--certificatesresolvers.myresolver.acme.email=XXXXXXXXX"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - "./letsencrypt:/letsencrypt"
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/root/shared:/root/shared"
    labels:
      - "traefik.http.services.dashboard.loadbalancer.server.port=80"
      - "traefik.http.middlewares.httpsonly.redirectscheme.scheme=https"
      - "traefik.http.middlewares.httpsonly.redirectscheme.permanent=true"
      - "traefik.http.routers.httpsonly.rule=HostRegexp(`{any:.*}`)"
      - "traefik.http.routers.httpsonly.middlewares=httpsonly"
      - "traefik.http.routers.dashboard.rule=Host(`tra.XXXXXXX`)"
      - "traefik.http.routers.dashboard.entrypoints=websecure"
      - "traefik.http.routers.dashboard.tls.certresolver=myresolver"
      - "traefik.http.routers.dashboard.service=dashboard@internal"
      - "traefik.http.routers.api.rule=Host(`tra.XXXXXXX`) && PathPrefix(`/api`)"
      - "traefik.http.routers.api.service=api@internal"
      - "traefik.http.routers.api.entrypoints=websecure"
      - "traefik.http.routers.api.tls.certresolver=myresolver"
      - "traefik.http.routers.dashboard.middlewares=traefik-auth"
      - "traefik.http.routers.api.middlewares=traefik-auth"
      - "traefik.http.middlewares.traefik-auth.basicauth.usersfile=/root/shared/users"
      - "traefik.http.middlewares.traefik-auth.basicauth.removeheader=true"
      - "com.centurylinklabs.watchtower.enable=false"

The traefik config of my application :

services:
  geodude:
    image: "XXXXXXXX/geodude:main"
    container_name: "geodude"
    restart: "always"
    networks:
      - "traefik"
    environment:
      [...]
    volumes:
      - "/root/geodude/data:/data"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.geodude.rule=Host(`api.XXXXXX`)"
      - "traefik.http.routers.geodude.entrypoints=websecure"
      - "traefik.http.routers.geodude.tls.certresolver=myresolver"
networks:
    traefik:
        external: true


问:
is it possible for a function to connect to another function and gather information from an array JS
is it possible to make a function that is connected to another function that has an array this is a JS game Red Light Green Light the array is holding the text "Green Light, Red Light" I want to know if its possible to make another function that is taking information from my characters movement and when the green light or red light text appears for exapmple when green light appears nothing happens because its safe to move but when red light it appears you fail and a game over screen appears

var colors = ['Green light', 'Red light'];
(function () {
    var words = ["Red light"]
    i = 0;
    setInterval(function(){ $('#words').fadeOut(function(){
        $(this).html(colors[(i = (i + 1) % colors.length)]).fadeIn();
      }); }, 4000)
  })();

$(document).ready(function(){

var Block = function()
{
    this.goalDistance = 1370;
    this.distanceTraveled = 0;
    go = false;

}

var block = new Block();

$('#green-button').click(function(){
    console.log('GO!');
    block.go = true;
    animateBlock();
// this allows the block bob to move forward
});

$('#red-button').click(function(){
    console.log('STOP!');
    block.go = false;
// this allows the block bob to stop moving
});

function animateBlock()
{
    if(block.go === true && block.distanceTraveled < block.goalDistance)
    {
        $('#block').animate({left:'+=10'},50);
        block.distanceTraveled += 10;
        setTimeout(function(){
            animateBlock();
        },50);
    }
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
    border: 1px solid black;
    width: 65%;
    margin-top: 35px;
    margin-inline-start: 5px;
    border-inline-start-color: #ffffff;
}
body {
    background-color: grey;
}

.container {
    width: 20%;
    max-width: 20px;
    margin: auto;
}

.animated-heading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 1vh;
}

h1{
    color: black;

}

#finish-line
{
    position:absolute;
    height:650px;
    width:10px;
    left:1670px;
    top:135px;
    background-color:black;
}

.buttons
{
    margin-top: 1px;
    float: left;
}

.light
{
    width:150px;
    height:50px;
    margin-left:30px;
    color:white;
    font-size:2em;
}

#green-button
{
    background-color:green;
    border-radius: 12px;
    display: inline-block; margin-right: 20px;
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
    width: 200px;
    margin-left: 820px;
    margin-right: 5px;
    cursor: pointer
}

#red-button
{
    background-color:red;
    border-radius: 12px;
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
    width: 200px;
    margin: 0 auto;
    margin-right: 1px;
    cursor: pointer
}

.block
{
    position:relative;
    width:40px;
    height:39px;
    background-image: url('./image/bob.jpg');
    border: 1px solid black;
    bottom:400px;
    left:310px;
}</code>```

 Red light

<canvas id="myCanvas"></canvas>

        <button class = "light" id="green-button" type="button">GO!</button>
        <button class = "light" id="red-button" type="button">STOP!</button>

```

Body:
is it possible to make a function that is connected to another function that has an array this is a JS game Red Light Green Light the array is holding the text "Green Light, Red Light" I want to know if its possible to make another function that is taking information from my characters movement and when the green light or red light text appears for exapmple when green light appears nothing happens because its safe to move but when red light it appears you fail and a game over screen appears

var colors = ['Green light', 'Red light'];
(function () {
    var words = ["Red light"]
    i = 0;
    setInterval(function(){ $('#words').fadeOut(function(){
        $(this).html(colors[(i = (i + 1) % colors.length)]).fadeIn();
      }); }, 4000)
  })();

$(document).ready(function(){

var Block = function()
{
    this.goalDistance = 1370;
    this.distanceTraveled = 0;
    go = false;

}

var block = new Block();

$('#green-button').click(function(){
    console.log('GO!');
    block.go = true;
    animateBlock();
// this allows the block bob to move forward
});

$('#red-button').click(function(){
    console.log('STOP!');
    block.go = false;
// this allows the block bob to stop moving
});

function animateBlock()
{
    if(block.go === true && block.distanceTraveled < block.goalDistance)
    {
        $('#block').animate({left:'+=10'},50);
        block.distanceTraveled += 10;
        setTimeout(function(){
            animateBlock();
        },50);
    }
}

});

canvas{
    border: 1px solid black;
    width: 65%;
    margin-top: 35px;
    margin-inline-start: 5px;
    border-inline-start-color: #ffffff;
}
body {
    background-color: grey;
}

.container {
    width: 20%;
    max-width: 20px;
    margin: auto;
}

.animated-heading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 1vh;
}

h1{
    color: black;

}

#finish-line
{
    position:absolute;
    height:650px;
    width:10px;
    left:1670px;
    top:135px;
    background-color:black;
}

.buttons
{
    margin-top: 1px;
    float: left;
}

.light
{
    width:150px;
    height:50px;
    margin-left:30px;
    color:white;
    font-size:2em;
}

#green-button
{
    background-color:green;
    border-radius: 12px;
    display: inline-block; margin-right: 20px;
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
    width: 200px;
    margin-left: 820px;
    margin-right: 5px;
    cursor: pointer
}

#red-button
{
    background-color:red;
    border-radius: 12px;
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
    width: 200px;
    margin: 0 auto;
    margin-right: 1px;
    cursor: pointer
}

.block
{
    position:relative;
    width:40px;
    height:39px;
    background-image: url('./image/bob.jpg');
    border: 1px solid black;
    bottom:400px;
    left:310px;
}

 Red light

<canvas id="myCanvas"></canvas>

        <button class = "light" id="green-button" type="button">GO!</button>
        <button class = "light" id="red-button" type="button">STOP!</button>


问:
Styling prefilled Django radio input as buttons
I have a Django form field that is prefilled and using widget gave it a class. The form is rendered out in html as

```<code><div id="id_clothingType" class="closet-form-section form-clothing-type">
    <div>
        <label for="id_clothingType_0">
            <input type="radio" name="clothingType" value="11" class="closet-form-section form-clothing-type" required="" id="id_clothingType_0">
            Accessory
        </label>
    </div>
    <div>
        <label for="id_clothingType_1">
            <input type="radio" name="clothingType" value="12" class="closet-form-section form-clothing-type" required="" id="id_clothingType_1" checked>
            Top
        </label>
    </div>
</div>
</code>```

How do I style the radio inputs as buttons such that it changes its background color when it is checked without changing the html (form template)?

The problem is that the input is within the labels, so I am unable use the conventional way of the input:checked + label to style them.

Body:
I have a Django form field that is prefilled and using widget gave it a class. The form is rendered out in html as

            <input type="radio" name="clothingType" value="11" class="closet-form-section form-clothing-type" required="" id="id_clothingType_0">
            Accessory

            <input type="radio" name="clothingType" value="12" class="closet-form-section form-clothing-type" required="" id="id_clothingType_1" checked>
            Top

How do I style the radio inputs as buttons such that it changes its background color when it is checked without changing the html (form template)?

The problem is that the input is within the labels, so I am unable use the conventional way of the input:checked + label to style them.


问:
TypeScript overload cannot see a type that is defined in the implementation
In this example TypeScript reports "Cannot find name 'fnA'."  This is a simplified case.  I need to define the functions inside fn in the actual use case.  Is there any way to get it to see fnA?

```<code>function fn(a: true): typeof fnA; // "Cannot find name 'fnA'."
function fn(a: false): typeof fnB;
function fn(a: boolean): typeof fnA | typeof fnB {

    function fnA() { console.log(a);};
    function fnB() { console.log(a);};
    if (a) {
        return fnA;
    }
    else {
        return fnB;
    }
}
</code>```

Body:
In this example TypeScript reports "Cannot find name 'fnA'."  This is a simplified case.  I need to define the functions inside fn in the actual use case.  Is there any way to get it to see fnA?

function fn(a: true): typeof fnA; // "Cannot find name 'fnA'."
function fn(a: false): typeof fnB;
function fn(a: boolean): typeof fnA | typeof fnB {

    function fnA() { console.log(a);};
    function fnB() { console.log(a);};
    if (a) {
        return fnA;
    }
    else {
        return fnB;
    }
}


问:
Jest testing HTML Media Element
I have written a web-app which plays selected mp3 files in order of selection. When it comes to testing I cannot get my jest tests to enter the onended() handler of the HTMLAudioElement.

I have tried to spyOn the play() method on the elements but cannot find a way to set the audio's ended attribute to true.

The code for playing the audio is as follows:

```<code>playAudioFiles = () =\> {

    const audioFiles = this.getAudioFiles()
    const audio = audioFiles[0]
    let index = 1
    audio.play()
    audio.onended = () => {
        if (index < audioFiles.length) {
            audio.src = audioFiles[index].src
            audio.play()
            index++
        }
    }

}
</code>```

I am spying on the play method of the audio elements as follows:

```<code>mockPlay = jest.spyOn(window.HTMLMediaElement.prototype, 'play')
</code>```

Potentially there is something I could do here to trigger the ended event?

Title: Jest testing HTML Media Element

Body:
I have written a web-app which plays selected mp3 files in order of selection. When it comes to testing I cannot get my jest tests to enter the onended() handler of the HTMLAudioElement.

I have tried to spyOn the play() method on the elements but cannot find a way to set the audio's ended attribute to true.

The code for playing the audio is as follows:

playAudioFiles = () =\> {

    const audioFiles = this.getAudioFiles()
    const audio = audioFiles[0]
    let index = 1
    audio.play()
    audio.onended = () => {
        if (index < audioFiles.length) {
            audio.src = audioFiles[index].src
            audio.play()
            index++
        }
    }

}

I am spying on the play method of the audio elements as follows:

mockPlay = jest.spyOn(window.HTMLMediaElement.prototype, 'play')

Potentially there is something I could do here to trigger the ended event?


问:
pyautogui.write() not automatically using shift to type characters on non-english keyboard
I'm trying to automate the uploading of a file to a website. Using selenium to navigate the website, I got to the point where I get the prompt box to input the filename:

To enter the filename, I thought of using pyautogui (but if there is a better way, I'll take it, because at the moment, I'm testing with a headful navigator, but I'm not sure using pyautogui will work when I try to use a headless navigator.), like such:

```<code>import pyautogui
path = r"C:\path\to_my_file.pdf"
pyautogui.write(path)
pyautogui.hotkey('enter')
</code>```

My problem is that instead of typing the content of path, pyautogui types the keyboard keys that correspond to each character. Therefore, I get C/\path\to8my8file.pdf, because I have a french keyboard (where numbers are uppercase and special characters like _ and : are lowercase).

Of course, I could make sure that when pyautogui types : and _, it does what's needed to do shift + / and shift + 8, but that would be painstaking, and it would have to be done to each specific usecase. I'm sure there is a better, generic way, to type precisely the content of path.

Sidenote:

An old SO question had the answers pyautogui.write('C:\path\to_my_file.pdf', interval=0.1) or pyautogui.typewrite("C:\path\to_my_file.pdf", interval=0.1). They do not work.

Body:
I'm trying to automate the uploading of a file to a website. Using selenium to navigate the website, I got to the point where I get the prompt box to input the filename:

To enter the filename, I thought of using pyautogui (but if there is a better way, I'll take it, because at the moment, I'm testing with a headful navigator, but I'm not sure using pyautogui will work when I try to use a headless navigator.), like such:

import pyautogui
path = r"C:\path\to_my_file.pdf"
pyautogui.write(path)
pyautogui.hotkey('enter')

My problem is that instead of typing the content of path, pyautogui types the keyboard keys that correspond to each character. Therefore, I get C/\path\to8my8file.pdf, because I have a french keyboard (where numbers are uppercase and special characters like _ and : are lowercase).

Of course, I could make sure that when pyautogui types : and _, it does what's needed to do shift + / and shift + 8, but that would be painstaking, and it would have to be done to each specific usecase. I'm sure there is a better, generic way, to type precisely the content of path.

Sidenote:

An old SO question had the answers pyautogui.write('C:\path\to_my_file.pdf', interval=0.1) or pyautogui.typewrite("C:\path\to_my_file.pdf", interval=0.1). They do not work.


问:
xml value editing with php
I need to delete the value of <price>68.834</price> with point to <price>68834</price>
Is it possible to do it in ubuntu vps with php cronjob?

I took the xml in original location from another server and download to my web public html in xml format but i should change this price values in all over the xml without "."
This is my xml file ;

```<code><products>
<product>
<brand>Brand</brand>
<name>Gold ring</name>
<price>68.834</price>
<product_url>https://www.brand.com/blablaa</product_url>
<stok>1</stok>
</products>
<products>
.......
</code>```

I tried like this :

```<code>$xmlDoc = new \DOMDocument;$xmlDoc->load('products.xml');
$response = $xmlDoc->getElementsByTagName('price');
foreach ($response as $node){$node->nodeValue = '????';}
$xmlDoc->saveXML();
</code>```

how can i find the point in the value and remove it?

Title: xml value editing with php

Body:
I need to delete the value of <price>68.834</price> with point to <price>68834</price>
Is it possible to do it in ubuntu vps with php cronjob?

I took the xml in original location from another server and download to my web public html in xml format but i should change this price values in all over the xml without "."
This is my xml file ;

<products>
<product>
<brand>Brand</brand>
<name>Gold ring</name>
<price>68.834</price>
<product_url>https://www.brand.com/blablaa</product_url>
<stok>1</stok>
</products>
<products>
.......

I tried like this :

$xmlDoc = new \DOMDocument;$xmlDoc->load('products.xml');
$response = $xmlDoc->getElementsByTagName('price');
foreach ($response as $node){$node->nodeValue = '????';}
$xmlDoc->saveXML();

how can i find the point in the value and remove it?