问:
Submit form after unbinding
```<code>$("#qwerq").submit(function (e){
    e.preventDefault();
    var check=0;

    if($("#firstName").val() == "") {
        check=1;
    }

    if(check!=1){
        $("#qwerq").unbind("submit") ;
        $("#qwerq").submit();
        //$("#qwerq").trigger('submit', [true]);
    }
});
</code>```

When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.

I have tried using .submit() and .trigger("submit").  I have to manually click on submit again.

What should I add so that I don't have to click again?

答:
I think you were trying to submit a form on a button click.
Then you need to make some changes in your code:

Provide an id to your form and change button type="button" (instead of "submit"):

```<code><form id="form_1" action="yourserverpagename.php" method="post">
   <input id="firstName" type="text" value="" />
   <input id="qwerq" type="button" value="Send" />
</form>
</code>```

Now your script should like below:

```<code>    <script>
            $("#qwerq").click(function (e) {
                e.preventDefault();

                var check = 0;

                if ($("#firstName").val() == "") {
                    check = 1;
                }

                if (check != 1) {
                    //-- here is the way to submit the form using form id --
                    $('#form_1').submit();
                }

            });
    </script>
</code>```

Title: Submit form after unbinding

Body:
$("#qwerq").submit(function (e){
    e.preventDefault();
    var check=0;

    if($("#firstName").val() == "") {
        check=1;
    }

    if(check!=1){
        $("#qwerq").unbind("submit") ;
        $("#qwerq").submit();
        //$("#qwerq").trigger('submit', [true]);
    }
});

When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.

I have tried using .submit() and .trigger("submit").  I have to manually click on submit again.

What should I add so that I don't have to click again?

Body:
I think you were trying to submit a form on a button click.
Then you need to make some changes in your code:

Provide an id to your form and change button type="button" (instead of "submit"):

<form id="form_1" action="yourserverpagename.php" method="post">
   <input id="firstName" type="text" value="" />
   <input id="qwerq" type="button" value="Send" />
</form>

Now your script should like below:

    <script>
            $("#qwerq").click(function (e) {
                e.preventDefault();

                var check = 0;

                if ($("#firstName").val() == "") {
                    check = 1;
                }

                if (check != 1) {
                    //-- here is the way to submit the form using form id --
                    $('#form_1').submit();
                }

            });
    </script>


来源: stackexchange

问:
Javascript convert image to File return zeros
I have img from other server

```<code><img src="https://cloudserver/1.jpg">
</code>```

On click this img i want convert to File object for send post request to server.
After this function i see that data all bytes = 0, dont understand what happing ? In search i find problem about that need wait then image is loading done but i 100% have already loaded image.

```<code>imgToFile: function (imageElement){
    imageElement.crossOrigin="anonymous";

    var canvasElement = document.createElement("canvas");
    canvasElement.width = imageElement.width;
    canvasElement.height = imageElement.height;
    var canvasContext = canvasElement.getContext("2d");
    canvasContext.drawImage(imageElement, 0, 0);

    var imageData = canvasContext.getImageData(0, 0, imageElement.width, imageElement.height).data;
    var buffer = new Uint8Array(imageData.length);
    for(var index = 0; index < imageData.length; index++)
        buffer[index] = imageData[index];

    var imageBlob = new Blob(buffer);
    return new File([imageBlob], /\/([^/]+)$/.exec(imageElement.src)[1]);
}
</code>```

Sandbox:
https://liveweave.com/DCXuNY

答:
That's quite surprising to me who thought I knew this part of the specs, but turns out that since 2016, changing the crossorigin attribute state is part of the
img's relevant mutations, which will force a refetching of the image source.

Chrome only caught up with the specs relatively recently (M84), Firefox still hasn't and will thus just throw an Error complaining about the fact the image did taint the canvas.

Chrome on the other hand will thus refetch the image as soon as you change that crossOrigin IDL attribute, this time with the proper CORS headers. So at the time you hit drawImage in that browser, it still won't have fetched the CORS compliant resource (even though it's the same file, because it's served with different headers, browsers will fetch it entirely again).

So contrarily to what you thought, your image is still not loaded in Chrome.

To fix that, you could add an onload event handler in your js script, but you'd also need to force the refetching of the image for other browsers by setting again the src attribute (even to the same value):

onload = (evt) => {
  const img = document.querySelector( 'img' );
  img.onload = (evt) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img,0,0);
    console.log(...ctx.getImageData(250,120,1,1).data);
  };
  img.crossOrigin = 'anonymous';
  img.src = img.src; // force refetching for non-Chrome browsers
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img { width: 300px }</code>```

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

<p>But the best is certainly to request your image directly with the proper CORS headers, from the beginning, so you don't make your users download two times the same file for nothing.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>onload = (evt) => {
  const img = document.querySelector( 'img' );
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img,0,0);
  console.log(...ctx.getImageData(250,120,1,1).data);
};</code>```

img { width: 300px }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" crossorigin="anonymous"></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have img from other server

On click this img i want convert to File object for send post request to server.
After this function i see that data all bytes = 0, dont understand what happing ? In search i find problem about that need wait then image is loading done but i 100% have already loaded image.

imgToFile: function (imageElement){
    imageElement.crossOrigin="anonymous";

    var canvasElement = document.createElement("canvas");
    canvasElement.width = imageElement.width;
    canvasElement.height = imageElement.height;
    var canvasContext = canvasElement.getContext("2d");
    canvasContext.drawImage(imageElement, 0, 0);

    var imageData = canvasContext.getImageData(0, 0, imageElement.width, imageElement.height).data;
    var buffer = new Uint8Array(imageData.length);
    for(var index = 0; index < imageData.length; index++)
        buffer[index] = imageData[index];

    var imageBlob = new Blob(buffer);
    return new File([imageBlob], /\/([^/]+)$/.exec(imageElement.src)[1]);
}

Sandbox:
https://liveweave.com/DCXuNY

Body:
That's quite surprising to me who thought I knew this part of the specs, but turns out that since 2016, changing the crossorigin attribute state is part of the
img's relevant mutations, which will force a refetching of the image source.

Chrome only caught up with the specs relatively recently (M84), Firefox still hasn't and will thus just throw an Error complaining about the fact the image did taint the canvas.

Chrome on the other hand will thus refetch the image as soon as you change that crossOrigin IDL attribute, this time with the proper CORS headers. So at the time you hit drawImage in that browser, it still won't have fetched the CORS compliant resource (even though it's the same file, because it's served with different headers, browsers will fetch it entirely again).

So contrarily to what you thought, your image is still not loaded in Chrome.

To fix that, you could add an onload event handler in your js script, but you'd also need to force the refetching of the image for other browsers by setting again the src attribute (even to the same value):

onload = (evt) => {
  const img = document.querySelector( 'img' );
  img.onload = (evt) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img,0,0);
    console.log(...ctx.getImageData(250,120,1,1).data);
  };
  img.crossOrigin = 'anonymous';
  img.src = img.src; // force refetching for non-Chrome browsers
};

img { width: 300px }

<img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png">

But the best is certainly to request your image directly with the proper CORS headers, from the beginning, so you don't make your users download two times the same file for nothing.

onload = (evt) => {
  const img = document.querySelector( 'img' );
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img,0,0);
  console.log(...ctx.getImageData(250,120,1,1).data);
};

img { width: 300px }

<img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" crossorigin="anonymous">


问:
Extra output outputted
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story">
  <p class="story"></p>
</div></code>```

答:
You can use the below:

```<code>window.onload= function(){
    let usr = ["a", "b", "c"];

    for (let i = 0; i < 3; i++) {
      var story = document.createElement('p');
      story.classList.add('story');
      story.innerText= usr[i];
      document.getElementById("story").appendChild(story);
    }
  }
</code>```

Also Update this as

```<code><div id="story">
</div>
</code>```

Title: Extra output outputted

Body:
You can use the below:

window.onload= function(){
    let usr = ["a", "b", "c"];

    for (let i = 0; i < 3; i++) {
      var story = document.createElement('p');
      story.classList.add('story');
      story.innerText= usr[i];
      document.getElementById("story").appendChild(story);
    }
  }

Also Update this as

<div id="story">
</div>


问:
Can any one help me with this one . I was trying to write a prog for finding 'LCM'. I want to equate these variable
Here c and d basically represent tables of respective number for variable a and b...i am trying to match the least common product from these table.Please help me figure it out</p>

```<code>a=(input('your first no: '))
b=(input('your second no: '))

for i in range(1,100):
    c=a*i
    d=b*i
    if (c==d):
    print('lcm is')
</code>```

答:
Here is a program that will work.  It will also calculate the LCM of more than two numbers.

```<code>from collections import Counter
from operator import mul
from functools import reduce

def primeFactors(n):
    if not isinstance(n, int) or n < 1:
        raise ValueError("must be positive integer")
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n /= 2
    i = 3
    while n != 1:
        while n % i == 0:
            factors.append(i)
            n /= i
        i += 2
    return factors

def get_lcm(numbers):
    factorisations = [Counter(primeFactors(n)) for n in numbers]
    primes = frozenset().union(*(set(x.keys()) for x in factorisations))
    primes_to_max_powers = (p ** max(*(x.get(p,0) for x in factorisations))
                            for p in primes)
    return reduce(mul, primes_to_max_powers, 1)

a = int(input('your first no: '))
b = int(input('your second no: '))

print('lcm is', get_lcm([a, b]))
</code>```

Or you can do this instead but it might be a bit slower:

```<code>a = input('your first no: ')
b = input('your second no: ')
for i in range(max(a, b), a * b + 1):
    if i % a == 0 and i % b == 0:
        lcm = i
        break
