问:
How to fix problem with Roboto font load in Google Chrome?
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

```<code>GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND
</code>```

I tried to import directy in the CSS and in the HTML this:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}
</code>```

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>
</code>```

答:
the URL is not correct
use this</p>

```<code>@import url('https://fonts.googleapis.com/css?family=Roboto+Mono:100i,300,300i,400,400i,500,500i,700,700i&display=swap');
</code>```

Body:
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND

I tried to import directy in the CSS and in the HTML this:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

        <link rel="stylesheet" href="./css/style.css"></link>

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>

Body:
the URL is not correct
use this

@import url('https://fonts.googleapis.com/css?family=Roboto+Mono:100i,300,300i,400,400i,500,500i,700,700i&display=swap');


来源: stackexchange

问:
2D array on CUDA
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

```<code>int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}
</code>```

Any suggestions? Thank you.

答:
Two opening comments - using a dynamically allocated 2D array is a bad idea in CUDA, and doing repetitive memory allocations in a loop is also not a good idea. Both incur needless performance penalties.

For the host code, something like this:

```<code>size_t allocsize = 16000 * sizeof(float);
int n_allocations = 16;
float * dpointer
cudaMalloc((void **)&dpointer, n_allocations * size_t(allocsize));

float * dcurrent = dpointer;
int n = 0;
for(int i=0; ((n==0) && (i<n_allocations)); i++, dcurrent+=allocsize) {

    // whatever you do before the kernel

    kernel <<< gridsize,blocksize >>> (dcurrent,.....);

    // whatever you do after the kernel

}
</code>```

is preferable. Here you only call cudaMalloc once, and pass offsets into the allocation, which makes memory allocation and management free inside the loop. The loop structure also means you can't run endlessly and exhaust all the GPU memory.

On the 2D array question itself, there are two reasons why it is a bad idea. Firstly, the allocation requires of a 2D array with N rows requires (N+1) cudaMalloc calls and a host device memory copy, which is slow and ugly. Secondly inside the kernel code, to get at your data, the GPU must do two global memory reads, one for the pointer indirection to get the row address, and then one to fetch from the data from the row. That is much slower than this alternative:

```<code>#define idx(i,j,lda) ( (j) + ((i)*(lda)) )
__global__ void kernerl(float * Mem, int lda, ....)
{
    Mem[idx(0,5,lda)]=1; // MemMem[0][5]=1;
}
</code>```

which uses indexing into a 1D allocation. In the GPU memory transactions are very expensive, but FLOPS and IOPS are cheap. A single integer multiply-add is the most efficient way to do this. If you need to access results from a previous kernel call, just pass the offset to the previous results and use two pointers inside the kernel, something like this:

```<code>__global__ void kernel(float *Mem, int lda, int this, int previous)
{
   float * Mem0 = Mem + this;
   float * Mem1 = Mem + previous;

}
</code>```

Efficient distributed memory programs (and CUDA is really a type of distributed memory programming) start to look like Fortran after a while, but that is the price you pay for portability, transparency and efficiency.

Hope this helped.

ContentLicense: CC BY-SA 3.0

Title: 2D array on CUDA

Body:
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}

Any suggestions? Thank you.

Body:
Two opening comments - using a dynamically allocated 2D array is a bad idea in CUDA, and doing repetitive memory allocations in a loop is also not a good idea. Both incur needless performance penalties.

For the host code, something like this:

size_t allocsize = 16000 * sizeof(float);
int n_allocations = 16;
float * dpointer
cudaMalloc((void **)&dpointer, n_allocations * size_t(allocsize));

float * dcurrent = dpointer;
int n = 0;
for(int i=0; ((n==0) && (i<n_allocations)); i++, dcurrent+=allocsize) {

    // whatever you do before the kernel

    kernel <<< gridsize,blocksize >>> (dcurrent,.....);

    // whatever you do after the kernel

}

is preferable. Here you only call cudaMalloc once, and pass offsets into the allocation, which makes memory allocation and management free inside the loop. The loop structure also means you can't run endlessly and exhaust all the GPU memory.

On the 2D array question itself, there are two reasons why it is a bad idea. Firstly, the allocation requires of a 2D array with N rows requires (N+1) cudaMalloc calls and a host device memory copy, which is slow and ugly. Secondly inside the kernel code, to get at your data, the GPU must do two global memory reads, one for the pointer indirection to get the row address, and then one to fetch from the data from the row. That is much slower than this alternative:

#define idx(i,j,lda) ( (j) + ((i)*(lda)) )
__global__ void kernerl(float * Mem, int lda, ....)
{
    Mem[idx(0,5,lda)]=1; // MemMem[0][5]=1;
}

which uses indexing into a 1D allocation. In the GPU memory transactions are very expensive, but FLOPS and IOPS are cheap. A single integer multiply-add is the most efficient way to do this. If you need to access results from a previous kernel call, just pass the offset to the previous results and use two pointers inside the kernel, something like this:

__global__ void kernel(float *Mem, int lda, int this, int previous)
{
   float * Mem0 = Mem + this;
   float * Mem1 = Mem + previous;

}

Efficient distributed memory programs (and CUDA is really a type of distributed memory programming) start to look like Fortran after a while, but that is the price you pay for portability, transparency and efficiency.

Hope this helped.


问:
How to set up a function to highlight the existence of a set of two specific values within a table?
I'm setting up a google sheet (they won't let me use excel, unfortunately :/) to track shifts at stations for a pool that I manage. There are pairs of people that I want to avoid scheduling to work together. I'd like my sheet to highlight the names of pairs of people in a table if I have scheduled those two people to work at the same time.

I've tried using a COUNTIF function and putting pairs of people that I don't want to work together in named ranges (the sheet is named Duties!), then pulling from the named range, e.g. Duties!E12:F12. My table has values E2:M10 so the function looked something like

```<code>=COUNTIF(E2:M10,E2)=Duties!E12:F12
</code>```

However, that's not working.

答:
let's say you have a table A1:D12 and a and b can't be next to each other:

custom formula: =COUNTIFS(A1, "a" ,B1, "b") applied to range A1:D12

custom formula: =COUNTIFS(A1, "a" ,B1, "b") applied to range B1:E12

if a and b are on Sheet2 in A1 and B1 you use INDIRECT like:

=COUNTIFS(A1, INDIRECT("Sheet2!A1") ,B1, INDIRECT("Sheet2!B1"))

ContentLicense: CC BY-SA 4.0

Body:
I'm setting up a google sheet (they won't let me use excel, unfortunately :/) to track shifts at stations for a pool that I manage. There are pairs of people that I want to avoid scheduling to work together. I'd like my sheet to highlight the names of pairs of people in a table if I have scheduled those two people to work at the same time.

I've tried using a COUNTIF function and putting pairs of people that I don't want to work together in named ranges (the sheet is named Duties!), then pulling from the named range, e.g. Duties!E12:F12. My table has values E2:M10 so the function looked something like

=COUNTIF(E2:M10,E2)=Duties!E12:F12

However, that's not working.


问:
Why is this int array not passed as an object vararg array?
I used this code. I am confused why this int array is not converted to an object vararg argument:

```<code>class MyClass {
    static void print(Object... obj) {
        System.out.println("Object…: " + obj[0]);
    }

    public static void main(String[] args) {
        int[] array = new int[] {9, 1, 1};
        print(array);
        System.out.println(array instanceof Object);
    }
}
</code>```

I expected the output:

```<code>Object…: 9
true
</code>```

but it gives:

```<code>Object…: [I@140e19d
true
</code>```

