问:
do consumer lag of one consumer will affect other consumer in a same group id with different topics
I have one group Id "my-consumer-group-id" and 3 topics with their own consumers
say

```<code>"my-consumer-1" consumed to "topic1" with groupId "my-consumer-group-id"
"my-consumer-2" consumed to "topic2" with groupId "my-consumer-group-id"
"my-consumer-3" consumed to "topic3" with groupId "my-consumer-group-id"
</code>```

I observed "my-consumer-1" has 2 million records with 600k consumer lag,
will this affect other consumers from being processed their own message? in terms of the performance, is it better to have a separate consumer groupId for each consumer?

答:
A consumer can join a consumer group (let us say group_1) by setting its group.id to group_1. Consumer groups is also a way of supporting parallel consumption of the data i.e. different consumers of the same consumer group consume data in parallel from different partitions.

In addition to the group Id, each consumer also identifies itself to the Kafka broker using consumer.id. This is used by Kafka to identify the currently ACTIVE consumers of a particular consumer group.

Reference
difference between groupid and consumerid in Kafka consumer

In your case; by adding another consumer (with different ID), Kafka will assign another partition to the new consumer. As you mentioned, my-consumer-1 has 600k lag. Adding a new consumer under the same group won’t help since a new partition will be allocated. But there are only three partitions, 4th consumer won't get any new partition as long 3 consumers are working fine.

Body:
I have one group Id "my-consumer-group-id" and 3 topics with their own consumers
say

"my-consumer-1" consumed to "topic1" with groupId "my-consumer-group-id"
"my-consumer-2" consumed to "topic2" with groupId "my-consumer-group-id"
"my-consumer-3" consumed to "topic3" with groupId "my-consumer-group-id"

I observed "my-consumer-1" has 2 million records with 600k consumer lag,
will this affect other consumers from being processed their own message? in terms of the performance, is it better to have a separate consumer groupId for each consumer?


来源: stackexchange

问:
show data from object on click
In my react app, I'm setting multiple values in an object. I also have some input field with a button/icon attached to it. What I want is, to get the id value of that button on click and with that id value I want to check if the object has the same property or not. If it has that property I want to use it later for separate functionality. But right now I'm just console logging it. For this I've attached a handleClick() handler and getting the e.target.id and printing it. But there are 2 problems I'm facing right now.

Sometimes I'm getting empty string on clicking. Sometimes I've to click multiple times to get the value.

In the handleClick() I'm not getting the data from the object. I've tried using hasOwnProperty or key in Object, but they are not working

code

```<code>const dropdowns = {
  group: [
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
  ],
  supplier: [
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
  ],
  attribute: [
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
  ],
  unit: [
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
  ],
  uses: [
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
  ],
};

const SetupBar = () => {

  const [formData, setFormData] = useState({
    group: "",
    supplier: "",
    attribute: "",
    unit: "",
    uses: "",
  });

  const handleClick = (value) => {
    console.log(value);
    // console.log(dropdowns.value); I want this
  };

return (
    <div className="parent">
     <div className="input-fields">
      <label htmlFor="attribute">Attribute ID</label>
      <div className="input-grp">
        <input type="text" />
        <CgArrowRightR
          id="attribute"
          style={{ fontSize: "21px" }}
          onClick={(e) => handleClick(e.target.id)}
        />
      </div>
    </div>

        <div className="input-fields">
          <label htmlFor="color">Color</label>
          <input type="text" id="color" />
        </div>
        <div className="input-fields">
          <label htmlFor="group">Group Code</label>
          <div className="input-grp">
            <input type="text" />
            <CgArrowRightR
              id="group"
              style={{ fontSize: "21px" }}
              onClick={(e) => handleClick(e.target.id)}
            />
          </div>
        </div>
        <div className="input-fields">
          <label htmlFor="supplier">Supplier</label>
          <div className="input-grp">
            <input type="text" />
            <CgArrowRightR
              id="supplier"
              style={{ fontSize: "21px" }}
              onClick={(e) => handleClick(e.target.id)}
            />
          </div>
        </div>
</code>```

答:
Your problem with e.target, react-icons SVG also have path tag without id and when you click on icon you click on path and you get empy string. Just use e.currentTarget.id instead of e.target.id. currentTarget always refers to the element to which the event handler has been attached.

Second issue (You incorrect get property):

```<code>const handleClick = (value) => {
   console.log(dropdowns[value]);
};
</code>```

ContentLicense: CC BY-SA 4.0

Title: show data from object on click

Body:
In my react app, I'm setting multiple values in an object. I also have some input field with a button/icon attached to it. What I want is, to get the id value of that button on click and with that id value I want to check if the object has the same property or not. If it has that property I want to use it later for separate functionality. But right now I'm just console logging it. For this I've attached a handleClick() handler and getting the e.target.id and printing it. But there are 2 problems I'm facing right now.

Sometimes I'm getting empty string on clicking. Sometimes I've to click multiple times to get the value.

In the handleClick() I'm not getting the data from the object. I've tried using hasOwnProperty or key in Object, but they are not working

code

const dropdowns = {
  group: [
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
  ],
  supplier: [
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
  ],
  attribute: [
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
  ],
  unit: [
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
  ],
  uses: [
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
  ],
};