print('lcm is ', lcm)
</code>```

Body:
Here c and d basically represent tables of respective number for variable a and b...i am trying to match the least common product from these table.Please help me figure it out

a=(input('your first no: '))
b=(input('your second no: '))

for i in range(1,100):
    c=a*i
    d=b*i
    if (c==d):
    print('lcm is')

Body:
Here is a program that will work.  It will also calculate the LCM of more than two numbers.

from collections import Counter
from operator import mul
from functools import reduce

def primeFactors(n):
    if not isinstance(n, int) or n < 1:
        raise ValueError("must be positive integer")
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n /= 2
    i = 3
    while n != 1:
        while n % i == 0:
            factors.append(i)
            n /= i
        i += 2
    return factors

def get_lcm(numbers):
    factorisations = [Counter(primeFactors(n)) for n in numbers]
    primes = frozenset().union(*(set(x.keys()) for x in factorisations))
    primes_to_max_powers = (p ** max(*(x.get(p,0) for x in factorisations))
                            for p in primes)
    return reduce(mul, primes_to_max_powers, 1)

a = int(input('your first no: '))
b = int(input('your second no: '))

print('lcm is', get_lcm([a, b]))

Or you can do this instead but it might be a bit slower:

a = input('your first no: ')
b = input('your second no: ')
for i in range(max(a, b), a * b + 1):
    if i % a == 0 and i % b == 0:
        lcm = i
        break
print('lcm is ', lcm)


问:
Emit signal to update UI from thread
I have defined a new slot in a class that inherits from QThread:

```<code>class MyThread : public QThread
{
    Q_OBJECT

public:
    MyThread(QString fileName);
    void run() override;

signals:
    void addNewItem(int row, int col, QString text);

private:
    QString fileName;
};
</code>```

In the Dialog class I have defined slot that should get called when the above signal will be emitted. This slot updates widget on UI:

```<code>void Dialog::onAddNewItem(int row, int col, QString text)
{
    ui->tableWidget->setItem(row, col, new QTableWidgetItem(text));
}
</code>```

In the constructor of the Dialog class I have created the working thread and connected signal to a slot:

```<code>worker = new MyThread(filePath);
worker->run();

connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);
</code>```

In the run() function I'm emitting the addNewItem signal but the onAddNewItem slot never gets called. Why is that?

答:
You have connected signals and slots after the thread runs.

Replace worker->run() with worker->start(). The start member immediately calls run once the thread starts successfully.

Connect signals and slots as follows:

```<code>worker = new MyThread(filePath);
connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);
worker->start();
</code>```

Title: Emit signal to update UI from thread

Body:
I have defined a new slot in a class that inherits from QThread:

class MyThread : public QThread
{
    Q_OBJECT

public:
    MyThread(QString fileName);
    void run() override;

signals:
    void addNewItem(int row, int col, QString text);

private:
    QString fileName;
};

In the Dialog class I have defined slot that should get called when the above signal will be emitted. This slot updates widget on UI:

void Dialog::onAddNewItem(int row, int col, QString text)
{
    ui->tableWidget->setItem(row, col, new QTableWidgetItem(text));
}

In the constructor of the Dialog class I have created the working thread and connected signal to a slot:

worker = new MyThread(filePath);
worker->run();

connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);

In the run() function I'm emitting the addNewItem signal but the onAddNewItem slot never gets called. Why is that?

Body:
You have connected signals and slots after the thread runs.

Replace worker->run() with worker->start(). The start member immediately calls run once the thread starts successfully.

Connect signals and slots as follows:

worker = new MyThread(filePath);
connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);
worker->start();


问:
Can I check if a list contains any item from another list?
using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

```<code>list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")
</code>```

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

答:
```<code>list1.extend(list2)
if len(set(list1)) != len(list1) + len(list2):
    print("Duplicates Found")
else:
    print("Duplicates Not Found")