答:
```<code>class MyClass {
    static void print(Object... obj) {
        System.out.println("Object…: " + obj[0]);
    }

        public static void main(String[] args) {
            int[] array = new int[] {9, 1, 1};
        // To boxed array
        Integer[] oArray = Arrays.stream( array ).boxed().toArray( Integer[]::new );

            print(oArray);
            System.out.println(oArray instanceof Object);
        }
    }
</code>```

Body:
I used this code. I am confused why this int array is not converted to an object vararg argument:

class MyClass {
    static void print(Object... obj) {
        System.out.println("Object…: " + obj[0]);
    }

    public static void main(String[] args) {
        int[] array = new int[] {9, 1, 1};
        print(array);
        System.out.println(array instanceof Object);
    }
}

I expected the output:

Object…: 9
true

but it gives:

Object…: [I@140e19d
true


问:
Constructor Lists in particular order with pointers
I am writing code that uses a library with no default constructor (there is, but it's soon to be deprecated, and throws warnings), and I'd like to use it inside a class. Now, I am aware that there are several answers for this in general, but none seem to answer my particular variant.

Here's why:
The library's constructor takes a pointer to two arrays that are used for input and output. I need to allocate memory for those arrays, and I have to do this before I call this library's constructor.

I thus need an alternative to constructor lists that will allow me to control the order, or I need to know how to allocate memory for objects inside a constructor list.

Here is the relevant code:

My class:

```<code>class audio_class{
arduinoFFT FFT;//cannot call constructor HERE, but that leaves the default!
double *real_samples;
double *imaginary;
//--snip--
};
</code>```

Library's constructor:

```<code>arduinoFFT(double *vReal, double *vImag, uint16_t samples, double samplingFrequency);
</code>```

My code's constructor:

```<code>audio_class::audio_class() {
  real_samples = new double[READINGS];
  imaginary = new double[READINGS];
  //Need to initialize arduinoFFT here? Or after allocation of samples, anyway. Constructor list would fire before I call the new[], and the pointers would be invalid. I think?
}

audio_class::~audio_class() {
  delete[] real_samples;
  delete[] imaginary;
}
</code>```

答:
The order of initialization of class data members is determined by the order of declaration in the class definition. (The order of member initializers in the constructor has no effect on this.) So you could rearrange the members to do something like:

```<code>class audio_class{
    double *real_samples;
    double *imaginary;
    arduinoFFT FFT;
    //--snip--
};

audio_class::audio_class() :
    real_samples(new double[READINGS]),
    imaginary(new double[READINGS]),
    FFT(real_samples, imaginary, READINGS, DFLT_FFT_FREQ)
{
}
</code>```

But there's an unrelated issue here: this is not exception-safe. If either the second new or the arduinoFFT constructor throws an exception, the previous allocations are never deleted and are leaked. Plus dealing with new and delete yourself is trickier, and requires more code (obey at least the Rule of Three). So I'd recommend using std::vector here to switch to RAII / Rule of Zero, to fix all of that at once.

```<code>#include <vector>

class audio_class{
    std::vector<double> real_samples;
    std::vector<double> imaginary;
    arduinoFFT FFT;
    // No destructor declaration needed.
    //--snip--
};

audio_class::audio_class() :
    real_samples(READINGS),
    imaginary(READINGS),
    FFT(real_samples.data(), imaginary.data(), READINGS, DFLT_FFT_FREQ)
{
}
</code>```

(This way still requires FFT to be declared after real_samples and imaginary, for the same reasons.)

Body:
I am writing code that uses a library with no default constructor (there is, but it's soon to be deprecated, and throws warnings), and I'd like to use it inside a class. Now, I am aware that there are several answers for this in general, but none seem to answer my particular variant.

Here's why:
The library's constructor takes a pointer to two arrays that are used for input and output. I need to allocate memory for those arrays, and I have to do this before I call this library's constructor.

I thus need an alternative to constructor lists that will allow me to control the order, or I need to know how to allocate memory for objects inside a constructor list.

Here is the relevant code:

My class:

class audio_class{
arduinoFFT FFT;//cannot call constructor HERE, but that leaves the default!
double *real_samples;
double *imaginary;
//--snip--
};

Library's constructor:

arduinoFFT(double *vReal, double *vImag, uint16_t samples, double samplingFrequency);

My code's constructor:

audio_class::audio_class() {
  real_samples = new double[READINGS];
  imaginary = new double[READINGS];
  //Need to initialize arduinoFFT here? Or after allocation of samples, anyway. Constructor list would fire before I call the new[], and the pointers would be invalid. I think?
}

audio_class::~audio_class() {
  delete[] real_samples;
  delete[] imaginary;
}

Body:
The order of initialization of class data members is determined by the order of declaration in the class definition. (The order of member initializers in the constructor has no effect on this.) So you could rearrange the members to do something like:

class audio_class{
    double *real_samples;
    double *imaginary;
    arduinoFFT FFT;
    //--snip--
};

audio_class::audio_class() :
    real_samples(new double[READINGS]),
    imaginary(new double[READINGS]),
    FFT(real_samples, imaginary, READINGS, DFLT_FFT_FREQ)
{
}

But there's an unrelated issue here: this is not exception-safe. If either the second new or the arduinoFFT constructor throws an exception, the previous allocations are never deleted and are leaked. Plus dealing with new and delete yourself is trickier, and requires more code (obey at least the Rule of Three). So I'd recommend using std::vector here to switch to RAII / Rule of Zero, to fix all of that at once.

#include <vector>

class audio_class{
    std::vector<double> real_samples;
    std::vector<double> imaginary;
    arduinoFFT FFT;
    // No destructor declaration needed.
    //--snip--
};

audio_class::audio_class() :
    real_samples(READINGS),
    imaginary(READINGS),
    FFT(real_samples.data(), imaginary.data(), READINGS, DFLT_FFT_FREQ)
{
}

(This way still requires FFT to be declared after real_samples and imaginary, for the same reasons.)


问:
Using the reorder function within geom_point in ggplot2
Beginner to R, and here is my beginner question: I would like to know how to use the reorder function within geom_point

if I run my code (below), the figure will arrange the x axis according to number order 1,2,3,5 of the first number in "Split_time" column, and not the order I would want: m_5,m_10,m_20,m_30.

What would be the appropriate change here?

This is my data set:

```<code>Group Split_time ES
Heavy m_5 -0.753006245
Heavy m_10 -0.946046493
Heavy m_20 -0.766883256
 Heavy m_30 -0.6175288
Optimal m_5 -1.041742539
Optimal m_10 -1.253699539
 Optimal m_20 -1.153807339
 Optimal m_30 -1.179895776
Control m_5 -0.503250366
Control m_10 -0.476303945
Control m_20 -0.543155436
 Control m_30 -0.54148328
</code>```

Code:

```<code>ggplot(SledESsplittimes2, aes(x = Split_time, y = ES, col = Group)) + geom_point()
</code>```

答:
It is because that column is of type character and when characters are sorted, "1" comes before "5" (so "m_10" comes before "m_5").

The data type in R that is used for categorical variables is called "factor". Read more on https://www.stat.berkeley.edu/~s133/factors.html and https://www.rdocumentation.org/packages/base/versions/3.6.0/topics/factor

In your case, you can convert Split_time to a factor, and specify the levels manually in the order that you like them.

```<code>df$Split_time = factor(df$Split_time, levels = c("m_5", "m_10", "m_20", "m_30"))
</code>```

Once you do that, ggplot will also order the factor based on its levels, with m_5 coming before m_10

Body:
Beginner to R, and here is my beginner question: I would like to know how to use the reorder function within geom_point

if I run my code (below), the figure will arrange the x axis according to number order 1,2,3,5 of the first number in "Split_time" column, and not the order I would want: m_5,m_10,m_20,m_30.

What would be the appropriate change here?

This is my data set:

Group Split_time ES
Heavy m_5 -0.753006245
Heavy m_10 -0.946046493
Heavy m_20 -0.766883256
 Heavy m_30 -0.6175288
Optimal m_5 -1.041742539
Optimal m_10 -1.253699539
 Optimal m_20 -1.153807339
 Optimal m_30 -1.179895776
Control m_5 -0.503250366
Control m_10 -0.476303945
Control m_20 -0.543155436
 Control m_30 -0.54148328

Code:

ggplot(SledESsplittimes2, aes(x = Split_time, y = ES, col = Group)) + geom_point()

Body:
It is because that column is of type character and when characters are sorted, "1" comes before "5" (so "m_10" comes before "m_5").

The data type in R that is used for categorical variables is called "factor". Read more on https://www.stat.berkeley.edu/~s133/factors.html and https://www.rdocumentation.org/packages/base/versions/3.6.0/topics/factor

In your case, you can convert Split_time to a factor, and specify the levels manually in the order that you like them.

df$Split_time = factor(df$Split_time, levels = c("m_5", "m_10", "m_20", "m_30"))

Once you do that, ggplot will also order the factor based on its levels, with m_5 coming before m_10


问:
Datatype of dataframe columns
I am having a pandas dataframe which has more than 100 columns in it. Some are of object datatype and some are float64 datatype. Is there a way to display the datatype of each columns in the dataframe. </p>

答:
You can use .dtypes to display all datatypes in each column

```<code>df = pd.read_csv('my_df.csv')
df.dtypes

School_ID                           float64
ExNO                                  int64
MemberID                              int64
CourseNO                              int64
tba_id                                int64
.
.
.
</code>```

Update:
To find a number of float64 columns, I would do as follows,

```<code>col_float = len([i for i in df.dtypes if i == 'float64'])
</code>```

Title: Datatype of dataframe columns

Body:
You can use .dtypes to display all datatypes in each column

df = pd.read_csv('my_df.csv')
df.dtypes

School_ID                           float64
ExNO                                  int64
MemberID                              int64
CourseNO                              int64
tba_id                                int64
.
.
.

Update:
To find a number of float64 columns, I would do as follows,

col_float = len([i for i in df.dtypes if i == 'float64'])


问:
Memory leak while using posenet in tensorflow JavaScript
I am trying to experiment tensorflow using javascript. I want to run the posenet model over a folder of images. With some googling I have written the HTML below. When I run the HTML shown below the system is running out of memory soon, indeed there is a memory leak. I don't know where and how the memory leak is happening. Can community please explain how the memory leak is happening and how to get around it

```<code><html>
  <head>
    <script src="https://unpkg.com/@tensorflow/tfjs"></script>
    <script src="https://unpkg.com/@tensorflow-models/posenet"</script>
 </head>

  <body>
    <img id='faceImg' src='1.0.jpg'/>

  <script>
      var i = 1;
      async function makeTensors(){
            var psData;
           var imageScaleFactor = 0.5;
           var outputStride = 16;
           var flipHorizontal = false;
          var iterator;
           var imageElements = document.getElementById('faceImg');

       console.log(imageElements);

      let result = await posenet.load().then(function(net){
        return net.estimateSinglePose(imageElements, imageScaleFactor, flipHorizontal, outputStride)
      }).then(function(pose){
        console.log(pose);
        psData = pose;
      })

       var im_tensor_pos = []
       for (iter = 0; iter < 17; iter++) {
         im_tensor_pos.push(psData.keypoints[iter].position.x);
         im_tensor_pos.push(psData.keypoints[iter].position.y);
       }
       for (iter = 0; iter < 17; iter++) {
         im_tensor_pos.push(psData.keypoints[iter].score);
       }
       im_tensor_pos.push(psData.score);
      //  tensor_vals.push(im_tensor_pos);
       psData = null;
       delete result;
      // console.log(tensor_vals);
    }

    async function test(){
      for (i = 1; i < 270; i++) {
        var ImageSrc = 'results/' + i + ".0.jpg";
        console.log(ImageSrc)
        var imageElements = document.getElementById('faceImg');
        imageElements.src = ImageSrc;

        result = await makeTensors();
        delete result;
      }
    }
    test().then(console.log('done'));

   </script>
  </body>
  </html>
</code>```

This is my first attempt at js too. Please let me know if your thoughts on code too.

答:
I'm not seeing any space where you're disposing your tensors.  Remember if you're not calling .dispose on a tensor you're done with, it's still going to sit in memory.

Dispose logic:
https://js.tensorflow.org/api/latest/#dispose

For debugging the memmory issue, please look at using tf.memory to see where the issue might be building:   https://js.tensorflow.org/api/latest/#memory

Body:
I am trying to experiment tensorflow using javascript. I want to run the posenet model over a folder of images. With some googling I have written the HTML below. When I run the HTML shown below the system is running out of memory soon, indeed there is a memory leak. I don't know where and how the memory leak is happening. Can community please explain how the memory leak is happening and how to get around it

This is my first attempt at js too. Please let me know if your thoughts on code too.


问:
if else for ant script
hi current i have this ant script:

```<code>        <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${Product_version}/${name}"'/>
        </exec>

    </target>
</code>```

what this script does is that it will execute ssremove.exe with some parameters as shown.

however, this script above is only valid when the parameter ${Product_version} contains the word "Extensions" for example 6.00_Extensions

Else if they dont contain "Extensions" the script should look like this:

```<code>    <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${name}"'/>
        </exec>

    </target>
</code>```

so my question is how should i add the if else statements that contain exactly the line "Extensions"? or how do i check if "Extensions" word is present?

答:
There is an ant library : antlib ( http://ant-contrib.sourceforge.net)

which supports if/else statements ( http://ant-contrib.sourceforge.net/tasks/tasks/index.html)

Examples from the site:

```<code><if>
 <equals arg1="${foo}" arg2="bar" />
 <then>
   <echo message="The value of property foo is bar" />
 </then>
 <else>
   <echo message="The value of property foo is not bar" />
 </else>
</if>

<if>
 <equals arg1="${foo}" arg2="bar" />
 <then>
   <echo message="The value of property foo is 'bar'" />
 </then>

 <elseif>
  <equals arg1="${foo}" arg2="foo" />
  <then>
   <echo message="The value of property foo is 'foo'" />
  </then>
 </elseif>

 <else>
   <echo message="The value of property foo is not 'foo' or 'bar'" />
 </else>
</if>
</code>```

Title: if else for ant script

Body:
hi current i have this ant script:

        <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${Product_version}/${name}"'/>
        </exec>

    </target>

what this script does is that it will execute ssremove.exe with some parameters as shown.

however, this script above is only valid when the parameter ${Product_version} contains the word "Extensions" for example 6.00_Extensions

Else if they dont contain "Extensions" the script should look like this:

    <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${name}"'/>
        </exec>

    </target>

so my question is how should i add the if else statements that contain exactly the line "Extensions"? or how do i check if "Extensions" word is present?

Body:
There is an ant library : antlib ( http://ant-contrib.sourceforge.net)

which supports if/else statements ( http://ant-contrib.sourceforge.net/tasks/tasks/index.html)

Examples from the site:

<if>
 <equals arg1="${foo}" arg2="bar" />
 <then>
   <echo message="The value of property foo is bar" />
 </then>
 <else>
   <echo message="The value of property foo is not bar" />
 </else>
</if>

<if>
 <equals arg1="${foo}" arg2="bar" />
 <then>
   <echo message="The value of property foo is 'bar'" />
 </then>

 <elseif>
  <equals arg1="${foo}" arg2="foo" />
  <then>
   <echo message="The value of property foo is 'foo'" />
  </then>
 </elseif>

 <else>
   <echo message="The value of property foo is not 'foo' or 'bar'" />
 </else>
</if>


问:
How to perform face recognition on a streaming video using amazon Rekognition?
I am streaming video the amazon kinesis from raspberry pi (This is done). Now i want to perform face detection/recognition on that video using amazon Rekognition how to do it explain in detail with links. Thanks</p>

答:
From Working with Streaming Videos - Amazon Rekognition:

You can use Amazon Rekognition Video to detect and recognize faces in streaming video. A typical use case is when you want to detect a known face in a video stream. Amazon Rekognition Video uses Amazon Kinesis Video Streams to receive and process a video stream. The analysis results are output from Amazon Rekognition Video to a Kinesis data stream and then read by your client application. Amazon Rekognition Video provides a stream processor (CreateStreamProcessor) that you can use to start and manage the analysis of streaming video.

In simple terms, your application sends video to Amazon Kinesis Video. It then calls Amazon Rekognition on your behalf and detected faces are provided via an Amazon Kinesis stream. You can write an application to consume this stream and react to faces detected. There is a delay of several seconds for the video to be processed.


问:
Refer to a Property name using a Variable in Linq
I am trying to access a property "DailyQtyOrders_01" in my object using the first code below, this works ok.
but now i want to use it in a linq expression on the second line code, this works, but i want the property to be variable (3rd line code), this throws error. What is the method to do that?</p>

```<code>item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().DailyQtyOrders_01 = 5;

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);
</code>```

答:
First of all if this code is run in any sort of loop, you have to be careful you dont run into performance issues.

When you enter the areas of .GetType(),.GetProperty() and .SetProperty() you are doing reflection, which really shouldn't be nessesary.

It's hard to see from your code example but the Order that you have in your item should really be changable from item.DailyQtyOrders_01 directly. Also if you really want to use strings and reflection, which i cannot recommend in any way, you can at least use strongly typed ways to achieve this (which makes sure your code doesn't break on a refactor)

That would make this code:

```<code>item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5)
</code>```

Look like this instead:

```<code>item.GetType().GetProperty(nameof(Order.DailyQtyOrders_01)).SetValue(item, 5)
</code>```

available from c# 6.0 and forward, nameof can be used on classes and properties and so on to get the string, but avoiding the actual string, that you might not catch in a rename.

Body:
I am trying to access a property "DailyQtyOrders_01" in my object using the first code below, this works ok.
but now i want to use it in a linq expression on the second line code, this works, but i want the property to be variable (3rd line code), this throws error. What is the method to do that?

item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().DailyQtyOrders_01 = 5;

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

Body:
First of all if this code is run in any sort of loop, you have to be careful you dont run into performance issues.

When you enter the areas of .GetType(),.GetProperty() and .SetProperty() you are doing reflection, which really shouldn't be nessesary.

It's hard to see from your code example but the Order that you have in your item should really be changable from item.DailyQtyOrders_01 directly. Also if you really want to use strings and reflection, which i cannot recommend in any way, you can at least use strongly typed ways to achieve this (which makes sure your code doesn't break on a refactor)

That would make this code:

item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5)

Look like this instead:

item.GetType().GetProperty(nameof(Order.DailyQtyOrders_01)).SetValue(item, 5)

available from c# 6.0 and forward, nameof can be used on classes and properties and so on to get the string, but avoiding the actual string, that you might not catch in a rename.


问:
Reading data from NetworkStream
I try to send a lot of data (an image) on a NetworkStream, yet it looks like a single Read is not enough- I'd like to try to read all the data sent on a NetworkStream, yet I have no idea how to do that. Also, I'd like to have this data as a bytes array byte[]. Any idea how to do that?

```<code>byte[] b = new byte[length];
int bytes = 0;
while (!GetNetworkStream().DataAvailable)
    Thread.Sleep(20); // Some delay
bytes = GetNetworkStream().Read(b, 0, b.Length);
MemoryStream ms = new MemoryStream();
ms.Write(b, 0, bytes);

</code>```

I also tried the next code which does not seem to work:

```<code>using (NetworkStream stream = CommunicationHandler.GetStream())
{
    byte[] data = new byte[1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int numBytesRead;
        while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
        ms.Write(data, 0, numBytesRead);
    }
}
</code>```

答:
As I can see you put in here some methods which you have created on your own and I suppose you don't have any problems in reading data.
What you really need is some kind of handle at start of a new file because your socket should receiving data continiously.

It obviously depends on which image format you want to use, what you want to send.
For PNG files you should read chapter 12 of this pdf file. Especially section 12. You could look for signature and extracting data from buffer if you hit sequence like this

```<code>(decimal)             137 80 78 71 13 10 26   10
(hexadecimal)          89 50 4e 47 0d 0a 1a   0a
(ASCII C notation)   \211 P  N   G \r \n \032 \n
</code>```

Then you need to simply recreate png file. You must do the same with every type of file you send.

If you do not care about content of a file you could've create some data frame and put the data into payload (compressed and encrypted). Create own signature blahblahblah.
The simplest example is Modbus. You can read more about it here.

edit

Reading the data of tcp stream is very simple. Just look at this code.

```<code>var receiveBufferSize = 512; // amount of bytes to read
try
{
    var buffer = new byte[receiveBufferSize];
    _tcpClient.GetStream().Read(buffer, 0, receiveBufferSize);
    // handle the received data chunk
}
catch (Exception e)
{
    // handle the error
    Debug.WriteLine(ex.Message);
}
</code>```

Title: Reading data from NetworkStream

Body:
I try to send a lot of data (an image) on a NetworkStream, yet it looks like a single Read is not enough- I'd like to try to read all the data sent on a NetworkStream, yet I have no idea how to do that. Also, I'd like to have this data as a bytes array byte[]. Any idea how to do that?

byte[] b = new byte[length];
int bytes = 0;
while (!GetNetworkStream().DataAvailable)
    Thread.Sleep(20); // Some delay
bytes = GetNetworkStream().Read(b, 0, b.Length);
MemoryStream ms = new MemoryStream();
ms.Write(b, 0, bytes);

I also tried the next code which does not seem to work:

using (NetworkStream stream = CommunicationHandler.GetStream())
{
    byte[] data = new byte[1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int numBytesRead;
        while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
        ms.Write(data, 0, numBytesRead);
    }
}

Body:
As I can see you put in here some methods which you have created on your own and I suppose you don't have any problems in reading data.
What you really need is some kind of handle at start of a new file because your socket should receiving data continiously.

It obviously depends on which image format you want to use, what you want to send.
For PNG files you should read chapter 12 of this pdf file. Especially section 12. You could look for signature and extracting data from buffer if you hit sequence like this

(decimal)             137 80 78 71 13 10 26   10
(hexadecimal)          89 50 4e 47 0d 0a 1a   0a
(ASCII C notation)   \211 P  N   G \r \n \032 \n

Then you need to simply recreate png file. You must do the same with every type of file you send.

If you do not care about content of a file you could've create some data frame and put the data into payload (compressed and encrypted). Create own signature blahblahblah.
The simplest example is Modbus. You can read more about it here.

edit

Reading the data of tcp stream is very simple. Just look at this code.

var receiveBufferSize = 512; // amount of bytes to read
try
{
    var buffer = new byte[receiveBufferSize];
    _tcpClient.GetStream().Read(buffer, 0, receiveBufferSize);
    // handle the received data chunk
}
catch (Exception e)
{
    // handle the error
    Debug.WriteLine(ex.Message);
}


问:
How to change content mode on AVPlayer video?
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

```<code>let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)
</code>```

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.

答:
This may work for you
https://gist.github.com/jkosoy/c835fea2c03e76720c77

Call this method when your video started buffering

```<code>DispatchQueue.main.async {
    let size = CGSize.aspectFit(aspectRatio: self. avPlayerLayer.frame.size, boundingSize: self.view.frame.size)
    self.avPlayerLayerHeightContraint.constant = size.height
    self.avPlayerLayer.layoutIfNeeded()
}
</code>```

Hope you get
the desired result.

Body:
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.

Body:
This may work for you
https://gist.github.com/jkosoy/c835fea2c03e76720c77

Call this method when your video started buffering

DispatchQueue.main.async {
    let size = CGSize.aspectFit(aspectRatio: self. avPlayerLayer.frame.size, boundingSize: self.view.frame.size)
    self.avPlayerLayerHeightContraint.constant = size.height
    self.avPlayerLayer.layoutIfNeeded()
}

Hope you get
the desired result.


问:
Generate Header for txt file
I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.

What am I doing wrong?

function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){

    // Generate .txt file header

    //force 4 chars
    let id = document.getElementById("senderID");
    if (id.textContent.length < 4) {

            id.textContent += ' ';

    }

    //force 45 chars
    let name = document.getElementById("senderName");
    if (name.textContent.length < 45) {
        name.textContent += ' ';
    }

    let header = "HDRPB" + id.textContent + name + "01.10";
    let body = document.getElementById("fileContents").textContent;

    let text = header;

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/site.css">
    <title>Generator</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-2 p-0 mt-2">
          <label for="senderID" class="font-weight-bold">Sender ID:</label>
          <input id="senderID" type="text" maxlength="4" size="4"/>
        </div>
        <div class="col-6 p-0 mt-2">
          <label for="senderName" class="font-weight-bold">Sender Name:</label>
          <input id="senderName" type="text" maxlength="45" size="45"/>
        </div>
      </div>
      <div class="row mt-5">
        <div class="col-10">
          <label for="fileName" class="font-weight-bold">File Name:</label>
          <input id="fileName" type="text"/>
        </div>
        <div class="col-2">
          <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
        </div>
      </div>
      <div id="fileContents" class=""></div>
    </div>
    <script src="js/app.js"></script>
  </body>
</html></code>```

答:
Consider the following code:

function genId(seed) {
  var result = new Array(4);
  for (var i = 0; i < 4; i++) {
    result[i] = seed[i] || " ";
  }
  return result.join("");
}

function genName(seed) {
  var result = new Array(45);
  for (var c = 0; c < 45; c++) {
    result[c] = seed[c] || " ";
  }
  return result.join("");
}

document.getElementById("genHead").addEventListener("click", function() {
  var i = document.getElementById("hid").value;
  var n = document.getElementById("hname").value;
  var header = genId(i) + genName(n);
  document.getElementById("results").innerHTML = header;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#results {
  font-family: monospace;
  border: 1px solid #ccc;
  display: inline-block;
}</code>```

ID: <input type="text" id="hid" />

Name: <input type="" id="hname" />

<button id="genHead">Generate Header</button>

```
</div>
</div>
</p>

<p>In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using <code>$nbsp;</code> to represent spaces in HTML but you can use <code>' '</code> or <code>" "</code>.</p>

<p>There will always be a result due to <code>result[c] = seed[c] || " ";</code> If <code>seed</code> has a character in that position, it will be entered into <code>result</code> at the same position. Otherwise it will enter the No Break Space or the character you want. </p>

<p>You can also do this:</p>

```function formatText(t, n, c) {
  if(t == undefined){
    return "";
  }
  if(n == undefined){
    n = 45;
  }
  if(c == undefined){
    c = " ";
  }
  var r = new Array(n);
  for (var i = 0; i < n; i++) {
    r[i] = t[i] || c;
  }
  return r.join("");
}
```

<p>Then use like so:</p>

```var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");
```

Hope this helps.

Title: Generate Header for txt file

Body:
I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.

What am I doing wrong?

function download(fileName, text) {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', fileName);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){

    // Generate .txt file header

    //force 4 chars
    let id = document.getElementById("senderID");
    if (id.textContent.length < 4) {

            id.textContent += ' ';

    }

    //force 45 chars
    let name = document.getElementById("senderName");
    if (name.textContent.length < 45) {
        name.textContent += ' ';
    }

    let header = "HDRPB" + id.textContent + name + "01.10";
    let body = document.getElementById("fileContents").textContent;

    let text = header;

    let fileName = document.getElementById("fileName").value + ".txt";

    download(fileName, text);
}, false);

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/site.css">
    <title>Generator</title>

          Sender ID:
          <input id="senderID" type="text" maxlength="4" size="4"/>

          Sender Name:
          <input id="senderName" type="text" maxlength="45" size="45"/>

          File Name:
          <input id="fileName" type="text"/>

          <button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>

Body:
Consider the following code:

function genId(seed) {
  var result = new Array(4);
  for (var i = 0; i < 4; i++) {
    result[i] = seed[i] || "&nbsp;";
  }
  return result.join("");
}

function genName(seed) {
  var result = new Array(45);
  for (var c = 0; c < 45; c++) {
    result[c] = seed[c] || "&nbsp;";
  }
  return result.join("");
}

document.getElementById("genHead").addEventListener("click", function() {
  var i = document.getElementById("hid").value;
  var n = document.getElementById("hname").value;
  var header = genId(i) + genName(n);
  document.getElementById("results").innerHTML = header;
});

#results {
  font-family: monospace;
  border: 1px solid #ccc;
  display: inline-block;
}

<p>ID: <input type="text" id="hid" /></p>
<p>Name: <input type="" id="hname" /></p>
<button id="genHead">Generate Header</button>
<div id="results"></div>

In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using $nbsp; to represent spaces in HTML but you can use ' ' or " ".

There will always be a result due to result[c] = seed[c] || "&nbsp;"; If seed has a character in that position, it will be entered into result at the same position. Otherwise it will enter the No Break Space or the character you want.

You can also do this:

function formatText(t, n, c) {
  if(t == undefined){
    return "";
  }
  if(n == undefined){
    n = 45;
  }
  if(c == undefined){
    c = " ";
  }
  var r = new Array(n);
  for (var i = 0; i < n; i++) {
    r[i] = t[i] || c;
  }
  return r.join("");
}

Then use like so:

var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");

Hope this helps.


问:
Problems using method in subclass dialog window to affect main window
I'm trying to create a GUI program using PyQT5.  I'm new to programming and Python so if I'm explaining things in the wrong way please correct me.

I have a main window that will contain multiple QLineEdit widgets and corresponding "Clear" buttons to clear the user entered data.  The main window also contains "Edit" buttons to dispay specific dialog boxes where the data can also be edited.  My example has a "User ID" QLineEdit widget/text box, "Clear" and "Edit" push buttons.

The dialog box that appears when "Edit' is clicked has it's own "Clear" button.  If the Clear button in the dialog window is clicked, both the QLineEdit widget in the dialog and main window should be cleared.

Problem: When I inherit the main window class from the dialog class the method, clearUserID(), used to clear the User ID field fails to be invoked.

When I do not inherit from the main window class the clearUserID method works and I am able to clear the dialog QLineEdit (UserIDWin_UserID_lnedt) but not the corresponding widget on the main window (UserID_lnedt).  All of the code I've tried to clear the main window QLineEdit widget using the dialog "Clear" button caused my program to crash.

Would somebody please help me to better understand the logic behind these principles and how to get my code working?  Thank you.

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 611)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
        self.tabWidget.setObjectName("tabWidget")
        self.MainTab = QtWidgets.QWidget()
        self.MainTab.setObjectName("MainTab")
        self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
        self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
        self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
        self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
        self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
        self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
        self.label = QtWidgets.QLabel(self.MainTab)
        self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
        self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
        self.UserID_le.setObjectName("UserID_le")
        self.tabWidget.addTab(self.MainTab, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
        self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
        self.label.setText(_translate("MainWindow", "User ID"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))

    def openUserIDWin(self):
        UserID_value = self.UserID_le.text()
        UserIDWin = QtWidgets.QDialog()
        ui = Ui_UserIDWin(UserID_value)
        ui.setupUi(UserIDWin)
        UserIDWin.exec_();

class Ui_UserIDWin(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, userID):
        print("The User ID is:" + userID)
        self.userID = userID

    def setupUi(self, UserIDWin):
        UserIDWin.setObjectName("UserIDWin")
        UserIDWin.resize(400, 124)
        self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
        self.UserIDWin_UserID_lnedt.setText(self.userID)
        self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
        self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
        self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
        self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
        self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
        self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
        self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
        self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
        self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
        self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
        self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")

        self.retranslateUi(UserIDWin)
        QtCore.QMetaObject.connectSlotsByName(UserIDWin)

        #If I do not inherit from "QtWidgets.QMainWindow, Ui_MainWindow" the code below works and invokes clearUserId().  However, I then am having problems using SetText on the main window UserId_le text box and the program crashes.
        self.UserIDWin_UserIDClear_pushb.clicked.connect(self.clearUserID)

    def retranslateUi(self, UserIDWin):
        _translate = QtCore.QCoreApplication.translate
        UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
        self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
        self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
        self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
        self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))

    def clearUserID(self):
        self.UserIDWin_UserID_lnedt.setText('')
        # The line below crashes my program if I am able to invoke this method.
        #self.Ui_MainWindow.UserID_le.setText('')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

</code>```

答:
It seems that they have certain clear concepts about inheritance and good practices but others do not like the following:

PyQt recommends not modifying the code generated by Qt Designer because you probably want to modify the GUI in the future and when using pyuic the initial code is overwritten. Another problem is that beginners do not understand that the class generated by Qt Designer is not a widget but an interface that serves to fill another widget, and consequently can not overwrite the methods of the widgets in addition to other problems.

You only have to modify the object of a class from the object of another class if both have the same scope, in your case when wanting to clean the QLineEdit of the main window from the other window is a dangerous task, instead you should do that logic where both windows have the same scope and that is in the openUserIDWin method.

QLineEdit already has the clear() method that allows to clean, it fulfills the same function as setText("") but the first method is more readable.

Considering the above, the solution is:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 611)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
        self.tabWidget.setObjectName("tabWidget")
        self.MainTab = QtWidgets.QWidget()
        self.MainTab.setObjectName("MainTab")
        self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
        self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
        self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
        self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
        self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
        self.label = QtWidgets.QLabel(self.MainTab)
        self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
        self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
        self.UserID_le.setObjectName("UserID_le")
        self.tabWidget.addTab(self.MainTab, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
        self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
        self.label.setText(_translate("MainWindow", "User ID"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))

class Ui_UserIDWin(object):
    def setupUi(self, UserIDWin):
        UserIDWin.setObjectName("UserIDWin")
        UserIDWin.resize(400, 124)
        self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
        self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
        self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
        self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
        self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
        self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
        self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
        self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
        self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
        self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
        self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
        self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")

        self.retranslateUi(UserIDWin)
        QtCore.QMetaObject.connectSlotsByName(UserIDWin)

    def retranslateUi(self, UserIDWin):
        _translate = QtCore.QCoreApplication.translate
        UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
        self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
        self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
        self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
        self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
        self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)

    def openUserIDWin(self):
        UserID_value = self.UserID_le.text()
        w = UserIDWin(UserID_value)
        w.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserID_le.clear)
        w.exec_()

class UserIDWin(QtWidgets.QDialog, Ui_UserIDWin):
    def __init__(self, userID, parent=None):
        super(UserIDWin, self).__init__(parent)
        self.setupUi(self)
        self.userID = userID
        self.UserIDWin_UserID_lnedt.setText(self.userID)
        self.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserIDWin_UserID_lnedt.clear)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
```

I recommend you read:

http://pyqt.sourceforge.net/Docs/PyQt5/designer.html

QtDesigner changes will be lost after redesign User Interface

Body:
I'm trying to create a GUI program using PyQT5.  I'm new to programming and Python so if I'm explaining things in the wrong way please correct me.

I have a main window that will contain multiple QLineEdit widgets and corresponding "Clear" buttons to clear the user entered data.  The main window also contains "Edit" buttons to dispay specific dialog boxes where the data can also be edited.  My example has a "User ID" QLineEdit widget/text box, "Clear" and "Edit" push buttons.

The dialog box that appears when "Edit' is clicked has it's own "Clear" button.  If the Clear button in the dialog window is clicked, both the QLineEdit widget in the dialog and main window should be cleared.

Problem: When I inherit the main window class from the dialog class the method, clearUserID(), used to clear the User ID field fails to be invoked.

When I do not inherit from the main window class the clearUserID method works and I am able to clear the dialog QLineEdit (UserIDWin_UserID_lnedt) but not the corresponding widget on the main window (UserID_lnedt).  All of the code I've tried to clear the main window QLineEdit widget using the dialog "Clear" button caused my program to crash.

Would somebody please help me to better understand the logic behind these principles and how to get my code working?  Thank you.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 611)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
        self.tabWidget.setObjectName("tabWidget")
        self.MainTab = QtWidgets.QWidget()
        self.MainTab.setObjectName("MainTab")
        self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
        self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
        self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
        self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
        self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
        self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
        self.label = QtWidgets.QLabel(self.MainTab)
        self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
        self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
        self.UserID_le.setObjectName("UserID_le")
        self.tabWidget.addTab(self.MainTab, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
        self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
        self.label.setText(_translate("MainWindow", "User ID"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))

    def openUserIDWin(self):
        UserID_value = self.UserID_le.text()
        UserIDWin = QtWidgets.QDialog()
        ui = Ui_UserIDWin(UserID_value)
        ui.setupUi(UserIDWin)
        UserIDWin.exec_();

class Ui_UserIDWin(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, userID):
        print("The User ID is:" + userID)
        self.userID = userID

    def setupUi(self, UserIDWin):
        UserIDWin.setObjectName("UserIDWin")
        UserIDWin.resize(400, 124)
        self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
        self.UserIDWin_UserID_lnedt.setText(self.userID)
        self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
        self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
        self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
        self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
        self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
        self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
        self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
        self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
        self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
        self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
        self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")

        self.retranslateUi(UserIDWin)
        QtCore.QMetaObject.connectSlotsByName(UserIDWin)

        #If I do not inherit from "QtWidgets.QMainWindow, Ui_MainWindow" the code below works and invokes clearUserId().  However, I then am having problems using SetText on the main window UserId_le text box and the program crashes.
        self.UserIDWin_UserIDClear_pushb.clicked.connect(self.clearUserID)

    def retranslateUi(self, UserIDWin):
        _translate = QtCore.QCoreApplication.translate
        UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
        self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
        self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
        self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
        self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))

    def clearUserID(self):
        self.UserIDWin_UserID_lnedt.setText('')
        # The line below crashes my program if I am able to invoke this method.
        #self.Ui_MainWindow.UserID_le.setText('')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Body:
It seems that they have certain clear concepts about inheritance and good practices but others do not like the following:

PyQt recommends not modifying the code generated by Qt Designer because you probably want to modify the GUI in the future and when using pyuic the initial code is overwritten. Another problem is that beginners do not understand that the class generated by Qt Designer is not a widget but an interface that serves to fill another widget, and consequently can not overwrite the methods of the widgets in addition to other problems.

You only have to modify the object of a class from the object of another class if both have the same scope, in your case when wanting to clean the QLineEdit of the main window from the other window is a dangerous task, instead you should do that logic where both windows have the same scope and that is in the openUserIDWin method.

QLineEdit already has the clear() method that allows to clean, it fulfills the same function as setText("") but the first method is more readable.

Considering the above, the solution is:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 611)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
        self.tabWidget.setObjectName("tabWidget")
        self.MainTab = QtWidgets.QWidget()
        self.MainTab.setObjectName("MainTab")
        self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
        self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
        self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
        self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
        self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
        self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
        self.label = QtWidgets.QLabel(self.MainTab)
        self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
        self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
        self.UserID_le.setObjectName("UserID_le")
        self.tabWidget.addTab(self.MainTab, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
        self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
        self.label.setText(_translate("MainWindow", "User ID"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))

class Ui_UserIDWin(object):
    def setupUi(self, UserIDWin):
        UserIDWin.setObjectName("UserIDWin")
        UserIDWin.resize(400, 124)
        self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
        self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
        self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
        self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
        self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
        self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
        self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
        self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
        self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
        self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
        self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
        self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
        self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")

        self.retranslateUi(UserIDWin)
        QtCore.QMetaObject.connectSlotsByName(UserIDWin)

    def retranslateUi(self, UserIDWin):
        _translate = QtCore.QCoreApplication.translate
        UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
        self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
        self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
        self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
        self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
        self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)

    def openUserIDWin(self):
        UserID_value = self.UserID_le.text()
        w = UserIDWin(UserID_value)
        w.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserID_le.clear)
        w.exec_()

class UserIDWin(QtWidgets.QDialog, Ui_UserIDWin):
    def __init__(self, userID, parent=None):
        super(UserIDWin, self).__init__(parent)
        self.setupUi(self)
        self.userID = userID
        self.UserIDWin_UserID_lnedt.setText(self.userID)
        self.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserIDWin_UserID_lnedt.clear)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

I recommend you read:

http://pyqt.sourceforge.net/Docs/PyQt5/designer.html

QtDesigner changes will be lost after redesign User Interface


问:
Xamarin Android Cannot Recieve Hands up Notifications (Banner Notifications)
I'm building the notification system on my app but problem is in Andorid Os particularly Huawei p20 lite i cannot get notification Banner on top of the screen

I have tried a lot of tutorials

(https://snag.gy/xy2ImQ.jpg) Picture
I want this to be true or activated

Xamarin:

```<code>    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        intent.PutExtra("SomeSpecialKey", "some special value");
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }

        var pendingIntent = PendingIntent.GetActivity(this,
                                                      MainActivity.NOTIFICATION_ID,
                                                      intent,
                                                      PendingIntentFlags.OneShot);

        var notificationBuilder = new  NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                  .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                                  .SetContentTitle(title)
                                  .SetContentText(messageBody)
                                  .SetPriority(5)
                                  .SetDefaults(1)
                                  .SetVibrate(new long[0])

                                  .SetContentIntent(pendingIntent);

       /*   NotificationChannel channel = new NotificationChannel(
                                MainActivity.CHANNEL_ID,
                               new Java.Lang.String("Channel"),
                                NotificationImportance.High
                            ); */

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());

    }