const SetupBar = () => {

  const [formData, setFormData] = useState({
    group: "",
    supplier: "",
    attribute: "",
    unit: "",
    uses: "",
  });

  const handleClick = (value) => {
    console.log(value);
    // console.log(dropdowns.value); I want this
  };

return (

      Attribute ID

        <input type="text" />
        <CgArrowRightR
          id="attribute"
          style={{ fontSize: "21px" }}
          onClick={(e) => handleClick(e.target.id)}
        />

          Color
          <input type="text" id="color" />

          Group Code

            <input type="text" />
            <CgArrowRightR
              id="group"
              style={{ fontSize: "21px" }}
              onClick={(e) => handleClick(e.target.id)}
            />

          Supplier

            <input type="text" />
            <CgArrowRightR
              id="supplier"
              style={{ fontSize: "21px" }}
              onClick={(e) => handleClick(e.target.id)}
            />

Body:
Your problem with e.target, react-icons SVG also have path tag without id and when you click on icon you click on path and you get empy string. Just use e.currentTarget.id instead of e.target.id. currentTarget always refers to the element to which the event handler has been attached.

Second issue (You incorrect get property):

const handleClick = (value) => {
   console.log(dropdowns[value]);
};


问:
Html purifier clears p tag
For some reason html purifier clears p tags. It happens when p is inside of span tags.
For example:

```<code><span class=\"large gray content_text article_text\">
<p>111111</p>
<p>222222</p>
<p>333333</p>
</span>
</code>```

Output:

```<code><span>111111

2222222

3333333</span>
</code>```

My htmlpurifier config:

```<code>$config = HTMLPurifier_Config::createDefault();
$config -> set('Core.Encoding', 'UTF-8');
$config -> set('HTML.Doctype', 'XHTML 1.0 Transitional');
$config -> set('HTML.TidyLevel','none');
$config -> set('HTML.Allowed', 'p, a[href|rel], span[style], img[src|style], object[height|width|data], param[name|value|allowscriptaccess|allowfullscreen|height|width], br, strong, em');
$config -> set('CSS.AllowedProperties', 'font-weight, font-style, text-decoration, color, width, height');
$config -> set('HTML.SafeObject', 'true');
$config -> set('Output.FlashCompat', 'true');
$config -> set('HTML.FlashAllowFullScreen', 'true');
$schemes = array('http' => true, 'https' => true);
$config -> set('URI.AllowedSchemes', $schemes);
$purifier = new HTMLPurifier($config);
$content = $purifier -> purify($content);
</code>```

答:
 is an inline element, it's incorrect to put block level
 tags inside of it.

Use
 instead of .

ContentLicense: CC BY-SA 3.0

Title: Html purifier clears p tag

Body:
For some reason html purifier clears p tags. It happens when p is inside of span tags.
For example:

111111

222222

333333

Output:

111111

2222222

3333333

My htmlpurifier config:

$config = HTMLPurifier_Config::createDefault();
$config -> set('Core.Encoding', 'UTF-8');
$config -> set('HTML.Doctype', 'XHTML 1.0 Transitional');
$config -> set('HTML.TidyLevel','none');
$config -> set('HTML.Allowed', 'p, a[href|rel], span[style], img[src|style], object[height|width|data], param[name|value|allowscriptaccess|allowfullscreen|height|width], br, strong, em');
$config -> set('CSS.AllowedProperties', 'font-weight, font-style, text-decoration, color, width, height');
$config -> set('HTML.SafeObject', 'true');
$config -> set('Output.FlashCompat', 'true');
$config -> set('HTML.FlashAllowFullScreen', 'true');
$schemes = array('http' => true, 'https' => true);
$config -> set('URI.AllowedSchemes', $schemes);
$purifier = new HTMLPurifier($config);
$content = $purifier -> purify($content);

Body:
<span> is an inline element, it's incorrect to put block level <p> tags inside of it.

Use <div> instead of <span>.


问:
how to Show like exist or not in serializer based on request.data in django
i have a post model and like model with ForeignKey. in API user will give the user session id . i want to show the user liked a post or not based on the session id in when i list all post . for example . when we open instagram we can as user which post we liked or not in the heart icon .

models.py

```<code>class Post(models.Model):
  title = models.CharField(max_length=150)
  image = models.FileField( upload_to="post/",)

class PostLike(models.Model):
    like = models.CharField(max_length=10)
    user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='post_likes')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')
</code>```

views.py

```<code>@api_view(["POST"])
def post(request):
  if request.data != {}:
     session_id = request.data["session_id"]
     user = Customer.objects.filter(session_id=session_id)
         if user.count() != 0:
             posts = Post.objects.all()
             like_exist = PostLike.objects.filter(user = user).exists()
             serializer = PostSerializer(posts, many=True,context=
                           {"like_exist":like_exist)
             return Custom_Response(request, news_serializer.data)
</code>```

serializer.py

```<code>class PostSerializer(serializers.ModelSerializer):
    like_exist = serializers.SerializerMethodField("like_exist_")

    class Meta:
        model = News
        fields  = ["title","image","like_exist"]

    def like_exist_(self,obj):
        is_liked = self.context.get("like_exist")
        return is_liked
</code>```

db

```<code>post

id title image
1  1st    ""
2  2nd    ""

post_like

id like post_id user_id
1   1   1       1
2   1   2       1
3   1   1       2
</code>```

if api input session_id 10000 ,it's customer 1
so i want to show like this

API

```<code>"data": [
        {
            "id": 1,
            "title": "trend post 1",
            "like_exist":true ,
        },
        {
            "id": 2,
            "title": "trend post 2",
            "like_exist": true,
        }
    ]
</code>```

if it's 20000 , that's customer 2
so response should look like

```<code>"data": [
        {
            "id": 1,
            "title": "trend post 1",
            "like_exist":true ,
        },
        {
            "id": 2,
            "title": "trend post 2",
            "like_exist": false,
        }
    ]
</code>```

how get this ? i think maybe it's work with model property . but how . ???

sorry for my poor english,
Thank you

答:
If I understand you correctly, you need something like this

```<code>from django.db.models import Count, Exists

@api_view(["POST"])
def post(request):
  if request.data != {}:
     session_id = request.data["session_id"]
     user = Customer.objects.filter(session_id=session_id)
     if user.count() != 0:
         posts = Post.objects.all().annotate(likes=Count('postlike'), i_liked=Exists(PostLike.objects.filter(user=user)))
         serializer = PostSerializer(posts, many=True)
         return Response(request, serializer.data)
</code>```

And in your serializers.py

```<code>class PostSerializer(ModelSerializer):
    # Annotated fields
    likes = IntegerField()
    i_liked = BooleanField()

    class Meta:
        model = Post
        fields = ['id', 'title', 'likes', 'i_liked']
</code>```

Body:
i have a post model and like model with ForeignKey. in API user will give the user session id . i want to show the user liked a post or not based on the session id in when i list all post . for example . when we open instagram we can as user which post we liked or not in the heart icon .

models.py

class Post(models.Model):
  title = models.CharField(max_length=150)
  image = models.FileField( upload_to="post/",)

class PostLike(models.Model):
    like = models.CharField(max_length=10)
    user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='post_likes')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')

views.py

@api_view(["POST"])
def post(request):
  if request.data != {}:
     session_id = request.data["session_id"]
     user = Customer.objects.filter(session_id=session_id)
         if user.count() != 0:
             posts = Post.objects.all()
             like_exist = PostLike.objects.filter(user = user).exists()
             serializer = PostSerializer(posts, many=True,context=
                           {"like_exist":like_exist)
             return Custom_Response(request, news_serializer.data)

serializer.py

class PostSerializer(serializers.ModelSerializer):
    like_exist = serializers.SerializerMethodField("like_exist_")

    class Meta:
        model = News
        fields  = ["title","image","like_exist"]

    def like_exist_(self,obj):
        is_liked = self.context.get("like_exist")
        return is_liked

db

post

id title image
1  1st    ""
2  2nd    ""

post_like

id like post_id user_id
1   1   1       1
2   1   2       1
3   1   1       2

if api input session_id 10000 ,it's customer 1
so i want to show like this

API

"data": [
        {
            "id": 1,
            "title": "trend post 1",
            "like_exist":true ,
        },
        {
            "id": 2,
            "title": "trend post 2",
            "like_exist": true,
        }
    ]

if it's 20000 , that's customer 2
so response should look like

"data": [
        {
            "id": 1,
            "title": "trend post 1",
            "like_exist":true ,
        },
        {
            "id": 2,
            "title": "trend post 2",
            "like_exist": false,
        }
    ]

how get this ? i think maybe it's work with model property . but how . ???

sorry for my poor english,
Thank you

Body:
If I understand you correctly, you need something like this

from django.db.models import Count, Exists

@api_view(["POST"])
def post(request):
  if request.data != {}:
     session_id = request.data["session_id"]
     user = Customer.objects.filter(session_id=session_id)
     if user.count() != 0:
         posts = Post.objects.all().annotate(likes=Count('postlike'), i_liked=Exists(PostLike.objects.filter(user=user)))
         serializer = PostSerializer(posts, many=True)
         return Response(request, serializer.data)

And in your serializers.py

class PostSerializer(ModelSerializer):
    # Annotated fields
    likes = IntegerField()
    i_liked = BooleanField()

    class Meta:
        model = Post
        fields = ['id', 'title', 'likes', 'i_liked']


问:
How to display single items from array using JS/JQuery
Its my first Question here, so be kind ^^ Im training myself some JS/Jquery/Ajax.
Short: Projekt to filter closest location of a specific company to our current postal zip.
So, here is my "work" so far: On index.php im using a simple form like this:

```<code><form id="ajaxForm">
                <input type="number" class="form-control" id="plzInput" name="plzInput" placeholder="99999"
                       aria-label="Username" aria-describedby="basic-addon1" required>
                <button type="submit" id="plzSubmit" name="plzSubmit" class="btn btn-primary">Search</button>
            </form>
</code>```

Im passing some data to ajax.php using ajax:

```<code> var request;
     $("#ajaxForm").submit(function (event) {
         event.preventDefault();
         if (request) {
             request.abort();
         }
         var $form = $(this);

         //Caching
         var $inputs = $form.find("input, select, button, textarea");

         var serializedData = $form.serialize();
         $inputs.prop("disabled", true);
         request = $.ajax({
             url: "ajax.php",
             type: "post",
             data: serializedData
         });
         request.done(function (response, textStatus, jqXHR) {
             console.log("in ajax.php geschrieben!");
             console.log(response);
             showResults(response);

         });
         request.fail(function (jqXHR, textStatus, errorThrown) {
             console.error(
                 "The following error occurred: " +
                 textStatus, errorThrown
             );
         });
         request.always(function () {
             $inputs.prop("disabled", false);
         });
     });

     function showResults(data){
         alert(data);

     }
 });
</code>```

Here the data finally getting handled using php (db queries, calculations, result). Now im struggling on how to send my resuslts from ajax.php back to index. All in all, i want to send back an array from SQLquery, and show those values into existing html inputs using js/jquery on index.php. But i don't know why the response of ajax.php isnt readable by the JS/Jquery. I think there is something wrong with php arrays vs js arrays. Is there a way to send "multiple" responses or even an array of responses?

im glad for every help!

答:
A good way to do this is by using JSON.

On the PHP side, in ajax.php, you use json_encode() to encode your array as a string.

That JSON string is then received in your Javascript AJAX as the response. There you can turn it back into an array with JSON.parse():

```<code>let array = JSON.parse(response);
</code>```

JQuery also has a shorthand for this, see:

https://api.jquery.com/jQuery.getJSON/

Body:
Its my first Question here, so be kind ^^ Im training myself some JS/Jquery/Ajax.
Short: Projekt to filter closest location of a specific company to our current postal zip.
So, here is my "work" so far: On index.php im using a simple form like this:

<form id="ajaxForm">
                <input type="number" class="form-control" id="plzInput" name="plzInput" placeholder="99999"
                       aria-label="Username" aria-describedby="basic-addon1" required>
                <button type="submit" id="plzSubmit" name="plzSubmit" class="btn btn-primary">Search</button>
            </form>

Im passing some data to ajax.php using ajax:

 var request;
     $("#ajaxForm").submit(function (event) {
         event.preventDefault();
         if (request) {
             request.abort();
         }
         var $form = $(this);

         //Caching
         var $inputs = $form.find("input, select, button, textarea");

         var serializedData = $form.serialize();
         $inputs.prop("disabled", true);
         request = $.ajax({
             url: "ajax.php",
             type: "post",
             data: serializedData
         });
         request.done(function (response, textStatus, jqXHR) {
             console.log("in ajax.php geschrieben!");
             console.log(response);
             showResults(response);

         });
         request.fail(function (jqXHR, textStatus, errorThrown) {
             console.error(
                 "The following error occurred: " +
                 textStatus, errorThrown
             );
         });
         request.always(function () {
             $inputs.prop("disabled", false);
         });
     });

     function showResults(data){
         alert(data);

     }
 });