</code>```

Time Analysis

```<code>>>>def fun():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]
       if len(set(list1.extend(list2)) != len(list1) + len(list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%timeit fun()
>>>3.59 µs ± 213 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>>def fun1():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]

       if any(x in list1 for x in list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%%timeit fun1():
>>>3.93 µs ± 696 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Conclusion

Both methods take nearly equal time but 'set + extend' method take slight less time to execute.

Body:
using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

Body:
list1.extend(list2)
if len(set(list1)) != len(list1) + len(list2):
    print("Duplicates Found")
else:
    print("Duplicates Not Found")

Time Analysis

>>>def fun():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]
       if len(set(list1.extend(list2)) != len(list1) + len(list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%timeit fun()
>>>3.59 µs ± 213 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>>def fun1():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]

       if any(x in list1 for x in list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%%timeit fun1():
>>>3.93 µs ± 696 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Conclusion

Both methods take nearly equal time but 'set + extend' method take slight less time to execute.


问:
Django reset password doesn't load correct templates
I have 4 custom templates but two of them are loading the default templates and I don't know why. This is my url paths:

```<code>#works fine
path('reset_password/',
     auth_views.PasswordResetView.as_view(template_name="myapp/password_reset.html"),
     name="reset_password"),

#doesn't work
path('reset_password_sent/',
      auth_views.PasswordResetDoneView.as_view(template_name="myapp/password_reset_sent.html"),
      name="password_reset_done"),

#works fine
path('reset/<uidb64>/<token>/',
     auth_views.PasswordResetConfirmView.as_view(template_name="myapp/password_reset_form.html"),
     name="password_reset_confirm"),

#doesn't work
path('reset_password_complete/',
     auth_views.PasswordResetCompleteView.as_view(template_name="myapp/password_reset_done.html"),
     name="password_reset_complete"),
</code>```

However, if I write the URL directly in the browser they load correctly.

Any ideas? Thanks!

答: The problem is that Django does not use a namespace when reversing the password reset urls.py. You must be removing 'app_name' from your urls.py.</p>

Body:
I have 4 custom templates but two of them are loading the default templates and I don't know why. This is my url paths:

#works fine
path('reset_password/',
     auth_views.PasswordResetView.as_view(template_name="myapp/password_reset.html"),
     name="reset_password"),

#doesn't work
path('reset_password_sent/',
      auth_views.PasswordResetDoneView.as_view(template_name="myapp/password_reset_sent.html"),
      name="password_reset_done"),

#works fine
path('reset/<uidb64>/<token>/',
     auth_views.PasswordResetConfirmView.as_view(template_name="myapp/password_reset_form.html"),
     name="password_reset_confirm"),

#doesn't work
path('reset_password_complete/',
     auth_views.PasswordResetCompleteView.as_view(template_name="myapp/password_reset_done.html"),
     name="password_reset_complete"),

However, if I write the URL directly in the browser they load correctly.

Any ideas? Thanks!


问:
What is regular expression for "Test123"
I tried - "Test\d\d\d" and it works but problem is, String in expression could contain any number of digits so it could be "Test1" or "Test12" or "Test123". Hence it could be in range [000] to [999]</p>

答:
```<code>Test[0-9]{1,3}
</code>```

should do what you need. [0-9] defines a range including numbers (you could use \d as well), and the {1,3} syntax defines that the preceding pattern should happen at least once, but no more than three times.

RegExr Demo

ContentLicense: CC BY-SA 3.0

Body:
Test[0-9]{1,3}

should do what you need. [0-9] defines a range including numbers (you could use \d as well), and the {1,3} syntax defines that the preceding pattern should happen at least once, but no more than three times.

RegExr Demo


答:
It is normal because you have three clones and original, so as final step you should remove original

window.onload= function(){
    var main_story=document.getElementById("story");
    var story = document.getElementsByClassName('story')[0];
    let usr = ["a", "b", "c"];
    for (let i = 0; i < 3; i++) {
      let clone = story.cloneNode(true);
      clone.innerHTML = usr[i];
      main_story.appendChild(clone);
    }
    story.remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story">
    <p class="story"></p>
</div></code>```

Title: Extra output outputted

Body:
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}

Body:
It is normal because you have three clones and original, so as final step you should remove original

window.onload= function(){
    var main_story=document.getElementById("story");
    var story = document.getElementsByClassName('story')[0];
    let usr = ["a", "b", "c"];
    for (let i = 0; i < 3; i++) {
      let clone = story.cloneNode(true);
      clone.innerHTML = usr[i];
      main_story.appendChild(clone);
    }
    story.remove();
}

<div id="story">
    <p class="story"></p>
</div>


问:
Server Side Render Dynamic Page based on Route Param
I'm starting with Next.js and after going through docs, I cannot figure out how to get the route param code inside getStaticPaths method as shown below!?. code is not known before hand by any means and it can be anything.

I don't want to call api and get the data using useEffect inside the component.

File: pages/post/[code].js

```<code>import React from 'react';
import apiCall from 'api/something';

export default ({post}) => {
     return <>
        render components here based on prop `post`
    </>
}

export async function getStaticPaths() {
    // How to get [code] from the route here, which can be used below?
    return {
        paths: // NEED [code] HERE from current route,
        fallback: false
    }
}

export async function getStaticProps(ctx) {
    return {
        props: {
         // [ctx.code] resolved from current route with the help of getStaticPaths,
         post: apiCall(ctx.code)
        }
    }
}
</code>```

I've tried getServerSideProps which works for me:

```<code>export const getServerSideProps = async (ctx) => {
    return {
        props: {
            post: await apiCall(ctx.query.code)
        }
    };
};
</code>```

But it fails when I do next export stating:

pages with getServerSideProps can not be exported. See more info here: https://err.sh/next.js/gssp-export

After investigating further on this error I found this solution, which is not feasible for me as my app is hosted on Heroku.

I'm trying to server-side render the html along with the data based on the route param code. But not able to do so now.

答:
The purpose of the function getStaticPaths is to generate a list of paths for which static HTML will be rendered at build time. For example, for a list of 10 posts, you can generate 10 posts/[id] routes ahead of time if you know the id of the posts.

How getStaticPaths works with dynamic routes in more details..

Suppose you have a dynamic route /posts/[postId] if you choose to use static-generation you have to generate a list of paths that will include the postId as a route param and for each path returned, the function getStaticProps will be called to query the data at build time. Example,

// for /post/[postId]

export const getStaticPaths = async () => {
  // if you know all the postId ahead of time

  const paths = [
     { params: { postId: '1234' } },  // keep in mind postId has to be a string
     { params: { postId: '3792' } },
     { params: { postId: '1749' } },
  ]

  return {
    paths,
    fallback: false // we are disabling fallback because we know all the paths ahead of time
  }
}

// for each path returned getStaticProps will be called at build time
export const getStaticProps = async (context) => {
   // you have access to the postId params that you returns from
   // getStaticPaths here
   const postId = context.params.postId

   // now you can query the data from postId and return as props

   return {
     props: // queried data
   }
}
```

<p>If <code>fallback</code> is set to <code>false</code> any for any route path that is not returned from the function <code>getStaticPaths</code> nextjs will simply show a <code>404</code> error page.</p>

<p><strong>How to use <code>fallback: true</code> to generate static pages for route params not known ahead of time</strong></p>

<p>If you know some <code>postId</code> of the posts and the data for the <code>posts</code> do not change very often, you can choose to generate the pages with <code>fallback</code> property set to <code>true</code>, which will display a fallback version of the page for the paths that are not returned from the function <code>getStaticPaths</code>. And on request for the page nextjs will call <code>getStaticProps</code> and send the data as JSON which will be used to render the page in the browser.
Example,</p>

```// for /post/[postId]
export const getStaticPaths = async () => {
   // you can get how many ever postIds are know ahead of time
   // and return as paths with fallback set to true
   const posts = // queried data from db or fetched from remote API

   const paths = posts.map(post => { params:{ postId: post.id.toString() }})

   return {
      paths,
      fallback: true
   }

}

// in your page Component check for fallback and render a loading indicator
import { useRouter } from 'next/router';

const MyPage = (props) => {
  // before you do anything
  const router = useRouter();

  if (router.isFallback) {
    return
Loading....

  }

  // rest of your page logic

}
```

<p>If your data is very dynamic, let's say changing every 30mins or an hour or so. You can choose to use server-side rendering which will <code>fetch</code> the data on per request basis, but TTFB(time to first byte) will be higher. For example,</p>

```// for /post/[postId]
export const getServerSideProps = async (context) => {

  // you also have access to the param postId from the context
  const postId = context.params.postId

  // query the data based on the postId and return as props
  return {
    props: // queried data
  }

}
```

Keep in mind if you choose to go with getServerSideProps the function will be called on per-request basis so time to first byte will be higher.

Depending on use-cases you can also use static generation with client-side data fetching using swr from nextjs team repo link.

Body:
I'm starting with Next.js and after going through docs, I cannot figure out how to get the route param code inside getStaticPaths method as shown below!?. code is not known before hand by any means and it can be anything.

I don't want to call api and get the data using useEffect inside the component.

File: pages/post/[code].js

import React from 'react';
import apiCall from 'api/something';

export default ({post}) => {
     return <>
        render components here based on prop `post`
    </>
}

export async function getStaticPaths() {
    // How to get [code] from the route here, which can be used below?
    return {
        paths: // NEED [code] HERE from current route,
        fallback: false
    }
}

export async function getStaticProps(ctx) {
    return {
        props: {
         // [ctx.code] resolved from current route with the help of getStaticPaths,
         post: apiCall(ctx.code)
        }
    }
}

I've tried getServerSideProps which works for me:

export const getServerSideProps = async (ctx) => {
    return {
        props: {
            post: await apiCall(ctx.query.code)
        }
    };
};

But it fails when I do next export stating:

pages with getServerSideProps can not be exported. See more info here: https://err.sh/next.js/gssp-export

After investigating further on this error I found this solution, which is not feasible for me as my app is hosted on Heroku.

I'm trying to server-side render the html along with the data based on the route param code. But not able to do so now.

Body:
The purpose of the function getStaticPaths is to generate a list of paths for which static HTML will be rendered at build time. For example, for a list of 10 posts, you can generate 10 posts/[id] routes ahead of time if you know the id of the posts.

How getStaticPaths works with dynamic routes in more details..

Suppose you have a dynamic route /posts/[postId] if you choose to use static-generation you have to generate a list of paths that will include the postId as a route param and for each path returned, the function getStaticProps will be called to query the data at build time. Example,

// for /post/[postId]

export const getStaticPaths = async () => {
  // if you know all the postId ahead of time

  const paths = [
     { params: { postId: '1234' } },  // keep in mind postId has to be a string
     { params: { postId: '3792' } },
     { params: { postId: '1749' } },
  ]

  return {
    paths,
    fallback: false // we are disabling fallback because we know all the paths ahead of time
  }
}

// for each path returned getStaticProps will be called at build time
export const getStaticProps = async (context) => {
   // you have access to the postId params that you returns from
   // getStaticPaths here
   const postId = context.params.postId

   // now you can query the data from postId and return as props

   return {
     props: // queried data
   }
}

If fallback is set to false any for any route path that is not returned from the function getStaticPaths nextjs will simply show a 404 error page.

How to use fallback: true to generate static pages for route params not known ahead of time

If you know some postId of the posts and the data for the posts do not change very often, you can choose to generate the pages with fallback property set to true, which will display a fallback version of the page for the paths that are not returned from the function getStaticPaths. And on request for the page nextjs will call getStaticProps and send the data as JSON which will be used to render the page in the browser.
Example,

// for /post/[postId]
export const getStaticPaths = async () => {
   // you can get how many ever postIds are know ahead of time
   // and return as paths with fallback set to true
   const posts = // queried data from db or fetched from remote API

   const paths = posts.map(post => { params:{ postId: post.id.toString() }})

   return {
      paths,
      fallback: true
   }

}

// in your page Component check for fallback and render a loading indicator
import { useRouter } from 'next/router';

const MyPage = (props) => {
  // before you do anything
  const router = useRouter();

  if (router.isFallback) {
    return <div>Loading....</div>
  }

  // rest of your page logic

}

If your data is very dynamic, let's say changing every 30mins or an hour or so. You can choose to use server-side rendering which will fetch the data on per request basis, but TTFB(time to first byte) will be higher. For example,

// for /post/[postId]
export const getServerSideProps = async (context) => {

  // you also have access to the param postId from the context
  const postId = context.params.postId

  // query the data based on the postId and return as props
  return {
    props: // queried data
  }

}

Keep in mind if you choose to go with getServerSideProps the function will be called on per-request basis so time to first byte will be higher.

Depending on use-cases you can also use static generation with client-side data fetching using swr from nextjs team repo link.


问:
Implementing Component system from Unity in c++
I've been experimenting with making a component based system similar to Unity's, but in C++. I'm wondering how the GetComponent() method that Unity implements works. It is a very powerful function. Specifically, I want to know what kind of container it uses to store its components.

The two criteria I need in my clone of this function are as follows. 1. I need any inherited components to be returned as well. For example, if SphereCollider inherits Collider, GetComponent<Collider>() will return the SphereCollider attached to the GameObject, but GetComponent<SphereCollider>() will not return any Collider attached. 2. I need the function to be fast. Preferably, it would use some kind of hash function.

For criteria one, I know that I could use something similar to the following implementation

```<code>std::vector<Component*> components
template <typename T>
T* GetComponent()
{
    for each (Component* c in components)
        if (dynamic_cast<T>(*c))
            return (T*)c;
    return nullptr;
}
</code>```

But that doesn't fit the second criteria of being fast. For that, I know I could do something like this.

```<code>std::unordered_map<type_index, Component*> components
template <typename T>
T* GetComponent()
{
    return (T*)components[typeid(T)];
}
</code>```

But again, that doesn't fit the first criteria.

If anybody knows of some way to combine those two features, even if it's a little slower than the second example, I would be willing to sacrifice a little bit. Thank you!

答:
The Unity engine is linked with a forked mono runtime, on which unity scripts are executed.

In UnityEngine.Component

```<code>public class Component : Object
  {
    .
    .
    [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
    public Component GetComponent(Type type)
    {
        return this.gameObject.GetComponent(type);
    }

    [GeneratedByOldBindingsGenerator]
    [MethodImpl(MethodImplOptions.InternalCall)]
    internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue);

    [SecuritySafeCritical]
    public unsafe T GetComponent<T>()
    {
        CastHelper<T> castHelper = default(CastHelper<T>);
        this.GetComponentFastPath(typeof(T), new IntPtr((void*)(&castHelper.onePointerFurtherThanT)));
        return castHelper.t;
    }
    .
    .
}
</code>```

The C# code performs native calls, called Icalls to C++ methods that have been bound to the C# methods using the C# runtime library API. Bodyless (unimplemented) methods need either an extern, abstract or partial specifier as a rule so all internal calls are marked as extern. When the runtime sees a method with the [MethodImpl(MethodImplOptions.InternalCall)] attribute it knows it needs to make an Icall, so it looks up the function it has been bound to and jumps to that address.

An Icall does not need to be static in C# and automatically passes the this MonoObject of the component to the C++ handler function. If they are static then the this object is usually deliberately passed as a parameter using a C# shim method and making the shim method the static Icall. Using Icalls, types are not marshalled unless they are blittable types, meaning all other types are passed as MonoObject, MonoString etc.

Typically the C++ methods are functions or static methods but I think they can be non static methods as well, so long as they aren't virtual, because the address cannot be fixed by the runtime.

in UnityEngine.GameObject

```<code>public sealed class GameObject : Object
 {
    .
    .
    public GameObject(string name)
    {
      GameObject.Internal_CreateGameObject(this, name);
    }

    public GameObject()
    {
      GameObject.Internal_CreateGameObject(this, (string) null);
    }

    [WrapperlessIcall]
    [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public extern Component GetComponent(System.Type type);

    [WrapperlessIcall]
    [MethodImpl(MethodImplOptions.InternalCall)]
    private static extern void Internal_CreateGameObject([Writable] GameObject mono, string name);
    .
    .
 }
</code>```

The C# constructor for the GameObject contains a call to a native method. The body of the constructor is run after initialisation of the C# object such that there is already a this pointer. Internal_CreateGameObject is the static shim function that is actually called.

Someone's example implementation of their own C++ Internal_CreateGameObject using mono:

```<code>bool GameObjectBinding::init()
{
    MonoClass *gameObjectClass = Mono::get().getClass("GameObject");
    gameObject_NativeID_Field = mono_class_get_field_from_name(gameObjectClass, "nativeID");

    MonoClass *transformClass = Mono::get().getClass("Transform");
    transform_NativeID_Field = mono_class_get_field_from_name(transformClass, "nativeID");

    mono_add_internal_call("GameEngine_CS.GameObject::internal_createGameObject", GameObjectBinding::createGameObject);
    mono_add_internal_call("GameEngine_CS.GameObject::internal_deleteGameObject", GameObjectBinding::deleteGameObject);
    mono_add_internal_call("GameEngine_CS.GameObject::internal_getGameObject", GameObjectBinding::getGameObject);

    mono_add_internal_call("GameEngine_CS.GameObject::internal_getTransform", GameObjectBinding::getTransform);

    return true;
}

void GameObjectBinding::createGameObject(MonoObject * monoGameObject)
{
    Object *newObject = LevelManager::get().getCurrentLevel()->createObject(0);
    mono_field_set_value(monoGameObject, gameObject_NativeID_Field, (void*)newObject->getID());
}
</code>```

mono_add_internal_call has been used to bind this method to GameObjectBinding::createGameObject, to which the this pointer is passed as a MonoObject pointer. A native object is then created to represent the GameObject, and mono_field_set_value is then used to set the NativeID field of the C# object to the ID of the new native object. This way the native object can be accessed from the MonoObject which is the internal implementation of the C# object. The GameObject is represented by 2 objects essentially.

```<code>public sealed class GameObject : Object
 {
     .
     .
     private UInt32 nativeID;
     public UInt32 id { get { return nativeID; } }
     .
     .
 }
</code>```

This field is bound in the runtime using

```<code>mono_set_dirs( "/Library/Frameworks/Mono.framework/Home/lib", "/Library/Frameworks/Mono.framework/Home/etc" );
mono_config_parse( nullptr );
const char* managedbinarypath = "C:/Test.dll";
MonoDomain* domain = mono_jit_init(managedbinarypath)
MonoAssembly* assembly = mono_domain_assembly_open (domain, managedbinarypath);
MonoImage* image = mono_assembly_get_image (assembly);
MonoClass* gameobjectclass = mono_class_from_name(image, "ManagedLibrary", "GameObject");
gameObject_NativeID_Field = mono_class_get_field_from_name( gameobjectclass, "nativeID" );
</code>```

GetComponent<T>() passes typeof(T) to GetComponentFastPath (the native call) which passes the this pointer of the component as well. The native implementation of GetComponentFastPath will receive this as a MonoObject* and a MonoReflectionType* for the type. The bound C++ method will then call mono_reflection_type_get_type() on the MonoReflectionType* to get the MonoType* (here are the primitive types: https://github.com/samneirinck/cemono/blob/master/src/native/inc/mono/mono/metadata/blob.h), or for object types you can get the MonoClass* from MonoType* using mono_class_from_mono_type(). It will then get the game object that is attached to the Component and search the components that the object has in some internal data structure.

Someone's example implementation of their own C++ GetComponent using mono:

```<code>id ModuleScriptImporter::RegisterAPI()
{
    //GAMEOBJECT
    mono_add_internal_call("TheEngine.TheGameObject::CreateNewGameObject", (const void*)CreateGameObject);
    mono_add_internal_call("TheEngine.TheGameObject::AddComponent", (const void*)AddComponent);
    mono_add_internal_call("TheEngine.TheGameObject::GetComponent", (const void*)GetComponent);
}

MonoObject* ModuleScriptImporter::GetComponent(MonoObject * object, MonoReflectionType * type)
{
    return current_script->GetComponent(object, type);
}

MonoObject* CSharpScript::GetComponent(MonoObject* object, MonoReflectionType* type)
{
    if (!CheckMonoObject(object))
    {
        return nullptr;
    }

    if (currentGameObject == nullptr)
    {
        return nullptr;
    }

    MonoType* t = mono_reflection_type_get_type(type);
    std::string name = mono_type_get_name(t);

    const char* comp_name = "";

    if (name == "CulverinEditor.Transform")
    {
        comp_name = "Transform";
    }

    MonoClass* classT = mono_class_from_name(App->importer->iScript->GetCulverinImage(), "CulverinEditor", comp_name);
    if (classT)
    {
        MonoObject* new_object = mono_object_new(CSdomain, classT);
        if (new_object)
        {
            return new_object;
        }
    }
    return nullptr;
}
</code>```

C# methods can be invoked from C++:

```<code>MonoMethodDesc* desc = mono_method_desc_new (const char *name, gboolean include_namespace);
MonoClass* class = mono_class_from_name (MonoImage *image, const char* name_space, const char *name);
MonoMethod* method = mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass);
MonoMethod* method = mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image);
MonoObject* obj = mono_runtime_invoke (MonoMethod *method, void *obj, void **params,
                       MonoObject **exc);
</code>```

See: https://gamedev.stackexchange.com/questions/115573/how-are-methods-like-awake-start-and-update-called-in-unity/183091#183091

Body:
I've been experimenting with making a component based system similar to Unity's, but in C++. I'm wondering how the GetComponent() method that Unity implements works. It is a very powerful function. Specifically, I want to know what kind of container it uses to store its components.

The two criteria I need in my clone of this function are as follows. 1. I need any inherited components to be returned as well. For example, if SphereCollider inherits Collider, GetComponent<Collider>() will return the SphereCollider attached to the GameObject, but GetComponent<SphereCollider>() will not return any Collider attached. 2. I need the function to be fast. Preferably, it would use some kind of hash function.

For criteria one, I know that I could use something similar to the following implementation

std::vector<Component*> components
template <typename T>
T* GetComponent()
{
    for each (Component* c in components)
        if (dynamic_cast<T>(*c))
            return (T*)c;
    return nullptr;
}

But that doesn't fit the second criteria of being fast. For that, I know I could do something like this.

std::unordered_map<type_index, Component*> components
template <typename T>
T* GetComponent()
{
    return (T*)components[typeid(T)];
}

But again, that doesn't fit the first criteria.

If anybody knows of some way to combine those two features, even if it's a little slower than the second example, I would be willing to sacrifice a little bit. Thank you!

Body:
The Unity engine is linked with a forked mono runtime, on which unity scripts are executed.

In UnityEngine.Component

public class Component : Object
  {
    .
    .
    [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
    public Component GetComponent(Type type)
    {
        return this.gameObject.GetComponent(type);
    }

    [GeneratedByOldBindingsGenerator]
    [MethodImpl(MethodImplOptions.InternalCall)]
    internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue);

    [SecuritySafeCritical]
    public unsafe T GetComponent<T>()
    {
        CastHelper<T> castHelper = default(CastHelper<T>);
        this.GetComponentFastPath(typeof(T), new IntPtr((void*)(&castHelper.onePointerFurtherThanT)));
        return castHelper.t;
    }
    .
    .
}

The C# code performs native calls, called Icalls to C++ methods that have been bound to the C# methods using the C# runtime library API. Bodyless (unimplemented) methods need either an extern, abstract or partial specifier as a rule so all internal calls are marked as extern. When the runtime sees a method with the [MethodImpl(MethodImplOptions.InternalCall)] attribute it knows it needs to make an Icall, so it looks up the function it has been bound to and jumps to that address.

An Icall does not need to be static in C# and automatically passes the this MonoObject of the component to the C++ handler function. If they are static then the this object is usually deliberately passed as a parameter using a C# shim method and making the shim method the static Icall. Using Icalls, types are not marshalled unless they are blittable types, meaning all other types are passed as MonoObject, MonoString etc.

Typically the C++ methods are functions or static methods but I think they can be non static methods as well, so long as they aren't virtual, because the address cannot be fixed by the runtime.

in UnityEngine.GameObject

public sealed class GameObject : Object
 {
    .
    .
    public GameObject(string name)
    {
      GameObject.Internal_CreateGameObject(this, name);
    }

    public GameObject()
    {
      GameObject.Internal_CreateGameObject(this, (string) null);
    }

    [WrapperlessIcall]
    [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public extern Component GetComponent(System.Type type);

    [WrapperlessIcall]
    [MethodImpl(MethodImplOptions.InternalCall)]
    private static extern void Internal_CreateGameObject([Writable] GameObject mono, string name);
    .
    .
 }

The C# constructor for the GameObject contains a call to a native method. The body of the constructor is run after initialisation of the C# object such that there is already a this pointer. Internal_CreateGameObject is the static shim function that is actually called.

Someone's example implementation of their own C++ Internal_CreateGameObject using mono:

bool GameObjectBinding::init()
{
    MonoClass *gameObjectClass = Mono::get().getClass("GameObject");
    gameObject_NativeID_Field = mono_class_get_field_from_name(gameObjectClass, "nativeID");

    MonoClass *transformClass = Mono::get().getClass("Transform");
    transform_NativeID_Field = mono_class_get_field_from_name(transformClass, "nativeID");

    mono_add_internal_call("GameEngine_CS.GameObject::internal_createGameObject", GameObjectBinding::createGameObject);
    mono_add_internal_call("GameEngine_CS.GameObject::internal_deleteGameObject", GameObjectBinding::deleteGameObject);
    mono_add_internal_call("GameEngine_CS.GameObject::internal_getGameObject", GameObjectBinding::getGameObject);

    mono_add_internal_call("GameEngine_CS.GameObject::internal_getTransform", GameObjectBinding::getTransform);

    return true;
}

void GameObjectBinding::createGameObject(MonoObject * monoGameObject)
{
    Object *newObject = LevelManager::get().getCurrentLevel()->createObject(0);
    mono_field_set_value(monoGameObject, gameObject_NativeID_Field, (void*)newObject->getID());
}

mono_add_internal_call has been used to bind this method to GameObjectBinding::createGameObject, to which the this pointer is passed as a MonoObject pointer. A native object is then created to represent the GameObject, and mono_field_set_value is then used to set the NativeID field of the C# object to the ID of the new native object. This way the native object can be accessed from the MonoObject which is the internal implementation of the C# object. The GameObject is represented by 2 objects essentially.

public sealed class GameObject : Object
 {
     .
     .
     private UInt32 nativeID;
     public UInt32 id { get { return nativeID; } }
     .
     .
 }

This field is bound in the runtime using

mono_set_dirs( "/Library/Frameworks/Mono.framework/Home/lib", "/Library/Frameworks/Mono.framework/Home/etc" );
mono_config_parse( nullptr );
const char* managedbinarypath = "C:/Test.dll";
MonoDomain* domain = mono_jit_init(managedbinarypath)
MonoAssembly* assembly = mono_domain_assembly_open (domain, managedbinarypath);
MonoImage* image = mono_assembly_get_image (assembly);
MonoClass* gameobjectclass = mono_class_from_name(image, "ManagedLibrary", "GameObject");
gameObject_NativeID_Field = mono_class_get_field_from_name( gameobjectclass, "nativeID" );

GetComponent<T>() passes typeof(T) to GetComponentFastPath (the native call) which passes the this pointer of the component as well. The native implementation of GetComponentFastPath will receive this as a MonoObject* and a MonoReflectionType* for the type. The bound C++ method will then call mono_reflection_type_get_type() on the MonoReflectionType* to get the MonoType* (here are the primitive types: https://github.com/samneirinck/cemono/blob/master/src/native/inc/mono/mono/metadata/blob.h), or for object types you can get the MonoClass* from MonoType* using mono_class_from_mono_type(). It will then get the game object that is attached to the Component and search the components that the object has in some internal data structure.

Someone's example implementation of their own C++ GetComponent using mono:

id ModuleScriptImporter::RegisterAPI()
{
    //GAMEOBJECT
    mono_add_internal_call("TheEngine.TheGameObject::CreateNewGameObject", (const void*)CreateGameObject);
    mono_add_internal_call("TheEngine.TheGameObject::AddComponent", (const void*)AddComponent);
    mono_add_internal_call("TheEngine.TheGameObject::GetComponent", (const void*)GetComponent);
}

MonoObject* ModuleScriptImporter::GetComponent(MonoObject * object, MonoReflectionType * type)
{
    return current_script->GetComponent(object, type);
}

MonoObject* CSharpScript::GetComponent(MonoObject* object, MonoReflectionType* type)
{
    if (!CheckMonoObject(object))
    {
        return nullptr;
    }

    if (currentGameObject == nullptr)
    {
        return nullptr;
    }

    MonoType* t = mono_reflection_type_get_type(type);
    std::string name = mono_type_get_name(t);

    const char* comp_name = "";

    if (name == "CulverinEditor.Transform")
    {
        comp_name = "Transform";
    }

    MonoClass* classT = mono_class_from_name(App->importer->iScript->GetCulverinImage(), "CulverinEditor", comp_name);
    if (classT)
    {
        MonoObject* new_object = mono_object_new(CSdomain, classT);
        if (new_object)
        {
            return new_object;
        }
    }
    return nullptr;
}

C# methods can be invoked from C++:

MonoMethodDesc* desc = mono_method_desc_new (const char *name, gboolean include_namespace);
MonoClass* class = mono_class_from_name (MonoImage *image, const char* name_space, const char *name);
MonoMethod* method = mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass);
MonoMethod* method = mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image);
MonoObject* obj = mono_runtime_invoke (MonoMethod *method, void *obj, void **params,
                       MonoObject **exc);

See: https://gamedev.stackexchange.com/questions/115573/how-are-methods-like-awake-start-and-update-called-in-unity/183091#183091


问:
["'<built-in function id>' is not a valid UUID."]
I am trying to patch an existing but i get an unknown problem .Does anybody know why?

Models.py

```<code>class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles')
    caption = models.CharField(max_length=250)
</code>```

Views.py

```<code>class ArticleView(CreateAPIView):
  serializer_class = ArticleCreateSerializer
  permission_classes = (IsAuthenticated,)

  def patch(self, request, *args, **kwargs):
        article = get_object_or_404(Article, pk=id)
        serializer = ArticleCreateSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            article = serializer.save()
            return Response(ArticleCreateSerializer(article).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

Error:

```<code>["'<built-in function id>' is not a valid UUID."]
</code>```

答:
The error you're getting is related to the Python builtin id function. It's trying to use this id because there's no id in scope here - id isn't declared here or passed in as an argument.

Assuming you're using DRF's views normally, you should be able to do this instead:

```<code>article = self.get_object()
</code>```

Body:
I am trying to patch an existing but i get an unknown problem .Does anybody know why?

Models.py

class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles')
    caption = models.CharField(max_length=250)

Views.py

class ArticleView(CreateAPIView):
  serializer_class = ArticleCreateSerializer
  permission_classes = (IsAuthenticated,)

  def patch(self, request, *args, **kwargs):
        article = get_object_or_404(Article, pk=id)
        serializer = ArticleCreateSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            article = serializer.save()
            return Response(ArticleCreateSerializer(article).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Error:

["'<built-in function id>' is not a valid UUID."]

Body:
The error you're getting is related to the Python builtin id function. It's trying to use this id because there's no id in scope here - id isn't declared here or passed in as an argument.

Assuming you're using DRF's views normally, you should be able to do this instead:

article = self.get_object()


问:
how to load two or more identical webassembly modules from one wasm file?
I was recently using webpack to load the webassembly module, but I found that the current mechanism does not seem to allow me to load two or more identical webassembly modules

My webassembly is generated using the rust toolchain, so it will also generate a js file at the same time, so I dynamically load the generated js file.

My appeal is that I can import multiple instances that do not affect each other through multiple import(). A simple demo is as follow:

```<code>const js = import (/ * webpackChunkName: "view_sketch_wasm" * / "../pkg/hello_wasm.js");
js.then (js => {
  js.add_index ();
  js.add_index ();
  let id = js.get_index ();
  console.log ('id:', id);
  let id2 = js.get_index ();
  console.log ('id:', id2);
  const js2 = import (/ * webpackChunkName: "view_wasm_2" * / "../pkg/hello_wasm.js"); // hello_wasm2 also not useful
  js2.then (js => {
    js.add_index ();
    js.add_index ();
    let id = js.get_index ();
    console.log ('js2 id:', id);
    let id2 = js.get_index ();
    console.log ('js2 id:', id2);
  });
});

</code>```

I hope that js and js2 will not affect each other. They use two WebAssembly instances, each with its own memory.
But in fact they used the same WebAssembly instance (even though I copied hello_wasm.js and changed its name).
I also looked at the generated code, mainly because the cache was used when wasm was loaded:

```<code>wasmModules.forEach (function (wasmModuleId) {
/ ****** / var installedWasmModuleData = installedWasmModules [wasmModuleId];
/ ****** /
/ ****** / // a Promise means "currently loading" or "already loaded".
/ ****** / if (installedWasmModuleData)
/ ****** / promises.push (installedWasmModuleData);
/ ****** / else {
/ ****** / var importObject = wasmImportObjects [wasmModuleId] ();
/ ****** / var req = fetch (__ webpack_require __. p + "" + {"2": "795c98e4258ee4a1e670"} [wasmModuleId] + ".module.wasm");
/ ****** / var promise;
/ ****** / if (importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') {
/ ****** / promise = Promise.all ([WebAssembly.compileStreaming (req), importObject]). then (function (items) {
/ ****** / return WebAssembly.instantiate (items [0], items [1]);
/ ****** /});
/ ****** /} else if (typeof WebAssembly.instantiateStreaming === 'function') {
/ ****** / promise = WebAssembly.instantiateStreaming (req, importObject);
/ ****** /} else {
/ ****** / var bytesPromise = req.then (function (x) {return x.arrayBuffer ();});
/ ****** / promise = bytesPromise.then (function (bytes) {
/ ****** / return WebAssembly.instantiate (bytes, importObject);
/ ****** /});
/ ****** /}
/ ****** / promises.push (installedWasmModules [wasmModuleId] = promise.then (function (res) {
/ ****** / return __webpack_require __. w [wasmModuleId] = (res.instance
 res) .exports;
/ ****** /}));
/ ****** /}
</code>```

In addition, even if I modify this part of the code, the mechanism of webpack_require will have a cache, which prevents me from using two separate instances.

Considering that the loading mechanism here is complicated, and I should not modify the compiled code of webpack. I don't know how to do yet.

I also prepared a demo source code: https://github.com/aircloud/hello-wasm2

In summary, my appeal is that I can have multiple instances of webassembly for a wasm file. How can I do this with the current mechanism of webpack?

Thank you!

答:
If I understood your question correctly. I think the conflict will arises because of multiple references to the same webassembly.

Are you using LLVM compiler? Emscripten is the backend for WebAssembly and LLVM.
Emscripten is a source-to-source compiler that runs as a back end to the WebAssembly & LLVM compiler.

Historically, Emscripten only supported one instance per browser context, which is a limitation WebAssembly inherited. More recently Emscripten has added support for multiple instances but not sure if your compiler has gained that feature yet.

I would recommend iframes as workaround. That will keep everything in separate contexts and should work fine.

Body:
I was recently using webpack to load the webassembly module, but I found that the current mechanism does not seem to allow me to load two or more identical webassembly modules

My webassembly is generated using the rust toolchain, so it will also generate a js file at the same time, so I dynamically load the generated js file.

My appeal is that I can import multiple instances that do not affect each other through multiple import(). A simple demo is as follow:

const js = import (/ * webpackChunkName: "view_sketch_wasm" * / "../pkg/hello_wasm.js");
js.then (js => {
  js.add_index ();
  js.add_index ();
  let id = js.get_index ();
  console.log ('id:', id);
  let id2 = js.get_index ();
  console.log ('id:', id2);
  const js2 = import (/ * webpackChunkName: "view_wasm_2" * / "../pkg/hello_wasm.js"); // hello_wasm2 also not useful
  js2.then (js => {
    js.add_index ();
    js.add_index ();
    let id = js.get_index ();
    console.log ('js2 id:', id);
    let id2 = js.get_index ();
    console.log ('js2 id:', id2);
  });
});

I hope that js and js2 will not affect each other. They use two WebAssembly instances, each with its own memory.
But in fact they used the same WebAssembly instance (even though I copied hello_wasm.js and changed its name).
I also looked at the generated code, mainly because the cache was used when wasm was loaded:

wasmModules.forEach (function (wasmModuleId) {
/ ****** / var installedWasmModuleData = installedWasmModules [wasmModuleId];
/ ****** /
/ ****** / // a Promise means "currently loading" or "already loaded".
/ ****** / if (installedWasmModuleData)
/ ****** / promises.push (installedWasmModuleData);
/ ****** / else {
/ ****** / var importObject = wasmImportObjects [wasmModuleId] ();
/ ****** / var req = fetch (__ webpack_require __. p + "" + {"2": "795c98e4258ee4a1e670"} [wasmModuleId] + ".module.wasm");
/ ****** / var promise;
/ ****** / if (importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') {
/ ****** / promise = Promise.all ([WebAssembly.compileStreaming (req), importObject]). then (function (items) {
/ ****** / return WebAssembly.instantiate (items [0], items [1]);
/ ****** /});
/ ****** /} else if (typeof WebAssembly.instantiateStreaming === 'function') {
/ ****** / promise = WebAssembly.instantiateStreaming (req, importObject);
/ ****** /} else {
/ ****** / var bytesPromise = req.then (function (x) {return x.arrayBuffer ();});
/ ****** / promise = bytesPromise.then (function (bytes) {
/ ****** / return WebAssembly.instantiate (bytes, importObject);
/ ****** /});
/ ****** /}
/ ****** / promises.push (installedWasmModules [wasmModuleId] = promise.then (function (res) {
/ ****** / return __webpack_require __. w [wasmModuleId] = (res.instance
 res) .exports;
/ ****** /}));
/ ****** /}

In addition, even if I modify this part of the code, the mechanism of webpack_require will have a cache, which prevents me from using two separate instances.

Considering that the loading mechanism here is complicated, and I should not modify the compiled code of webpack. I don't know how to do yet.

I also prepared a demo source code: https://github.com/aircloud/hello-wasm2

In summary, my appeal is that I can have multiple instances of webassembly for a wasm file. How can I do this with the current mechanism of webpack?

Thank you!


问:
Ttrigger after insert
I'm trying to write trigger which enters a value (+1) into another column.

If I add a new car into the dbo.deelnemers/autonr my dbo.auto's/risico column should be added with the value +1

```<code>create trigger trRisicos
on deelnemers
after insert
as
begin
    set nocount on;

    declare u/autonr int

    select u/autonr = inserted.autonr
    from inserted

    insert into autos
    values (@autonr, 1)
end
</code>```

This is the code I have so far.

```<code>dbo.deelnemers/autonr (PK, FK, INT, NOT NULL)
dbo.deelnemers/evenementnr (PK, FK, INT, NOT NULL)

dbo.autos/autonr (PK, INT, NOT NULL)
dbo.autos/typenaam (CHAR(50), NULL)
dbo.autos/bouwjaar (INT, NULL)
dbo.autos/waarde (INT, NULL)
dbo.autos/passagiers (INT, NULL)
dbo.autos/lidnr (FK, INT, NULL)
dbo.autos/Risico (SMALLINT, NULL)
</code>```

答:
Try this:

create trigger trRisicos
on deelnemers
after insert
as
begin
    set nocount on;

    INSERT INTO autos (autonr, risico)
    SELECT autonr, 1
    FROM INSERTED;
end

```

Title: Ttrigger after insert

Body:
I'm trying to write trigger which enters a value (+1) into another column.

If I add a new car into the dbo.deelnemers/autonr my dbo.auto's/risico column should be added with the value +1

create trigger trRisicos
on deelnemers
after insert
as
begin
    set nocount on;

    declare u/autonr int

    select u/autonr = inserted.autonr
    from inserted

    insert into autos
    values (@autonr, 1)
end

This is the code I have so far.

dbo.deelnemers/autonr (PK, FK, INT, NOT NULL)
dbo.deelnemers/evenementnr (PK, FK, INT, NOT NULL)

dbo.autos/autonr (PK, INT, NOT NULL)
dbo.autos/typenaam (CHAR(50), NULL)
dbo.autos/bouwjaar (INT, NULL)
dbo.autos/waarde (INT, NULL)
dbo.autos/passagiers (INT, NULL)
dbo.autos/lidnr (FK, INT, NULL)
dbo.autos/Risico (SMALLINT, NULL)


问:
How to avoid if statements which returns value based on the input in java 8
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

```<code>RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}
</code>```

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

答:
Hi I got below solution on this.</p>

```<code>RoleEnum fetchProcessForRole(Long roleID) {

String name= RoleEnum.values()[int(long)roleID].getName().toUpperCase();
return EnumSet.allOf(RoleEnum.class).stream()
            .filter(role -> role.getName().startsWith(name+"_"))
            .findFirst()
            .get();

}
</code>```

Body:
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

Body:
Hi I got below solution on this.

RoleEnum fetchProcessForRole(Long roleID) {

String name= RoleEnum.values()[int(long)roleID].getName().toUpperCase();
return EnumSet.allOf(RoleEnum.class).stream()
            .filter(role -> role.getName().startsWith(name+"_"))
            .findFirst()
            .get();

}


问:
Azure app service settings slotSetting not honored
In Azure DevOps, in a release pipeline, I specified Application Settings to be added/update:

```<code>[
  {
    "name": "HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONENABLED",
    "value": "true",
    "slotSetting": false
  },
  {
    "name": "HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONVAULT",
    "value": "https://******.vault.azure.net",
    "slotSetting": false
  }
]
</code>```

The slot setting is set to false. However, in the end, it becomes true after the release step happens.

I tried deleting them and executing the release pipeline again but the HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONENABLED slot setting flag is always set to true.

Why does this happen? How can I fix it?

答:
After I deleted the settings and run the pipeline, the true value would come back.

However, after I set the "slotSetting" to false and deleted it, it started working correctly.

It seems like a bug to me but, in case you face a similar issue, do the above and it should start working again.

Body:
In Azure DevOps, in a release pipeline, I specified Application Settings to be added/update:

[
  {
    "name": "HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONENABLED",
    "value": "true",
    "slotSetting": false
  },
  {
    "name": "HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONVAULT",
    "value": "https://******.vault.azure.net",
    "slotSetting": false
  }
]

The slot setting is set to false. However, in the end, it becomes true after the release step happens.

I tried deleting them and executing the release pipeline again but the HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONENABLED slot setting flag is always set to true.

Why does this happen? How can I fix it?


问:
Connecting two promises in a Firebase web app
I am using a Realtime Database to handle some data in a Firebase web app.
In the code hereafter, I want to insert a record in the DB only if fieldOne and fieldTwo aren't going to be duplicated.

```<code>dbReference.orderByChild("fieldOne").equalTo(fieldOneVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This fieldOne has already been used.')
    reject();
  }
}).then( // What is the correct way to connect this line and the following ??
dbReference.orderByChild("fieldTwo").equalTo(fieldTwoVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This NAME has already been used.')
    reject();
  }

  // All is now OK.
  .... do the final things here .....
}).catch(function(error) {
  // An error happened.
  alert('This record cannot be inserted.')
});
</code>```

At this point, I am able to tweak the code to make things work the way I wish. But my issue is that I am not doing things the proper way (I know that due to some messages I can see in the console). The comment in my code shows where I need to know the correct way to connect the two parts.
What is the .... the following ??

For information the DB looks like this:

```<code>MyList
  + -M93j....443cxYYDSN
      fieldOne: "asdc..."
      fieldTwo: "Gkk...."
  + -M94j.........OZS6FL
      fieldOne: "afc..."
      fieldTwo: "SDFSk...."
</code>```

答:
Try the hasChild() method.

```<code>if(snapshot.hasChild('name') {
   // ... do stuff !
}
</code>```

Or,

create a new node in your firebase real-time db named as usernames and add each username in this list. In future before inserting a new username check if it's present in this list

Body:
I am using a Realtime Database to handle some data in a Firebase web app.
In the code hereafter, I want to insert a record in the DB only if fieldOne and fieldTwo aren't going to be duplicated.

dbReference.orderByChild("fieldOne").equalTo(fieldOneVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This fieldOne has already been used.')
    reject();
  }
}).then( // What is the correct way to connect this line and the following ??
dbReference.orderByChild("fieldTwo").equalTo(fieldTwoVal).once('value')
.then(function(snapshot) {
  if (snapshot.exists()) {
    alert('This NAME has already been used.')
    reject();
  }

  // All is now OK.
  .... do the final things here .....
}).catch(function(error) {
  // An error happened.
  alert('This record cannot be inserted.')
});

At this point, I am able to tweak the code to make things work the way I wish. But my issue is that I am not doing things the proper way (I know that due to some messages I can see in the console). The comment in my code shows where I need to know the correct way to connect the two parts.
What is the .... the following ??

For information the DB looks like this:

MyList
  + -M93j....443cxYYDSN
      fieldOne: "asdc..."
      fieldTwo: "Gkk...."
  + -M94j.........OZS6FL
      fieldOne: "afc..."
      fieldTwo: "SDFSk...."

Body:
Try the hasChild() method.

if(snapshot.hasChild('name') {
   // ... do stuff !
}

Or,

create a new node in your firebase real-time db named as usernames and add each username in this list. In future before inserting a new username check if it's present in this list


问:
Tkinter disable bind to return key in a Dialog with Text
I have a simple dialog in my app whose purpose is to allow the user to edit some text properties. The relevant part of the code simplifies to:

from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):
    def __init__(self, root):
        Dialog.__init__(self, root)

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)
```

<p>Unfortunately, using the <code><Return></code> key when typing in the <code>ScrolledText</code> field is not interpreted as a line break but as an "OK" by the Dialog, which therefore closes. I thought binding that key to a handler that does nothing would help, but inserting <code>self.bind("<Return>", self.my_return_handler)</code> at the beginning of my dialog's <code>body</code> method does not intercept anything and inserting it right after <code>Dialog.__init__(self, root)</code> raises the following error:</p>

```Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "guitk.py", line 142, in edit_project_properties
    ProjectPropertiesDialog(self.main_window, None)
  File "guitk.py", line 337, in __init__
    self.bind("<Return>", self.return_handler)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1251, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1206, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad window path name ".!projectpropertiesdialog"
```

How do I fix this? Is there a better suited approach?

答:
If you use

```<code>import tkinter.simpledialog
print(tkinter.simpledialog.__file__)
</code>```

then you get path to source code and you will see where it binds <Return> and then you can remove it.

I copied original buttonbox() from source code and commented line which binds <Return>

```<code>from tkinter import *
from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)
        self.project_description.focus()

    def buttonbox(self):
        '''add standard button box.

        override if you do not want the standard buttons
        '''

        box = Frame(self)

        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        #self.bind("<Return>", self.ok)  # <-- remove it
        self.bind("<Escape>", self.cancel)

        box.pack()

root = Tk()
PropertiesDialog(root)
root.mainloop()
</code>```

BTW: In source code __init__ you can see it excutes body before buttonbox so you can't unbind() it in body because it will bind it after this unbind(). You can also see that __init__ works in different way then normal class - __init__ waits for closing window - so using it inside __init__ will be executed after closing Dialog window.

EDIT: Info for other users - as Anthony Labarre mentioned in comment it is simpler method

```<code>def buttonbox(self):
    super().buttonbox()
    self.unbind("<Return>")
    #self.bind("<Control-Return>", self.ok)  # bind other combination to OK
</code>```

```<code>from tkinter import *
from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)
        self.project_description.focus()

    def buttonbox(self):
        super().buttonbox()
        self.unbind("<Return>")
        #self.bind("<Control-Return>", self.ok)  # bind other combination to OK

root = Tk()
PropertiesDialog(root)
root.mainloop()
</code>```

Body:
I have a simple dialog in my app whose purpose is to allow the user to edit some text properties. The relevant part of the code simplifies to:

from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):
    def __init__(self, root):
        Dialog.__init__(self, root)

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)

Unfortunately, using the <Return> key when typing in the ScrolledText field is not interpreted as a line break but as an "OK" by the Dialog, which therefore closes. I thought binding that key to a handler that does nothing would help, but inserting self.bind("<Return>", self.my_return_handler) at the beginning of my dialog's body method does not intercept anything and inserting it right after Dialog.__init__(self, root) raises the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "guitk.py", line 142, in edit_project_properties
    ProjectPropertiesDialog(self.main_window, None)
  File "guitk.py", line 337, in __init__
    self.bind("<Return>", self.return_handler)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1251, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1206, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad window path name ".!projectpropertiesdialog"

How do I fix this? Is there a better suited approach?

Body:
If you use

import tkinter.simpledialog
print(tkinter.simpledialog.__file__)

then you get path to source code and you will see where it binds <Return> and then you can remove it.

I copied original buttonbox() from source code and commented line which binds <Return>

from tkinter import *
from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)
        self.project_description.focus()

    def buttonbox(self):
        '''add standard button box.

        override if you do not want the standard buttons
        '''

        box = Frame(self)

        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        #self.bind("<Return>", self.ok)  # <-- remove it
        self.bind("<Escape>", self.cancel)

        box.pack()

root = Tk()
PropertiesDialog(root)
root.mainloop()

BTW: In source code __init__ you can see it excutes body before buttonbox so you can't unbind() it in body because it will bind it after this unbind(). You can also see that __init__ works in different way then normal class - __init__ waits for closing window - so using it inside __init__ will be executed after closing Dialog window.

EDIT: Info for other users - as Anthony Labarre mentioned in comment it is simpler method

def buttonbox(self):
    super().buttonbox()
    self.unbind("<Return>")
    #self.bind("<Control-Return>", self.ok)  # bind other combination to OK

from tkinter import *
from tkinter.simpledialog import Dialog
from tkinter.scrolledtext import ScrolledText

class PropertiesDialog(Dialog):

    def body(self, master):
        Label(master, text="Description").grid(row=0, column=0, sticky=W)
        self.project_description = ScrolledText(master, height=10, width=40)
        self.project_description.grid(row=0, column=1, sticky=W)
        self.project_description.focus()

    def buttonbox(self):
        super().buttonbox()
        self.unbind("<Return>")
        #self.bind("<Control-Return>", self.ok)  # bind other combination to OK

root = Tk()
PropertiesDialog(root)
root.mainloop()


问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
You can just use simple dict for data mapping</p>

```<code>emotions = {'happy': 2, 'sad': 5,  'grumpy': 6, 'mad': 9}

if emotions['happy'] > emotions['sad']:
    print("you are happy")
else:
    print("you are sad")

</code>```

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

Body:
You can just use simple dict for data mapping

emotions = {'happy': 2, 'sad': 5,  'grumpy': 6, 'mad': 9}

if emotions['happy'] > emotions['sad']:
    print("you are happy")
else:
    print("you are sad")


答:
Your code is creating 3 elements + 1 already exists. I have updated the code to use the index.

window.onload = function() {
  const users = ["a", "b", "c"];

  users.forEach(function(user) {
    const el = document.createElement("p");
    el.innerHTML = user;
    el.className = 'story';

    document.getElementById("story").appendChild(el);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="story"></div></code>```

Title: Extra output outputted

Body:
In this code I want the output as a b c, but at the end there is another a outputting. So, how can I do it?

window.onload = function() {
  for (let i = 0; i < 3; i++) {
    var story = document.getElementsByClassName('story')[0];

    let clone = story.cloneNode(true);

    let usr = ["a", "b", "c"];

    document.getElementsByClassName('story')[i].innerHTML = usr[i];

    document.getElementById("story").appendChild(clone);
  }
}

Body:
Your code is creating 3 elements + 1 already exists. I have updated the code to use the index.

window.onload = function() {
  const users = ["a", "b", "c"];

  users.forEach(function(user) {
    const el = document.createElement("p");
    el.innerHTML = user;
    el.className = 'story';

    document.getElementById("story").appendChild(el);
  });
}

<div id="story"></div>


问:
lighttpd redirect from custom HTTP port 81 to HTTPS port 443
I have the following configuration

```<code>$SERVER["socket"] == ":81" {
#$HTTP["scheme"] == "http" {
    $HTTP["host"] =~ ".*" {
        url.redirect = (".*" => "https://%0$0")
    }
}
</code>```

As far as i see: %0 expands to serverip:81.
So i need to get rid of :81 from %0. How?

But it leads to the redirection from HTTP port 81 to https://serverip:81 and then fails with SSL_ERROR_SYSCALL.

Answer from https://stackoverflow.com/a/62099076/3743145:

```<code> * LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81
</code>```

The error is SSL_ERROR_SYSCALL and this has nothing to do with certificate validation. In fact, a closer look at what you are doing shows that you are redirecting from plain HTTP on port 81 to HTTPS on the same port.

答:
Solved.</p>

```<code>$HTTP["scheme"] == "http" {
    $HTTP["host"] =~ "(.*)(:[0-9]+|)$" {  ## %1 contains hostname without port
        url.redirect = (".*" => "https://%1$0")
    }
}
</code>```

Body:
I have the following configuration

$SERVER["socket"] == ":81" {
#$HTTP["scheme"] == "http" {
    $HTTP["host"] =~ ".*" {
        url.redirect = (".*" => "https://%0$0")
    }
}

As far as i see: %0 expands to serverip:81.
So i need to get rid of :81 from %0. How?

But it leads to the redirection from HTTP port 81 to https://serverip:81 and then fails with SSL_ERROR_SYSCALL.

Answer from https://stackoverflow.com/a/62099076/3743145:

 * LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81

The error is SSL_ERROR_SYSCALL and this has nothing to do with certificate validation. In fact, a closer look at what you are doing shows that you are redirecting from plain HTTP on port 81 to HTTPS on the same port.

Body:
Solved.

$HTTP["scheme"] == "http" {
    $HTTP["host"] =~ "(.*)(:[0-9]+|)$" {  ## %1 contains hostname without port
        url.redirect = (".*" => "https://%1$0")
    }
}


问:
How do I use the outputs from the network module in the security group module without creating resources twice?
```<code>├── instance.tf
├── module
│   ├── Network
│   │   ├── output.tf
│   │   ├── resource.tf
│   │   └── vars.tf
│   └── sg
│       ├── output.tf
│       └── resource.tf
├── provider.tf
├── terraform.tfstate
├── terraform.tfstate.backup
└── vars.tf
</code>```

This is my project folder structure

I am trying to create two modules, one is for vpc and another one for security  group . Here is my outputs for vpc module

```<code>output "vpc_id" {
    value = aws_vpc.vpc_dev.id
}
output "public_subnet_id" {
    value = aws_subnet.public_subnet.id
}
output "private_subnet_id" {
    value = aws_subnet.private_subnet.id
}
</code>```

the security groups module looks like

```<code>module "NetworkModule" {
    source ="../Network"
}
resource "aws_security_group" "sg_dev" {
    name = "web_sg"
    vpc_id = module.NetworkModule.vpc_id
    ....
    ...}
</code>```

here is the outputs for sg module

```<code>output "sg_id" {
    value = aws_security_group.sg_dev.id
}
</code>```

i am using this modules to create my instance in aws

```<code>module "NetworkModule" {
    source = "./module/Network"
}
module "sgmodule"{
    source = "./module/sg"
}
resource "aws_instance" "web_dev" {
    ami = var.AMIS[var.REGION]
    instance_type = "t2.micro"
    subnet_id = module.NetworkModule.public_subnet_id
    vpc_security_group_ids = ["${module.sgmodule.sg_id}"]
    tags = {
        Name = "web_dev"
    }
}
</code>```

But  i can see everything related to  vpc module is getting created for two times (for eg. i can see two vpc instead of one , 2 public subnets instead of one  etc.)  ..am i using the modules in the right way ? ..

How do I use the outputs from the network module in the security group module without creating resources twice?

答:
In instance.tf you have:

```<code>module "NetworkModule" {
    source = "./module/Network"
}
module "sgmodule"{
    source = "./module/sg"
}
</code>```

In module/sg/resource.tf you have:

```<code>module "NetworkModule" {
    source ="../Network"
}
</code>```

As a result you get two instances of the Network module, and double the resources.

Using module in Terraform is somewhat like using new in other languages. It instantiates the module again, creating another copy of its required resources. This is generally useful, but it's suprising in your case.

What you should likely do is remove the NetworkModule module from module/sg/resource.tf and replace it with a variable:

```<code>variable "vpc_id" {
    type = string
}

resource "aws_security_group" "sg_dev" {
    name = "web_sg"
    vpc_id = var.vpc_id
    ....
    ...}
</code>```

Then in instance.tf provide that variable to the sgmodule module block:

```<code>module "sgmodule"{
    source = "./module/sg"
    vpc_id = module.NetworkModule.vpc_id
}
</code>```

Now you'll have the dependencies you need without the duplication of network infrastructure resources.

Body:
├── instance.tf
├── module
│   ├── Network
│   │   ├── output.tf
│   │   ├── resource.tf
│   │   └── vars.tf
│   └── sg
│       ├── output.tf
│       └── resource.tf
├── provider.tf
├── terraform.tfstate
├── terraform.tfstate.backup
└── vars.tf

This is my project folder structure

I am trying to create two modules, one is for vpc and another one for security  group . Here is my outputs for vpc module

output "vpc_id" {
    value = aws_vpc.vpc_dev.id
}
output "public_subnet_id" {
    value = aws_subnet.public_subnet.id
}
output "private_subnet_id" {
    value = aws_subnet.private_subnet.id
}

the security groups module looks like

module "NetworkModule" {
    source ="../Network"
}
resource "aws_security_group" "sg_dev" {
    name = "web_sg"
    vpc_id = module.NetworkModule.vpc_id
    ....
    ...}

here is the outputs for sg module

output "sg_id" {
    value = aws_security_group.sg_dev.id
}

i am using this modules to create my instance in aws

module "NetworkModule" {
    source = "./module/Network"
}
module "sgmodule"{
    source = "./module/sg"
}
resource "aws_instance" "web_dev" {
    ami = var.AMIS[var.REGION]
    instance_type = "t2.micro"
    subnet_id = module.NetworkModule.public_subnet_id
    vpc_security_group_ids = ["${module.sgmodule.sg_id}"]
    tags = {
        Name = "web_dev"
    }
}

But  i can see everything related to  vpc module is getting created for two times (for eg. i can see two vpc instead of one , 2 public subnets instead of one  etc.)  ..am i using the modules in the right way ? ..

How do I use the outputs from the network module in the security group module without creating resources twice?

Body:
In instance.tf you have:

module "NetworkModule" {
    source = "./module/Network"
}
module "sgmodule"{
    source = "./module/sg"
}

In module/sg/resource.tf you have:

module "NetworkModule" {
    source ="../Network"
}

As a result you get two instances of the Network module, and double the resources.

Using module in Terraform is somewhat like using new in other languages. It instantiates the module again, creating another copy of its required resources. This is generally useful, but it's suprising in your case.

What you should likely do is remove the NetworkModule module from module/sg/resource.tf and replace it with a variable:

variable "vpc_id" {
    type = string
}

resource "aws_security_group" "sg_dev" {
    name = "web_sg"
    vpc_id = var.vpc_id
    ....
    ...}

Then in instance.tf provide that variable to the sgmodule module block:

module "sgmodule"{
    source = "./module/sg"
    vpc_id = module.NetworkModule.vpc_id
}

Now you'll have the dependencies you need without the duplication of network infrastructure resources.


问:
How to require a private package hosted on bitbucket.org with composer?
I'm trying to require a package I created from a private git repository on bitbucket.org.

I have the following composer.json in my private git repository:

```<code>{
    "name": "[user]/[package]",
    "type": "project",
    "license" : "proprietary",
    "authors": [],
    "require": {
        "php": "^5.6 || ^7.0"
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0-dev"
        }
    }
</code>```

If I call ...

composer require git@bitbucket.org:[user]/[package].git
```
<p>... I get the following exception:</p>
``` [UnexpectedValueException]
  Could not parse version constraint [user]/[package].git: Invalid version string "[user]/[package].git"
```
<p>How can I install my private package?</p>
<h1>[UPDATE]</h1>
<p>i have put the json file in my new project as suggested i am now getting this error.</p>
<pre class="lang-sh prettyprint-override"><code>Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package [user]/[package] 1.0-dev exists as [user]/[package][1.0.x-dev, dev-master] but these are rejected by your constraint.

</code>```

答:
You need to tell composer where to find your package(s) by adding repositories.

composer isn't able to require a package directly from a git repository like you tried.

Add your git repository containing the package under the repositories key as a vcs repository to the composer.json of the project you're intending to use the package in.

```<code>{
  "repositories": [
    { "type": "vcs", "url": "https://bitbucket.org/[user]/[package].git" }
  ],
  "require": {
    "[user]/[package]": "1.0-dev"
  }
}
</code>```

You can also add the repository to your global composer.json to make it available for all projects.

Body:
I'm trying to require a package I created from a private git repository on bitbucket.org.

I have the following composer.json in my private git repository:

{
    "name": "[user]/[package]",
    "type": "project",
    "license" : "proprietary",
    "authors": [],
    "require": {
        "php": "^5.6 || ^7.0"
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0-dev"
        }
    }

If I call ...

composer require git@bitbucket.org:[user]/[package].git

... I get the following exception:

 [UnexpectedValueException]
  Could not parse version constraint [user]/[package].git: Invalid version string "[user]/[package].git"

How can I install my private package?

[UPDATE]

i have put the json file in my new project as suggested i am now getting this error.

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package [user]/[package] 1.0-dev exists as [user]/[package][1.0.x-dev, dev-master] but these are rejected by your constraint.

Body:
You need to tell composer where to find your package(s) by adding repositories.

composer isn't able to require a package directly from a git repository like you tried.

Add your git repository containing the package under the repositories key as a vcs repository to the composer.json of the project you're intending to use the package in.

{
  "repositories": [
    { "type": "vcs", "url": "https://bitbucket.org/[user]/[package].git" }
  ],
  "require": {
    "[user]/[package]": "1.0-dev"
  }
}

You can also add the repository to your global composer.json to make it available for all projects.