</code>```

Local Server :

```<code>{"to":"MYTOKEN","notification":{"title":"Working Good","body":"Okok" ,"sound": "default",
      "icon": "icon_desc"},"priority":"high",
}
</code>```

答:
I found my solution i created custom Channel

```<code>internal static readonly string CHANNEL_ID = "test";
</code>```

and i did set properties straight from JSON Payload file

```<code>{
   "to": "fOBdGjbftTI:APA91bEV1G39J3sF-CBQMANdlW7ely-XGC8zQ9Fp00H31iHFsmxB5hcgFCMr8-Plh9w4bDHO9eDQ5Fr_SCbYjNJ93iaFvh-zcUe_e1sAKHmRo5u73vGMuGovmfvUuTIuak1xcoRTrOtQ",
   "notification":{
     "title":"New Notification!",
     "body":"Test",
"android_channel_id":"test"
   },
   "priority":"High",

    "android": {
            "notification": {
                "sound": "default"
            }
        }
}
</code>```

Body:
I'm building the notification system on my app but problem is in Andorid Os particularly Huawei p20 lite i cannot get notification Banner on top of the screen

I have tried a lot of tutorials

(https://snag.gy/xy2ImQ.jpg) Picture
I want this to be true or activated

Xamarin:

    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        intent.PutExtra("SomeSpecialKey", "some special value");
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }

        var pendingIntent = PendingIntent.GetActivity(this,
                                                      MainActivity.NOTIFICATION_ID,
                                                      intent,
                                                      PendingIntentFlags.OneShot);

        var notificationBuilder = new  NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                  .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                                  .SetContentTitle(title)
                                  .SetContentText(messageBody)
                                  .SetPriority(5)
                                  .SetDefaults(1)
                                  .SetVibrate(new long[0])

                                  .SetContentIntent(pendingIntent);

       /*   NotificationChannel channel = new NotificationChannel(
                                MainActivity.CHANNEL_ID,
                               new Java.Lang.String("Channel"),
                                NotificationImportance.High
                            ); */

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());

    }

Local Server :

{"to":"MYTOKEN","notification":{"title":"Working Good","body":"Okok" ,"sound": "default",
      "icon": "icon_desc"},"priority":"high",
}

Body:
I found my solution i created custom Channel

internal static readonly string CHANNEL_ID = "test";

and i did set properties straight from JSON Payload file

{
   "to": "fOBdGjbftTI:APA91bEV1G39J3sF-CBQMANdlW7ely-XGC8zQ9Fp00H31iHFsmxB5hcgFCMr8-Plh9w4bDHO9eDQ5Fr_SCbYjNJ93iaFvh-zcUe_e1sAKHmRo5u73vGMuGovmfvUuTIuak1xcoRTrOtQ",
   "notification":{
     "title":"New Notification!",
     "body":"Test",
"android_channel_id":"test"
   },
   "priority":"High",

    "android": {
            "notification": {
                "sound": "default"
            }
        }
}


问:
Setup Ingress-Nginx rate limit rps for a specific path
I am using Kubernetes Kops. I want to set rate limit rps at Ingress-Nginx level for a specific path only.

I know about

```<code>nginx.ingress.kubernetes.io/limit-rps
</code>```

If I set this in Ingress rules then it will be applicable for all the routes. But, I want to apply it for a specific route. Let's say, when I am trying to access

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

I want to set rps limit to 100 for the path /login

```<code>nginx.ingress.kubernetes.io/limit-rps: 100
</code>```

This is my Ingress rules config,

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules
  namespace: staging
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /login
        backend:
          serviceName: login_site
          servicePort: 80
      - path: /registration
        backend:
          serviceName: registration_site
          servicePort: 80
</code>```