Here the data finally getting handled using php (db queries, calculations, result). Now im struggling on how to send my resuslts from ajax.php back to index. All in all, i want to send back an array from SQLquery, and show those values into existing html inputs using js/jquery on index.php. But i don't know why the response of ajax.php isnt readable by the JS/Jquery. I think there is something wrong with php arrays vs js arrays. Is there a way to send "multiple" responses or even an array of responses?

im glad for every help!

Body:
A good way to do this is by using JSON.

On the PHP side, in ajax.php, you use json_encode() to encode your array as a string.

That JSON string is then received in your Javascript AJAX as the response. There you can turn it back into an array with JSON.parse():

let array = JSON.parse(response);

JQuery also has a shorthand for this, see:

https://api.jquery.com/jQuery.getJSON/


问:
Is there any way to get the height of a single page if you would print the page as a pdf?
I'm trying to render a pdf from dynamic content with puppeteer and react. The layouting is done in material ui for react, so page-break-before:always is not an option because i need the grid layout which is flex and wont work with page-break-before. I need to get the height of one page, so the header of the next page doesn't overflow. If i calculate where the header should be with pagewidth * Math.sqrt(2), it gives me the position value of where it actually is. But unfortunally when i go to print it it's overflowing by a few pixels and the error is getting bigger with each page. I have wondered how to fix this problem for the last 2 days. I've even tried resetting the position with a margin.

Here are some code snippets from my program which might maybe help.

```<code>let width = 800//document.documentElement.getBoundingClientRect().width
for (let pagewidth = width; pagewidth * Math.sqrt(2) < document.documentElement.getBoundingClientRect().height; pagewidth += width) {
  let pageBreakXPosition = Math.ceil(Math.sqrt(2) * pagewidth)
  header.style.marginTop = pageBreakXPosition - header.getBoundingClientRect().top + "px"
}
</code>```

this is just the "important" part of the code because all of the other code targets the elements' width or some other styles. My problem would really be fixed if i just knew the exact point where the page would break, but appareantly my calculation for pageBreakXPosition is wrong in some way.

attached is a picture of the overflow(if you look carefully you can see that the error is getting bigger):

Page 2

Page 4

答:
Use these:
`- document.height()

document.body.scrollheight

screen.height

$(document).height()`

Body:
I'm trying to render a pdf from dynamic content with puppeteer and react. The layouting is done in material ui for react, so page-break-before:always is not an option because i need the grid layout which is flex and wont work with page-break-before. I need to get the height of one page, so the header of the next page doesn't overflow. If i calculate where the header should be with pagewidth * Math.sqrt(2), it gives me the position value of where it actually is. But unfortunally when i go to print it it's overflowing by a few pixels and the error is getting bigger with each page. I have wondered how to fix this problem for the last 2 days. I've even tried resetting the position with a margin.

Here are some code snippets from my program which might maybe help.

let width = 800//document.documentElement.getBoundingClientRect().width
for (let pagewidth = width; pagewidth * Math.sqrt(2) < document.documentElement.getBoundingClientRect().height; pagewidth += width) {
  let pageBreakXPosition = Math.ceil(Math.sqrt(2) * pagewidth)
  header.style.marginTop = pageBreakXPosition - header.getBoundingClientRect().top + "px"
}

this is just the "important" part of the code because all of the other code targets the elements' width or some other styles. My problem would really be fixed if i just knew the exact point where the page would break, but appareantly my calculation for pageBreakXPosition is wrong in some way.

attached is a picture of the overflow(if you look carefully you can see that the error is getting bigger):

Page 2

Page 4


问:
Azure Data Factory Dynamic Content Filename Syntax
In a copy process going from one storage account to another I am trying to pick up the filenames in the sours and add the date to the filename in the destination so that each file copied is unique and no files are overwritten in the destination but I can't seem to get the syntax for filenames right. Welcome any suggestions on where are good examples to learn from.

Thanks

答:
Parameterize the source file name in the source dataset and get the files list using the Get Metadata activity from the source folder.

Get Metadata output:

Pass the Get Metadata output child items to ForEach activity.

@activity('Get Metadata1').output.childItems

Inside ForEach activity, add copy data activity to copy files from source to sink.

In Copy activity source, pass the current item as source file name dataset parameter.

Parameterize sink file name in sink dataset. In Copy activity sink, pass the expression to include date value in the file name.

Sink dataset:

Copy activity sink:

@concat(replace(item().name,'.csv',''),'_',formatDateTime(utcnow(),'yyyyMMdd HHmmss'),'.csv')

Output:


问:
How to deal with "java.lang.OutOfMemoryError: Java heap space" error?
I am writing a client-side Swing application (graphical font designer) on Java 5. Recently, I am running into java.lang.OutOfMemoryError: Java heap space error because I am not being conservative on memory usage. The user can open unlimited number of files, and the program keeps the opened objects in the memory. After a quick research I found Ergonomics in the 5.0 Java Virtual Machine and others saying on Windows machine the JVM defaults max heap size as 64MB.

Given this situation, how should I deal with this constraint?

I could increase the max heap size using command line option to java, but that would require figuring out available RAM and writing some launching program or script. Besides, increasing to some finite max does not ultimately get rid of the issue.

I could rewrite some of my code to persist objects to file system frequently (using database is the same thing) to free up the memory. It could work, but it's probably a lot work too.

If you could point me to details of above ideas or some alternatives like automatic virtual memory, extending heap size dynamically, that will be great.

答:
In my case it solved by assigning more memory to Shared build process heap size in intellij settings.

Go to intellij settings > Compiler > Shared build process heap size


问:
ReCaptcha gives valid as a response even when one character is skipped
I am using http://code.google.com/apis/recaptcha/docs/verify.html, Reptcha gives valid as a response even one character is skipped.</p>

答: Could this be due to it allowing a small variance in errors as the words may not always be legible?</p>


问:
Place div to the right side of the text
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

答:
The solution would be to add "flex: 0 0 auto;" on the ".first-child".

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
flex: 0 0 auto;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong <br>teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

Title: Place div to the right side of the text

Body:
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

    Loooooooong teeeeeext

    Short text

Body:
The solution would be to add "flex: 0 0 auto;" on the ".first-child".

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
flex: 0 0 auto;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

<div class="parent">
  <div class="first-child">
    <span>Loooooooong <br>teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div>


问:
Detecting folders/directories in javascript FileList objects
I have recently contributed some code to Moodle which uses some of the capabilities of HTML5 to allow files to be uploaded in forms via drag and drop from the desktop (the core part of the code is here: https://github.com/moodle/moodle/blob/master/lib/form/dndupload.js for reference).

This is working well, except for when a user drags a folder / directory instead of a real  file. Garbage is then uploaded to the server, but with the filename matching the folder.

What I am looking for is an easy and reliable way to detect the presence of a folder in the FileList object, so I can skip it (and probably return a friendly error message as well).

I've looked through the documentation on MDN, as well as a more general web search, but not turned up anything. I've also looked through the data in the Chrome developer tools and it appears that the 'type' of the File object is consistently set to "" for folders. However, I'm not quite convinced this is the most reliable, cross-browser detection method.

Does anyone have any better suggestions?

答:
An easy method is the following:

Check if the file's type is an empty string: type === ""

Check if the file's size is 0, 4096, or a multiple of it: size % 4096 === 0.

if (file.type === "" && file.size % 4096 === 0) {
    // The file is a folder
} else {
    // The file is not a folder
}
```

Note: Just by chance, there could be files without a file extension that have the size of some multiple of 4096. Even though this will not happen very often, be aware of it.

For reference, please see the great answer from user Marco Bonelli to a similar topic. This is just a short summary of it.

Body:
An easy method is the following:

Check if the file's type is an empty string: type === ""

Check if the file's size is 0, 4096, or a multiple of it: size % 4096 === 0.

if (file.type === "" && file.size % 4096 === 0) {
    // The file is a folder
} else {
    // The file is not a folder
}

Note: Just by chance, there could be files without a file extension that have the size of some multiple of 4096. Even though this will not happen very often, be aware of it.

For reference, please see the great answer from user Marco Bonelli to a similar topic. This is just a short summary of it.


问:
set dotnet core version using azure cli in azure windows webapp
We have windows webapp in Azure, we want to change the stack to dotnet core version(3.1,2.1) using Azure cli.
If it is a linux webapp, we can use az webapp config set -g $group -n $webappName --linux-fx-version "DOTNETCORE|2.1". But for windows couldn't find anything. Help is appreciated.
Thank you!

答:
Using the below powershell script, am able to achieve this.

```<code>Set-AzWebApp -ResourceGroupName 'MyRG' -Name 'MyWebApp' -AppServicePlan ' MyWebAppPlan'
$PropertiesObject = @{"CURRENT_STACK" = "dotnetcore"}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName 'MyRG' -ResourceType Microsoft.Web/sites/config/metadata -ResourceName 'MyWebApp' -ApiVersion 2021-03-01 -Force
</code>```

Refer this github issue for more information:- https://github.com/Azure/azure-cli/issues/21192

Body:
Using the below powershell script, am able to achieve this.

Set-AzWebApp -ResourceGroupName 'MyRG' -Name 'MyWebApp' -AppServicePlan ' MyWebAppPlan'
$PropertiesObject = @{"CURRENT_STACK" = "dotnetcore"}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName 'MyRG' -ResourceType Microsoft.Web/sites/config/metadata -ResourceName 'MyWebApp' -ApiVersion 2021-03-01 -Force

Refer this github issue for more information:- https://github.com/Azure/azure-cli/issues/21192


问:
How to dynamically access a remote component in vue js with module federation
I am trying to build a vue js 2 microfrontend with module federation. I dont want to use static remote imports via the webpack.config.js like this

```<code>module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'host',
      remotes: {
        app1: 'app1@http://localhost:3001/remoteEntry.js',
      },
    }),
  ],
};
</code>```

I am looking for a way to dynamically import vue components into my host application. I tried this approach so far, but i only found examples that worked with angular or react.

The goal is to have multiple remote frontends that can automatically register somewhere, maybe in some kind of store. The host application then can access this store and get all of the registered remote applications (name, url, components). The host application then loads the components and should be able to use them. I remote import the component HelloDerp, the loading process is working fine but i dont know how to render it on my host application. I read the vue js doc about dynamic and async imports but i think that only works for local components.
What i've got so far in the host application:

```<code><template>
  <div id="app">
    <HelloWorld />
    <HelloDerp />
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
const HelloDerp = null;

export default {
  name: "App",
  components: {
    HelloWorld,
    HelloDerp,
  },
  mounted() {
    var remoteUrlWithVersion = "http://localhost:9000/remoteEntry.js";
    const element = document.createElement("script");

    element.type = "text/javascript";
    element.async = true;
    element.src = remoteUrlWithVersion;
    element.onload = () => {
      console.log(`Dynamic Script Loaded: ${element.src}`);
      HelloDerp = loadComponent("core", "./HelloDerp");
    };

    document.head.appendChild(element);

    return null;
  },
};

async function loadComponent(scope, module) {
  // Initializes the shared scope. Fills it with known provided modules from this build and all remotes
  await __webpack_init_sharing__("default");
  const container = window[scope]; // or get the container somewhere else
  // Initialize the container, it may provide shared modules
  await container.init(__webpack_share_scopes__.default);
  const factory = await window[scope].get(module);
  const Module = factory();
  return Module;
}
</script>
</code>```

答:
Sorry i almost forgot about this. Here's my solution.

Load Modules:

```<code>export default async function loadModules(
  host: string,
  ownModuleName: string,
  wantedNames: string[]
): Promise<RemoteComponent[]> {
    ...
    uiApplications.forEach((uiApplication) => {
      const remoteURL = `${uiApplication.protocol}://${uiApplication.host}:${uiApplication.port}/${uiApplication.moduleName}/${uiApplication.fileName}`;

      const { componentNames } = uiApplication;
      const { moduleName } = uiApplication;
      const element = document.createElement('script');
      element.type = 'text/javascript';
      element.async = true;
      element.src = remoteURL;

      element.onload = () => {
        componentNames?.forEach((componentName) => {
          const component = loadModule(moduleName, `./${componentName}`);

          component.then((result) => {
            if (componentName.toLowerCase().endsWith('view')) {
            // share views
              components.push(new RemoteComponent(result.default, componentName));
            } else {
            // share business logic
              components.push(new RemoteComponent(result, componentName));
            }
           });
        });
      };
      document.head.appendChild(element);
    });
  });
  ...
}

export default async function loadModule(scope: string, module: string): Promise<any> {
  await __webpack_init_sharing__('default');
  const container = window[scope]; // or get the container somewhere else
  await container.init(__webpack_share_scopes__.default);
  const factory = await window[scope].get(module);
  const Module = factory();
  return Module;
}
</code>```

Add Modules to routes

```<code> router.addRoute({
        name: remoteComponent.componentName,
        path: `/${remoteComponent.componentName}`,
        component: remoteComponent.component,
  });