答:
It's possible to slightly abuse the config for ingress-nginx by adding multiple Ingress definitions for the same hostname. ingress-nginx will merge the rules/routes together. The config will become harder to manage though and you are getting towards the limits of what nginx proxying can do for you.

Other options

Traefik has a rate limit middleware that can be applied to routes.

Also look at something like kong or istio if you want to start managing individual services with more detail.

Nginx Ingress config

Creating a structure to your naming conventions will be important here so you know which Ingress houses which routes. Using the route path in the Ingress name is the where I would start but your use case may vary:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules-registration
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
    nginx.ingress.kubernetes.io/limit-rps: '10'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /registration
        backend:
          serviceName: registration-site
          servicePort: 80
</code>```

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules-login
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
    nginx.ingress.kubernetes.io/limit-rps: '100'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /login
        backend:
          serviceName: login-site
          servicePort: 80
</code>```

I'm not sure how host wide or server wide annotations (like nginx.ingress.kubernetes.io/ssl-ciphers) would need to be managed. If they all merge nicely then maybe create a special Ingress just to house those. If not you might end up managing host settings across all Ingress configs which will be a pain.

Body:
I am using Kubernetes Kops. I want to set rate limit rps at Ingress-Nginx level for a specific path only.

I know about

nginx.ingress.kubernetes.io/limit-rps