</code>```

Body:
I am trying to build a vue js 2 microfrontend with module federation. I dont want to use static remote imports via the webpack.config.js like this

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'host',
      remotes: {
        app1: 'app1@http://localhost:3001/remoteEntry.js',
      },
    }),
  ],
};

I am looking for a way to dynamically import vue components into my host application. I tried this approach so far, but i only found examples that worked with angular or react.

The goal is to have multiple remote frontends that can automatically register somewhere, maybe in some kind of store. The host application then can access this store and get all of the registered remote applications (name, url, components). The host application then loads the components and should be able to use them. I remote import the component HelloDerp, the loading process is working fine but i dont know how to render it on my host application. I read the vue js doc about dynamic and async imports but i think that only works for local components.
What i've got so far in the host application:

<template>

    <HelloWorld />
    <HelloDerp />

</template>

Body:
Sorry i almost forgot about this. Here's my solution.

Load Modules:

export default async function loadModules(
  host: string,
  ownModuleName: string,
  wantedNames: string[]
): Promise<RemoteComponent[]> {
    ...
    uiApplications.forEach((uiApplication) => {
      const remoteURL = `${uiApplication.protocol}://${uiApplication.host}:${uiApplication.port}/${uiApplication.moduleName}/${uiApplication.fileName}`;

      const { componentNames } = uiApplication;
      const { moduleName } = uiApplication;
      const element = document.createElement('script');
      element.type = 'text/javascript';
      element.async = true;
      element.src = remoteURL;

      element.onload = () => {
        componentNames?.forEach((componentName) => {
          const component = loadModule(moduleName, `./${componentName}`);

          component.then((result) => {
            if (componentName.toLowerCase().endsWith('view')) {
            // share views
              components.push(new RemoteComponent(result.default, componentName));
            } else {
            // share business logic
              components.push(new RemoteComponent(result, componentName));
            }
           });
        });
      };
      document.head.appendChild(element);
    });
  });
  ...
}

export default async function loadModule(scope: string, module: string): Promise<any> {
  await __webpack_init_sharing__('default');
  const container = window[scope]; // or get the container somewhere else
  await container.init(__webpack_share_scopes__.default);
  const factory = await window[scope].get(module);
  const Module = factory();
  return Module;
}

Add Modules to routes

 router.addRoute({
        name: remoteComponent.componentName,
        path: `/${remoteComponent.componentName}`,
        component: remoteComponent.component,
  });


问:
Empty fields not included on form submit when using Angular Formly
Using Angular Formly I've setup the following controller and template. I get the controller to print the values that the user has entered into all the fields, except those that the user hasn't touched. This means that if the user doesn't write anything at all in a field, that field is not included. Though if the user enters something and then deletes it, the field is included with an empty string.

How do I include the fields that the user hasn't touched?

```<code>// fooController.js

vm.fooModel= {};
vm.fooFields = [
    {
        key: 'foo',
        type: 'input'
        templateOptions: {
            label: 'Foo',
            placeholder: 'Foo'
        }
    }
];

vm.onSubmit = function() {
    console.log(vm.fooModel)
}
</code>```

```<code>// fooTemplate.html

<form ng-submit="vm.onSubmit()" novalidate>
    <formly-form model="vm.fooModel" fields="vm.fooFields"></formly-form>
    <button type="submit" class="btn btn-info submit-button">Submit</button>
</form>
</code>```

I would prefer not to set the empty string as a default value for every single field.

A simple example can be found here

答:
you can get field and set property of it with what you want
in your case, it will be like</p>
```<code>this.fooFields.get('fieldName').setValue('');
</code>```

Body:
Using Angular Formly I've setup the following controller and template. I get the controller to print the values that the user has entered into all the fields, except those that the user hasn't touched. This means that if the user doesn't write anything at all in a field, that field is not included. Though if the user enters something and then deletes it, the field is included with an empty string.

How do I include the fields that the user hasn't touched?

// fooController.js

vm.fooModel= {};
vm.fooFields = [
    {
        key: 'foo',
        type: 'input'
        templateOptions: {
            label: 'Foo',
            placeholder: 'Foo'
        }
    }
];

vm.onSubmit = function() {
    console.log(vm.fooModel)
}

// fooTemplate.html

<form ng-submit="vm.onSubmit()" novalidate>
    <formly-form model="vm.fooModel" fields="vm.fooFields"></formly-form>
    <button type="submit" class="btn btn-info submit-button">Submit</button>
</form>

I would prefer not to set the empty string as a default value for every single field.

A simple example can be found here

Body:
you can get field and set property of it with what you want
in your case, it will be like

this.fooFields.get('fieldName').setValue('');


问:
NotFound: 404 Not Found (error code: 10007): Unknown Member
```<code>    @commands.command(name='rostercheck', aliases=['rc'])
    async def rostercheck(self, ctx, dept_name):
        for dept_name in self.roster.keys():
            print(dept_name)
            google_sheet = await self.get_roster_sheet(dept_name)
            print(google_sheet)
            for value_list in google_sheet.get("values"):
                print(value_list)
                if len(value_list) != 1 or value_list is None or "Discord ID" in value_list:
                    continue
                value = value_list[0]
                print(value)
                discord_server = await self.bot.fetch_guild(int(self.guild_metadata.get(dept_name)))
                print(discord_server)
                discord_member = await discord_server.fetch_member(int(value))
                print(discord_member)
                if discord_member is None:
                    my_chan = self.bot.get_channel(self.channel_metadata.get(dept_name).get("roster_check"))
                    print(my_chan)
                    await self.send_message(f"{value} - is not in the {dept_name} discord, are you sure they are still in your department?", my_chan)
</code>```

I have ensured it prints everything correctly, so it goes through all the discordid from the google sheets, and then searches them in the discord. But as soon as it reaches someone who isn't in the discord it gets this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10007): Unknown Member

Then the code just breaks and the rostercheck command just breaks. I can't find any solutions regarding this on this website or in the documentation.

答:
You can use the in-built discord.py error handling mechanism to do something else when the exception occurs.