If I set this in Ingress rules then it will be applicable for all the routes. But, I want to apply it for a specific route. Let's say, when I am trying to access

/login

I want to set rps limit to 100 for the path /login

nginx.ingress.kubernetes.io/limit-rps: 100

This is my Ingress rules config,

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules
  namespace: staging
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /login
        backend:
          serviceName: login_site
          servicePort: 80
      - path: /registration
        backend:
          serviceName: registration_site
          servicePort: 80

Body:
It's possible to slightly abuse the config for ingress-nginx by adding multiple Ingress definitions for the same hostname. ingress-nginx will merge the rules/routes together. The config will become harder to manage though and you are getting towards the limits of what nginx proxying can do for you.

Other options

Traefik has a rate limit middleware that can be applied to routes.

Also look at something like kong or istio if you want to start managing individual services with more detail.

Nginx Ingress config

Creating a structure to your naming conventions will be important here so you know which Ingress houses which routes. Using the route path in the Ingress name is the where I would start but your use case may vary:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules-registration
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
    nginx.ingress.kubernetes.io/limit-rps: '10'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /registration
        backend:
          serviceName: registration-site
          servicePort: 80

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules-login
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
    nginx.ingress.kubernetes.io/limit-rps: '100'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /login
        backend:
          serviceName: login-site
          servicePort: 80