@rostercheck.error
async def please_dont_break_my_code(self, ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        # Do something here
        pass
```

However, the better solution in your case is to use a try-except block which is how it is done in vanilla python.

Body:
    @commands.command(name='rostercheck', aliases=['rc'])
    async def rostercheck(self, ctx, dept_name):
        for dept_name in self.roster.keys():
            print(dept_name)
            google_sheet = await self.get_roster_sheet(dept_name)
            print(google_sheet)
            for value_list in google_sheet.get("values"):
                print(value_list)
                if len(value_list) != 1 or value_list is None or "Discord ID" in value_list:
                    continue
                value = value_list[0]
                print(value)
                discord_server = await self.bot.fetch_guild(int(self.guild_metadata.get(dept_name)))
                print(discord_server)
                discord_member = await discord_server.fetch_member(int(value))
                print(discord_member)
                if discord_member is None:
                    my_chan = self.bot.get_channel(self.channel_metadata.get(dept_name).get("roster_check"))
                    print(my_chan)
                    await self.send_message(f"{value} - is not in the {dept_name} discord, are you sure they are still in your department?", my_chan)

I have ensured it prints everything correctly, so it goes through all the discordid from the google sheets, and then searches them in the discord. But as soon as it reaches someone who isn't in the discord it gets this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10007): Unknown Member

Then the code just breaks and the rostercheck command just breaks. I can't find any solutions regarding this on this website or in the documentation.

Body:
You can use the in-built discord.py error handling mechanism to do something else when the exception occurs.

@rostercheck.error
async def please_dont_break_my_code(self, ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        # Do something here
        pass

However, the better solution in your case is to use a try-except block which is how it is done in vanilla python.


问:
Camunda Rest - fetch variables of a completed process instance
I am trying to build an audit trail and print information of the users path to the task completion + some data are written in variables.

There are some history endpoints from camunda Rest that can provide every “node” which the task went through.

But there are some extra information in process instance variables that I need but when I try to fetch variables from a process instance that is already completed the API answers with “no process instance with id:xxxx found”

Is there a way to read information in the variables of a completed task so ?

Thank you in advance

答:
When a process instance is completed, its data is removed from the runtime tables, which are accessed by the endpoint you are using for the running instance. All information regarding completed process instances needs to be fetched using the history endpoint (the underlying API accesses the history tables).
https://docs.camunda.org/manual/7.16/reference/rest/history/

This endpoint using the query parameter processInstanceId will return the data of a completed instance:
https://docs.camunda.org/manual/7.16/reference/rest/history/variable-instance/get-variable-instance-query/

Example request:

```<code>curl -X GET "http://localhost:8080/engine-rest/history/variable-instance?processInstanceId=5487fe88-72d2-11ec-b607-0242ac110002" -H  "accept: application/json"
</code>```

Example response:

```<code>[
  {
    "type": "String",
    "value": "GPFE-23232323",
    "valueInfo": {},
    "id": "54890ff9-72d2-11ec-b607-0242ac110002",
    "name": "invoiceNumber",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:42.862+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  },
  {
    "type": "String",
    "value": "Travel Expenses",
    "valueInfo": {},
    "id": "5489ac44-72d2-11ec-b607-0242ac110002",
    "name": "invoiceCategory",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:42.865+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  },
  {
    "type": "Object",
    "value": [
      "accounting",
      "sales"
    ],
    "valueInfo": {
      "objectTypeName": "java.util.ArrayList",
      "serializationDataFormat": "application/x-java-serialized-object"
    },
    "id": "54a6aa32-72d2-11ec-b607-0242ac110002",
    "name": "approverGroups",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:43.055+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  }
]
</code>```

Body:
When a process instance is completed, its data is removed from the runtime tables, which are accessed by the endpoint you are using for the running instance. All information regarding completed process instances needs to be fetched using the history endpoint (the underlying API accesses the history tables).
https://docs.camunda.org/manual/7.16/reference/rest/history/

This endpoint using the query parameter processInstanceId will return the data of a completed instance:
https://docs.camunda.org/manual/7.16/reference/rest/history/variable-instance/get-variable-instance-query/

Example request:

curl -X GET "http://localhost:8080/engine-rest/history/variable-instance?processInstanceId=5487fe88-72d2-11ec-b607-0242ac110002" -H  "accept: application/json"

Example response:

[
  {
    "type": "String",
    "value": "GPFE-23232323",
    "valueInfo": {},
    "id": "54890ff9-72d2-11ec-b607-0242ac110002",
    "name": "invoiceNumber",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:42.862+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  },
  {
    "type": "String",
    "value": "Travel Expenses",
    "valueInfo": {},
    "id": "5489ac44-72d2-11ec-b607-0242ac110002",
    "name": "invoiceCategory",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:42.865+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  },
  {
    "type": "Object",
    "value": [
      "accounting",
      "sales"
    ],
    "valueInfo": {
      "objectTypeName": "java.util.ArrayList",
      "serializationDataFormat": "application/x-java-serialized-object"
    },
    "id": "54a6aa32-72d2-11ec-b607-0242ac110002",
    "name": "approverGroups",
    "processDefinitionKey": "invoice",
    "processDefinitionId": "invoice:1:53c23d7a-72d2-11ec-b607-0242ac110002",
    "processInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "executionId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "activityInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002",
    "caseDefinitionKey": null,
    "caseDefinitionId": null,
    "caseInstanceId": null,
    "caseExecutionId": null,
    "taskId": null,
    "errorMessage": null,
    "tenantId": null,
    "state": "CREATED",
    "createTime": "2022-01-11T11:33:43.055+0000",
    "removalTime": null,
    "rootProcessInstanceId": "5487fe88-72d2-11ec-b607-0242ac110002"
  }
]


问:
How do you explicitly set a new property on `window` in TypeScript?
I setup global namespaces for my objects by explicitly setting a property on window.

```<code>window.MyNamespace = window.MyNamespace || {};
</code>```

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window'
  any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

```<code>declare var MyNamespace: any;

MyNamespace = MyNamespace || {};
</code>```

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.

答:
I use without declarate.
My example looks like:

Body:
I setup global namespaces for my objects by explicitly setting a property on window.

window.MyNamespace = window.MyNamespace || {};

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window'
  any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

declare var MyNamespace: any;

MyNamespace = MyNamespace || {};

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.


问:
Http request in clojurescript with re-frame
I use Clojurescript + Reframe + http-fx.
This is example src for http request:

```<code>(re-frame/reg-event-fx
 ::request-login
 (fn [{:keys [db]} [_ req-data]]
   {:db   (assoc db :loading true)
    :http-xhrio {:method          :post
                 :uri             "http://localhost:8002/api/auth/login"
                 :params          req-data
                 :timeout         8000
                 :format          (ajax/json-request-format)
                 :response-format (ajax/json-response-format {:keywords? true})
                 :on-success      [::response-login-success]
                 :on-failure      [:bad-http-result]}}))
</code>```

My dev shadow-cljs works on http://localhost:8280/

But my api server on http://localhost:8002/ (this is other application).

The library does not allow me to make requests to servers at other addresses.
Only for (:uri "http://localhost:8280/api/auth/login")

In browser inspector displays: Provisional headers are shown! This is due to the referrer parameter in header, as I understand it.

I tryed:

```<code> :uri     "http://localhost:8002/api/auth/login"
 :params  req-data
 :headers {"referer" "http://localhost:8002/" "origin" "http://localhost:8002"}
</code>```

It does not help!
I found information that it is necessary to do not an asynchronous request.

I was able to run only this solution (call JS function from Clojurescript):

```<code>function myAjaxPost() {
    const xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://localhost:8002/api/auth/login", false);
    xhttp.send(JSON.stringify({login:"user1",password:"pswd1"}));
    console.log(xhttp.responseText);
};

</code>```

But How it is possible to set async mode for http-fx?

It is possible to make requests for a different URLs?

答:
I solved this problem. The problem was with the server.
Enabled on the server: Enable All CORS Requests.
And everything worked!!!
Maybe this will help someone.</p>

Body:
I use Clojurescript + Reframe + http-fx.
This is example src for http request:

(re-frame/reg-event-fx
 ::request-login
 (fn [{:keys [db]} [_ req-data]]
   {:db   (assoc db :loading true)
    :http-xhrio {:method          :post
                 :uri             "http://localhost:8002/api/auth/login"
                 :params          req-data
                 :timeout         8000
                 :format          (ajax/json-request-format)
                 :response-format (ajax/json-response-format {:keywords? true})
                 :on-success      [::response-login-success]
                 :on-failure      [:bad-http-result]}}))

My dev shadow-cljs works on http://localhost:8280/

But my api server on http://localhost:8002/ (this is other application).

The library does not allow me to make requests to servers at other addresses.
Only for (:uri "http://localhost:8280/api/auth/login")

In browser inspector displays: Provisional headers are shown! This is due to the referrer parameter in header, as I understand it.

I tryed:

 :uri     "http://localhost:8002/api/auth/login"
 :params  req-data
 :headers {"referer" "http://localhost:8002/" "origin" "http://localhost:8002"}

It does not help!
I found information that it is necessary to do not an asynchronous request.

I was able to run only this solution (call JS function from Clojurescript):

function myAjaxPost() {
    const xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://localhost:8002/api/auth/login", false);
    xhttp.send(JSON.stringify({login:"user1",password:"pswd1"}));
    console.log(xhttp.responseText);
};

But How it is possible to set async mode for http-fx?

It is possible to make requests for a different URLs?


问:
Select one Particular sheet instead of listing all the sheets. Google app script, Code
I got this code from here : Display Spreadsheet Data to HTML Table

thanks to the great work of Cooper.

```<code>function htmlSpreadsheet(ssO) {
  var br='<br />';
  var s='';
  var hdrRows=1;
  var ss=SpreadsheetApp.openById(ssO.id);
  var sht=ss.getSheetByName(ssO.name);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  s+='<table>';
  for(var i=0;i<rngA.length;i++)
  {
    s+='<tr>';
    for(var j=0;j<rngA[i].length;j++)
    {
      if(i<hdrRows)
      {
        s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
      else
      {
        s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
      }
    }
    s+='</tr>';
  }
  s+='</table>';
  s+='</body></html>';
  var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
  var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
  var opO={hl:s,name:namehl,shname:shnamehl};
  return opO;
}

function updateSpreadsheet(updObj) {
  var i=updObj.rowIndex;
  var j=updObj.colIndex;
  var value=updObj.value;
  var ss=SpreadsheetApp.openById(updObj.id);
  var sht=ss.getSheetByName(updObj.name);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  rngA[i][j]=value;
  rng.setValues(rngA);
  var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
  return data;
}

function doGet() {
  var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
  return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

function getAllSpreadSheets() {
  var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  var s = '';
  var vA=[['Select Spreadsheet',0]];
  while(files.hasNext())
  {
    var file = files.next();
    var fileName=file.getName();
    var fileId=file.getId();
    vA.push([fileName,fileId]);
  }
  //return vA;
  return {array:vA,type:'sel1'};
}

//working on this function right now 2017/11/08
function getAllSheets(ssO) {
  var ss=SpreadsheetApp.openById(ssO.id);
  var allSheets=ss.getSheets();
  var vA=[['Select Sheet']];
  for(var i=0;i<allSheets.length;i++)
  {
    var name=allSheets[i].getName();
    vA.push([name]);
  }
  return {array:vA,type:'sel2'};
}
</code>```

What I am trying to do is on a Single sheet. That is I don't want to browse all sheets and select among them~

I have tried modifying this code

```<code>function getAllSpreadSheets() {
  var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  var s = '';
 // var vA=[['Select Spreadsheet',0]];
  while(files.hasNext())
  {
  //  var file = files.next();
    var fileName=file.getName();
    var fileId=file.getId();
    vA.push([fileName,fileId]);
  }
  //return vA;
  return {array:vA,type:'sel1'};
}
</code>```

I have used sheet Id instead of file.getId(), But It just don't work.
Please help me.

答:
Change:

```<code>var files = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS)
</code>```

To getFileById():

```<code>var file = DriveApp.getFileById("sheet Id");
</code>```

Then remove the loop:

```<code>function getSingleSpreadSheet() {
  var file = DriveApp.getFileById("sheet Id")
  var fileName = file.getName()
  var fileId = file.getId()
  var vA = []
  vA.push([fileName, fileId])

  return {
    array: vA,
    type:'sel1'
  }
}
</code>```

Body:
I got this code from here : Display Spreadsheet Data to HTML Table

thanks to the great work of Cooper.

function htmlSpreadsheet(ssO) {
  var br='
';
  var s='';
  var hdrRows=1;
  var ss=SpreadsheetApp.openById(ssO.id);
  var sht=ss.getSheetByName(ssO.name);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  s+='
';
  for(var i=0;i<rngA.length;i++)
  {
    s+='
';
    for(var j=0;j<rngA[i].length;j++)
    {
      if(i<hdrRows)
      {
        s+='' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '	';
      }
      else
      {
        s+='' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '	';
      }
    }
    s+='
';
  }
  s+='
';
  s+='';
  var namehl=Utilities.formatString('
%s
', ss.getName());
  var shnamehl=Utilities.formatString('
%s
', sht.getName());
  var opO={hl:s,name:namehl,shname:shnamehl};
  return opO;
}

function updateSpreadsheet(updObj) {
  var i=updObj.rowIndex;
  var j=updObj.colIndex;
  var value=updObj.value;
  var ss=SpreadsheetApp.openById(updObj.id);
  var sht=ss.getSheetByName(updObj.name);
  var rng=sht.getDataRange();
  var rngA=rng.getValues();
  rngA[i][j]=value;
  rng.setValues(rngA);
  var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
  return data;
}

function doGet() {
  var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
  return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

function getAllSpreadSheets() {
  var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  var s = '';
  var vA=[['Select Spreadsheet',0]];
  while(files.hasNext())
  {
    var file = files.next();
    var fileName=file.getName();
    var fileId=file.getId();
    vA.push([fileName,fileId]);
  }
  //return vA;
  return {array:vA,type:'sel1'};
}

//working on this function right now 2017/11/08
function getAllSheets(ssO) {
  var ss=SpreadsheetApp.openById(ssO.id);
  var allSheets=ss.getSheets();
  var vA=[['Select Sheet']];
  for(var i=0;i<allSheets.length;i++)
  {
    var name=allSheets[i].getName();
    vA.push([name]);
  }
  return {array:vA,type:'sel2'};
}

What I am trying to do is on a Single sheet. That is I don't want to browse all sheets and select among them~

I have tried modifying this code

function getAllSpreadSheets() {
  var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
  var s = '';
 // var vA=[['Select Spreadsheet',0]];
  while(files.hasNext())
  {
  //  var file = files.next();
    var fileName=file.getName();
    var fileId=file.getId();
    vA.push([fileName,fileId]);
  }
  //return vA;
  return {array:vA,type:'sel1'};
}

I have used sheet Id instead of file.getId(), But It just don't work.
Please help me.

Body:
Change:

var files = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS)

To getFileById():

var file = DriveApp.getFileById("sheet Id");

Then remove the loop:

function getSingleSpreadSheet() {
  var file = DriveApp.getFileById("sheet Id")
  var fileName = file.getName()
  var fileId = file.getId()
  var vA = []
  vA.push([fileName, fileId])

  return {
    array: vA,
    type:'sel1'
  }
}


问:
Specify a default empty DataTemplate instead of the default 'ToString()' DataTemplate
The default DataTemplate in a wpf application displays the result of the .ToString() method. I'm developing an application where the default DataTemplate should display nothing.

I've tried:

```<code><Grid.Resources>
  <DataTemplate DataType="{x:Type System:Object}">
   <Grid></Grid>
  </DataTemplate>
</Grid.Resources>
</code>```

But this doesn't work. Does anyone knows if this is possible without specifiing a specific DataTemplate for every class type in the application?

答:
I know of no way to do this. As per Joe's comment below, WPF specifically disallows specifying a DataTemplate for type Object.

Depending on your exact requirements, it may be easier to search for a DataTemplate that matches the specific type. If you find one, use it. Otherwise, display nothing. For example:

```<code><ContentControl Content="{Binding YourContent}" ContentTemplateSelector="{StaticResource MyContentTemplateSelector}"/>
</code>```

And in your selector (pseudo-code, obviously):

```<code>var dataTemplateKey = new DataTemplateKey() { DataType = theType; };
var dataTemplate = yourControl.FindResource(dataTemplateKey);

if (dataTemplate != null)
{
    return dataTemplate;
}

return NulloDataTemplate;
</code>```

Body:
The default DataTemplate in a wpf application displays the result of the .ToString() method. I'm developing an application where the default DataTemplate should display nothing.

I've tried:

<Grid.Resources>
  <DataTemplate DataType="{x:Type System:Object}">
   <Grid></Grid>
  </DataTemplate>
</Grid.Resources>

But this doesn't work. Does anyone knows if this is possible without specifiing a specific DataTemplate for every class type in the application?

Body:
I know of no way to do this. As per Joe's comment below, WPF specifically disallows specifying a DataTemplate for type Object.

Depending on your exact requirements, it may be easier to search for a DataTemplate that matches the specific type. If you find one, use it. Otherwise, display nothing. For example:

<ContentControl Content="{Binding YourContent}" ContentTemplateSelector="{StaticResource MyContentTemplateSelector}"/>

And in your selector (pseudo-code, obviously):

var dataTemplateKey = new DataTemplateKey() { DataType = theType; };
var dataTemplate = yourControl.FindResource(dataTemplateKey);

if (dataTemplate != null)
{
    return dataTemplate;
}

return NulloDataTemplate;

OwnerDisplayName: Kent Boogaart


问:
Playwright with python - Download file from CloudFlare
I'm trying to download this file from CloudFlare using PlayWright in Python:
https://www.historique-meteo.net/site/export.php?ville_id=1067

But impossible to succeed...
Could you have any idea to help please ?

Note: there is no click to perform the download, just wait for 5 seconds for JS auto check

Here is my code:

```<code>from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context(accept_downloads=True)

    # Open new page
    page = context.new_page()

    # Go to site
    page.goto("https://www.historique-meteo.net/site/export.php?ville_id=1067")

    # Download
    page.on("download", lambda download: download.save_as(download.suggested_filename))

    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)
</code>```

Thanks a lot ! :)

答:
Not guaranteed for success. Change the parameters in function async_cf_retry if it tends to fail. I wrote this code by modifying my heavy modules, so it may not work elegantly.

import re
import asyncio
from playwright.async_api import async_playwright, Error, Page
from cf_clearance import stealth_async
import httpx

# local_client = httpx.AsyncClient(verify=False)

async def async_cf_retry(page: Page, tries=10) -> bool:
    # use tries=-1 for infinite retries
    # excerpted from `from cf_clearance import async_retry`
    success = False
    while tries != 0:
        try:
            title = await page.title()
        except Error:
            tries -= 1
            await asyncio.sleep(1)
        else:
            # print(title)
            if title == 'Please Wait... | Cloudflare':
                await page.close()
                raise NotImplementedError('Encountered recaptcha. Check whether your proxy is an elite proxy.')
            elif title == 'Just a moment...':
                tries -= 1
                await asyncio.sleep(5)
            elif "www." in title:
                await page.reload()
                tries -= 1
                await asyncio.sleep(5)
            else:
                success = True
                break
    return success

async def get_client_with_clearance(proxy: str = None):
    async def get_one_clearance(proxy=proxy, logs=False):
        # proxy = {"server": "socks5://localhost:7890"}
        if type(proxy) is str:
            proxy = {'server': proxy}
        async with async_playwright() as p:
            browser = await p.chromium.launch(headless=False, proxy=proxy,
                                              args=["--window-position=1000,800", "--disable-web-security",
                                                    "--disable-webgl"])
            page = await browser.new_page()#viewport={"width": 0, "height": 0})
            await stealth_async(page)

            # Download
            async def on_download(download):
                print('download', download)
                await download.save_as(download.suggested_filename)
            page.on("download", on_download)

            if logs:
                def log_response(intercepted_response):
                    print("a response was received:", intercepted_response.url)

                page.on("response", log_response)

            await page.goto("https://www.historique-meteo.net/site/export.php?ville_id=1067")
            res = await async_cf_retry(page)
            if res:
                cookies = await page.context.cookies()
                cookies_for_httpx = {cookie['name']: cookie['value'] for cookie in cookies}
                ua = await page.evaluate('() => {return navigator.userAgent}')
                # print(ua)
            else:
                await page.close()
                raise InterruptedError("cf challenge fail")
            await asyncio.sleep(10000)
            return ua, cookies_for_httpx

    ua, cookies_for_httpx = await get_one_clearance(logs=True)
    print(cookies_for_httpx)

print(asyncio.get_event_loop().run_until_complete(get_client_with_clearance(
    # proxy='http://localhost:8888'
    # use proxifier on windows as an elite proxy
)))

```

If download <Download url='https://www.historique-meteo.net/site/export.php?ville_id=1067' suggested_filename='export-aix-les-bains.csv'> is shown in the console, the browser must be downloading your file.

This code may keep trying to get a cloudflare clearance even if the file has been downloaded. Edit your strategies in async_cf_retry if this happens.

Use persisent context offered by playwright to save and reuse your cloudflare clearance. Consider downloading with httpx.

Body:
I'm trying to download this file from CloudFlare using PlayWright in Python:
https://www.historique-meteo.net/site/export.php?ville_id=1067

But impossible to succeed...
Could you have any idea to help please ?

Note: there is no click to perform the download, just wait for 5 seconds for JS auto check

Here is my code:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context(accept_downloads=True)

    # Open new page
    page = context.new_page()

    # Go to site
    page.goto("https://www.historique-meteo.net/site/export.php?ville_id=1067")

    # Download
    page.on("download", lambda download: download.save_as(download.suggested_filename))

    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

Thanks a lot ! :)