I'm not sure how host wide or server wide annotations (like nginx.ingress.kubernetes.io/ssl-ciphers) would need to be managed. If they all merge nicely then maybe create a special Ingress just to house those. If not you might end up managing host settings across all Ingress configs which will be a pain.


问:
Toggle DIV when Radio Buttons are checked
I am trying to make a DIV toggle visible and not visible when a group of radio buttons say yes or no.

For example I have a a list of stores in a DIV but I only want that list of stores visible when the radio button is checked as yes.

Edit Script View

```<code><div id="script_form_wrapper">
    <%= form_for(:script, :url => {:action => 'update', :id =>@script.id}) do |f| %>
        <div id="script_form_visibility">
            <div class="issue_section_header" align="center">Visibility</div>
            <div class="line-break"></div>
            <div class="standardText"><span class="boldText">All Stores:</span>
                <%=f.radio_button(:all_stores, true)%> Yes
                <%=f.radio_button(:all_stores, false)%> No
            </div>
            <br/>
            <div id="script_stores">
                <div class="issue_section_header" align="center">Stores</div>
                <div class="line-break"></div>
                <div class="standardText">
                    <%@stores.each do |store|%>
                        <%= check_box_tag 'script[store_ids][]', store.id, @script.store_ids.include?(store.id), :id => dom_id(store) %>
                        <%= label_tag dom_id(store), store.name, :class => "check_box_label" %><br/>
                    <%end%>
                </div>
            </div>
        </div>
        <div id="script_form">
            <div class="boldText"><%= f.label :name %></div>
            <div><%=f.text_field :name, :size => '94', :maxlength => '70'%></div>
            <div>
                <table width="100%" cellspacing="0">
                    <tr>
                        <td class="boldText"><%= f.label :category_id, "Category" %></td>
                        <td class="boldText" align="right">Show ID Required Field</td>
                    </tr>
                    <tr>
                        <td class="standardText"><%=f.select(:category_id, @categories.collect {|c| [c.name, c.id]}, :selected => session[:admin_category])%></td>
                        <td class="standardText" align="right"><%=f.radio_button(:require_id, true)%> Yes <%=f.radio_button(:require_id, false)%> No</td>
                    </tr>
                </table>
            </div>
            <div class="boldText"><%= f.label :task %></div>
            <div><%= f.text_area(:task, :size => "68x20") %></div>
            <div class="boldText"><%= f.label :expected_results, "Expected Results" %></div>
            <div><%= f.text_area(:expected_results, :size => "68x20") %></div>
            <div align="center"><%= f.submit "Update Script" %></div>
        </div>
    <% end %>
</div>
</code>```