Body:
Not guaranteed for success. Change the parameters in function async_cf_retry if it tends to fail. I wrote this code by modifying my heavy modules, so it may not work elegantly.

import re
import asyncio
from playwright.async_api import async_playwright, Error, Page
from cf_clearance import stealth_async
import httpx

# local_client = httpx.AsyncClient(verify=False)

async def async_cf_retry(page: Page, tries=10) -> bool:
    # use tries=-1 for infinite retries
    # excerpted from `from cf_clearance import async_retry`
    success = False
    while tries != 0:
        try:
            title = await page.title()
        except Error:
            tries -= 1
            await asyncio.sleep(1)
        else:
            # print(title)
            if title == 'Please Wait... | Cloudflare':
                await page.close()
                raise NotImplementedError('Encountered recaptcha. Check whether your proxy is an elite proxy.')
            elif title == 'Just a moment...':
                tries -= 1
                await asyncio.sleep(5)
            elif "www." in title:
                await page.reload()
                tries -= 1
                await asyncio.sleep(5)
            else:
                success = True
                break
    return success

async def get_client_with_clearance(proxy: str = None):
    async def get_one_clearance(proxy=proxy, logs=False):
        # proxy = {"server": "socks5://localhost:7890"}
        if type(proxy) is str:
            proxy = {'server': proxy}
        async with async_playwright() as p:
            browser = await p.chromium.launch(headless=False, proxy=proxy,
                                              args=["--window-position=1000,800", "--disable-web-security",
                                                    "--disable-webgl"])
            page = await browser.new_page()#viewport={"width": 0, "height": 0})
            await stealth_async(page)

            # Download
            async def on_download(download):
                print('download', download)
                await download.save_as(download.suggested_filename)
            page.on("download", on_download)

            if logs:
                def log_response(intercepted_response):
                    print("a response was received:", intercepted_response.url)

                page.on("response", log_response)

            await page.goto("https://www.historique-meteo.net/site/export.php?ville_id=1067")
            res = await async_cf_retry(page)
            if res:
                cookies = await page.context.cookies()
                cookies_for_httpx = {cookie['name']: cookie['value'] for cookie in cookies}
                ua = await page.evaluate('() => {return navigator.userAgent}')
                # print(ua)
            else:
                await page.close()
                raise InterruptedError("cf challenge fail")
            await asyncio.sleep(10000)
            return ua, cookies_for_httpx

    ua, cookies_for_httpx = await get_one_clearance(logs=True)
    print(cookies_for_httpx)

print(asyncio.get_event_loop().run_until_complete(get_client_with_clearance(
    # proxy='http://localhost:8888'
    # use proxifier on windows as an elite proxy
)))

If download <Download url='https://www.historique-meteo.net/site/export.php?ville_id=1067' suggested_filename='export-aix-les-bains.csv'> is shown in the console, the browser must be downloading your file.

This code may keep trying to get a cloudflare clearance even if the file has been downloaded. Edit your strategies in async_cf_retry if this happens.

Use persisent context offered by playwright to save and reuse your cloudflare clearance. Consider downloading with httpx.