Sad Attempt of Javascript

```<code><script type="text/javascript">
$(function() {
    $("[name=script[all_stores]]").click(function(){
            $('#script_stores').hide();
            $("#script_all_stores_"+$(this).val()).show('slow');
    });
 });
</script>
</code>```

Rendered HTML Source

```<code><div class="standardText"><span class="boldText">All Stores:</span>
                <input id="script_all_stores_true" name="script[all_stores]" type="radio" value="true" /> Yes
                <input checked="checked" id="script_all_stores_false" name="script[all_stores]" type="radio" value="false" /> No
            </div>
</code>```

Solution

```<code><script type="text/javascript">
$(function() {
    if($("#script_all_stores_false").is(":checked")){
       $('#script_stores').show();
         }else{
       $('#script_stores').hide();
         }
    $("input[name='script[all_stores]']").change(function(){
        if($("#script_all_stores_false").is(":checked")){
           $('#script_stores').show();
             }else{
           $('#script_stores').hide();
             }
    });
});
</script>
</code>```

Thank you for you help!!!

答:
Try this:</p>

```<code>  $("[name='script[all_stores]']").change(function(){
     if($(this).val()=="true"){
       $('#script_stores').show();
     }else {
       $('#script_stores').hide();
     }

  });
</code>```

Body:
I am trying to make a DIV toggle visible and not visible when a group of radio buttons say yes or no.

For example I have a a list of stores in a DIV but I only want that list of stores visible when the radio button is checked as yes.

Edit Script View

    <%= form_for(:script, :url => {:action => 'update', :id =>@script.id}) do |f| %>

Visibility

All Stores:
                <%=f.radio_button(:all_stores, true)%> Yes
                <%=f.radio_button(:all_stores, false)%> No

Stores

                    <%@stores.each do |store|%>
                        <%= check_box_tag 'script[store_ids][]', store.id, @script.store_ids.include?(store.id), :id => dom_id(store) %>
                        <%= label_tag dom_id(store), store.name, :class => "check_box_label" %>

                    <%end%>

<%= f.label :name %>

<%=f.text_field :name, :size => '94', :maxlength => '70'%>

                        <%= f.label :category_id, "Category" %>
                        Show ID Required Field

                        <%=f.select(:category_id, @categories.collect {|c| [c.name, c.id]}, :selected => session[:admin_category])%>
                        <%=f.radio_button(:require_id, true)%> Yes <%=f.radio_button(:require_id, false)%> No

<%= f.label :task %>

<%= f.text_area(:task, :size => "68x20") %>

<%= f.label :expected_results, "Expected Results" %>

<%= f.text_area(:expected_results, :size => "68x20") %>

<%= f.submit "Update Script" %>

    <% end %>

Sad Attempt of Javascript

Rendered HTML Source

All Stores:
                <input id="script_all_stores_true" name="script[all_stores]" type="radio" value="true" /> Yes
                <input checked="checked" id="script_all_stores_false" name="script[all_stores]" type="radio" value="false" /> No

Solution

Thank you for you help!!!

Body:
Try this:

  $("[name='script[all_stores]']").change(function(){
     if($(this).val()=="true"){
       $('#script_stores').show();
     }else {
       $('#script_stores').hide();
     }

  });