问:
Alembic Revision Autogenerate Didn't Recognized The Default Value Change
I was testing Alembic.
Initially I created a model something like this:

from main import Base
from sqlalchemy import Column, BigInteger, SmallInteger, String, Sequence, ForeignKey

class Users(Base):
    __tablename__ = "users"

    id = Column(BigInteger, Sequence("user_id_seq"),
                primary_key=True)
    first_name = Column(String(50))
    last_name = Column(String(50))
    email = Column(String(255))
    password = Column(String(60), nullable=True)
```
<p>Then I created the revision in alembic and it worked absolutely fine and I got the result properly.
Then I added the user types table and then my models looked like this,</p>
<pre class="lang-py prettyprint-override"><code>from main import Base
from sqlalchemy import Column, BigInteger, SmallInteger, String, Sequence, ForeignKey

class Users(Base):
    __tablename__ = "users"

    id = Column(BigInteger, Sequence("user_id_seq"),
                primary_key=True)
    first_name = Column(String(50))
    last_name = Column(String(50))
    email = Column(String(255))
    password = Column(String(60), nullable=True)
    user_type = Column(SmallInteger, ForeignKey(
        "user_types.id", name="fk_user_type"))

class UserTypes(Base):
    __tablename__ = "user_types"

    id = Column(SmallInteger, Sequence("user_types_id_seq"),
                primary_key=True)
    type = Column(String(20))
</code>```

Now I created the revision for this and obviously that also worked.
But then I thought that lets make the user_type default value 1. So I did a small change in Users model and added default value 1:

user_type = Column(SmallInteger, ForeignKey(
        "user_types.id", name="fk_user_type"), default=1)
```
<p>Now ideally if I created migration it should work. But it gave me the blank file:</p>
<pre class="lang-py prettyprint-override"><code>"""Made Default Value Of user_type 1

Revision ID: 054b79123431
Revises: 84bc1adb3e66
Create Date: 2022-12-28 17:20:06.757224

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '054b79123431'
down_revision = '84bc1adb3e66'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

</code>```

I also tried to add compare_server_default=True in the context.configure calls in both offline and online migration function as it was said in an answer I found on internet which was related to the same issue but that also didnt worked. Here is the link.
So if anyone knows the solution for this please tell me I would really be thankful to you!

Body:
I was testing Alembic.
Initially I created a model something like this:

from main import Base
from sqlalchemy import Column, BigInteger, SmallInteger, String, Sequence, ForeignKey

class Users(Base):
    __tablename__ = "users"

    id = Column(BigInteger, Sequence("user_id_seq"),
                primary_key=True)
    first_name = Column(String(50))
    last_name = Column(String(50))
    email = Column(String(255))
    password = Column(String(60), nullable=True)

Then I created the revision in alembic and it worked absolutely fine and I got the result properly.
Then I added the user types table and then my models looked like this,

from main import Base
from sqlalchemy import Column, BigInteger, SmallInteger, String, Sequence, ForeignKey

class Users(Base):
    __tablename__ = "users"

    id = Column(BigInteger, Sequence("user_id_seq"),
                primary_key=True)
    first_name = Column(String(50))
    last_name = Column(String(50))
    email = Column(String(255))
    password = Column(String(60), nullable=True)
    user_type = Column(SmallInteger, ForeignKey(
        "user_types.id", name="fk_user_type"))

class UserTypes(Base):
    __tablename__ = "user_types"

    id = Column(SmallInteger, Sequence("user_types_id_seq"),
                primary_key=True)
    type = Column(String(20))

Now I created the revision for this and obviously that also worked.
But then I thought that lets make the user_type default value 1. So I did a small change in Users model and added default value 1:

user_type = Column(SmallInteger, ForeignKey(
        "user_types.id", name="fk_user_type"), default=1)

Now ideally if I created migration it should work. But it gave me the blank file:

"""Made Default Value Of user_type 1

Revision ID: 054b79123431
Revises: 84bc1adb3e66
Create Date: 2022-12-28 17:20:06.757224

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '054b79123431'
down_revision = '84bc1adb3e66'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

I also tried to add compare_server_default=True in the context.configure calls in both offline and online migration function as it was said in an answer I found on internet which was related to the same issue but that also didnt worked. Here is the link.
So if anyone knows the solution for this please tell me I would really be thankful to you!


来源: stackexchange

问:
Custom Domain Features for MERN Stack APP deployed on AWS Amplify
We are using AWS Amplify for the React SPA hosting & Route 53 for the domain management.
Our App is a kind of SaaS. We want to implement custom domain features for our customers so that they can map their subdomain to our domain.
like our domain is https://our.domain.com and customer domain is https://customer.domain.com
When user enter https://customer.domain.com they should be able to see content of https://our.domain.com(It should not redirect.)

Since I am a beginner in DNS therefore I don't know much about DNS.

I was trying if there is a way available in AWS Amplify & Route 53 to solve this but was not get success.

PS: We have configured our custom domain with react app using route-53 in AWS Amplify.

ContentLicense: CC BY-SA 4.0


问:
Dockerfile installs newer python insteam of FROM source
I'm trying to make a new image for python dockerfile, but keeps installing Python 3.10 instead of Python 3.8.

My Dockerfile looks like this:

```<code>FROM python:3.8.16

COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

## follow installation from xtb-python github:
ENV CONDA_DIR /opt/conda

RUN apt-get update && apt-get install -y \
    wget \
    && rm -rf /var/lib/apt/lists/*

RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh  \
    && /bin/bash ~/miniconda.sh -b -p /opt/conda

ENV PATH=$CONDA_DIR/bin:$PATH
RUN conda config --add channels conda-forge  \
    && conda install -y -c conda-forge ...

</code>```

I don't know much about conda (but have to use it).
It is Conda messing with the my Python or I did it something wrong?

Body:
I'm trying to make a new image for python dockerfile, but keeps installing Python 3.10 instead of Python 3.8.

My Dockerfile looks like this:

FROM python:3.8.16

COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

## follow installation from xtb-python github:
ENV CONDA_DIR /opt/conda

RUN apt-get update && apt-get install -y \
    wget \
    && rm -rf /var/lib/apt/lists/*

RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh  \
    && /bin/bash ~/miniconda.sh -b -p /opt/conda

ENV PATH=$CONDA_DIR/bin:$PATH
RUN conda config --add channels conda-forge  \
    && conda install -y -c conda-forge ...

I don't know much about conda (but have to use it).
It is Conda messing with the my Python or I did it something wrong?


问:
webpack error when importing react-swiper
when I try to import react-swiper from react, the webpack throws an error and I haven't found a solution for this one. Does anyone here knows how to resolve this error? Thanks in advance.

Error in Webpack images

and here's my webpack

webpack.config.js


问:
Google play IAP subscription for yearly plan always get Cancelled for License Tester
I have recently implemented IAP for our android application.
I have created both monthly and yearly plan which have trial period offer for 7 days and are autorenewable.
We are using RTDN to handle the subscription state at backend.
For monthly plan INR 2800 the subscription flow is working perfect and I am receiving proper RTDN notifications every 5 min for test purchase.
However for Yearly plan INR 19000 is getting canceled immediately once subscription is done and I am getting SUBSCRIPTION_STATE_CANCELED notification from RTDN.
As per RBI if amount is greater than 5000 INR Subscriptions will not autorenew but I am not able to make 1st purchase for yearly plan which is more than 5000 INR.

Response from google api for yearly plan :

{
"kind": "androidpublisher#subscriptionPurchaseV2",
"startTime": "2022-11-22T11:43:56.194Z",
"regionCode": "IN",
"subscriptionState": "SUBSCRIPTION_STATE_CANCELED",
"latestOrderId": "GPA.XXXXXXXXXXXXXXX",
"canceledStateContext": {
"systemInitiatedCancellation": {}
},
"testPurchase": {},
"acknowledgementState": "ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED",
"externalAccountIdentifiers": {
"obfuscatedExternalAccountId": "XXXXXXXXX",
"obfuscatedExternalProfileId": "XXXXXXXXX"
},
"lineItems": [
{
"productId": "yearlyplan",
"expiryTime": "2022-11-22T12:13:45.621Z",
"autoRenewingPlan": {},
"offerDetails": {
"basePlanId": "yearly01"
}
}
]
}


问:
how can i load another question from the database after i have clicked on a button

I have a quiz game. After I click on the "Next" button (see picture), I want the next question to be loaded from the database. Only one question is currently displayed, but I don't know how to load more questions from the database. Summarized again: After clicking on the Next button, another question should be loaded from the database. I'm new to Django, would be cool if someone could help me further

views.py

def quiz_math(request):
    if request.method == 'POST':

        questions = QuesModel.objects.filter(kategorie__exact="Math")
        score = 0
        wrong = 0
        correct = 0
        total = 0
        for q in questions:
            total += 1

            answer = request.POST.get(q.question)
            print(answer)

            if q.ans == answer:
                score += 10
                correct += 1
            else:
                wrong += 1
        percent = score / (total * 10) * 100
        context = {
            'score': score,
            'time': request.POST.get('timer'),
            'correct': correct,
            'wrong': wrong,
            'percent': percent,
            'total': total,

        }
        return render(request, 'result.html', context)
    else:
        questions = QuesModel.objects.all()
        context = {
            'questions': questions
        }
        return render(request, 'quiz_math.html', context)
```
<p><strong>model.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class QuesModel(models.Model):
    Kategorie = (
        ("Math", "Math"),
        ("Digital Skills", "Digital Skills"),

    )

    kategorie = models.CharField(max_length=400, null=True, choices=Kategorie)

    user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL)
    question = models.CharField(max_length=200, null=True,)
    op1 = models.CharField(max_length=200, null=True)
    op2 = models.CharField(max_length=200, null=True)
    op3 = models.CharField(max_length=200, null=True)
    op4 = models.CharField(max_length=200, null=True)
    ans = models.CharField(max_length=200, null=True)
    flaag = models.BooleanField('Aprroved', default=False)
    def __str__(self):
        return self.question
</code>```

math.html

<form method="POST" action="">
    {% for q  in questions%}
        {% csrf_token %}
        {% if q.kategorie == "Math" and q.flaag == True %}

<button class="neuefragenladen_button">Next!</button>

                            <input type="radio" id="option1" name="option1" class="radio" value="option1"/>
                            {{q.op1}}

                            <input type="radio" id="option2" name="option2" class="radio" value="option2"/>
                            {{q.op2}}

{{q.question}}

                            <input type="radio" id="option3" name="option3" class="radio" value="option3"/>
                            {{q.op3}}

                            <input type="radio" id="option4" name="option4" class="radio" value="option4"/>
                            {{q.op4}}

```

Body:
I have a quiz game. After I click on the "Next" button (see picture), I want the next question to be loaded from the database. Only one question is currently displayed, but I don't know how to load more questions from the database. Summarized again: After clicking on the Next button, another question should be loaded from the database. I'm new to Django, would be cool if someone could help me further

views.py

def quiz_math(request):
    if request.method == 'POST':

        questions = QuesModel.objects.filter(kategorie__exact="Math")
        score = 0
        wrong = 0
        correct = 0
        total = 0
        for q in questions:
            total += 1

            answer = request.POST.get(q.question)
            print(answer)

            if q.ans == answer:
                score += 10
                correct += 1
            else:
                wrong += 1
        percent = score / (total * 10) * 100
        context = {
            'score': score,
            'time': request.POST.get('timer'),
            'correct': correct,
            'wrong': wrong,
            'percent': percent,
            'total': total,

        }
        return render(request, 'result.html', context)
    else:
        questions = QuesModel.objects.all()
        context = {
            'questions': questions
        }
        return render(request, 'quiz_math.html', context)

model.py

class QuesModel(models.Model):
    Kategorie = (
        ("Math", "Math"),
        ("Digital Skills", "Digital Skills"),

    )

    kategorie = models.CharField(max_length=400, null=True, choices=Kategorie)

    user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL)
    question = models.CharField(max_length=200, null=True,)
    op1 = models.CharField(max_length=200, null=True)
    op2 = models.CharField(max_length=200, null=True)
    op3 = models.CharField(max_length=200, null=True)
    op4 = models.CharField(max_length=200, null=True)
    ans = models.CharField(max_length=200, null=True)
    flaag = models.BooleanField('Aprroved', default=False)
    def __str__(self):
        return self.question

math.html

<form method="POST" action="">
    {% for q  in questions%}
        {% csrf_token %}
        {% if q.kategorie == "Math" and q.flaag == True %}

<button class="neuefragenladen_button">Next!</button>

                            <input type="radio" id="option1" name="option1" class="radio" value="option1"/>
                            {{q.op1}}

                            <input type="radio" id="option2" name="option2" class="radio" value="option2"/>
                            {{q.op2}}

{{q.question}}

                            <input type="radio" id="option3" name="option3" class="radio" value="option3"/>
                            {{q.op3}}

                            <input type="radio" id="option4" name="option4" class="radio" value="option4"/>
                            {{q.op4}}


问:
W3 Cache disable cdn for specific plugin
I am using the Elementor plugin I want to disable CDN for Elementor plugin CSS/JS files I tried adding the files in Rejected files still it's showing as hosted on CDN.

Here are the WP settings:

Error:


问:
Why FocusedrowChanged GridView in DevExpress runs slowly in vb.net
Why FocusrowChanged GridView in DevExpress runs slowly in vb.net?

Is there a solution so it doesn't get slow? And the image data there are four thousand. If I run FocusedRowChanged in gridview in the image in pictureedit it immediately appears but the row shift is not direct and becomes slow.

Thanks

```<code>Private Sub GridView1_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim view As GridView = TryCast(sender, GridView)

        If view.FocusedRowHandle = GridControl.AutoFilterRowHandle Then
            Return
        End If

        Dim SUBFOLDERP As String = view.GetFocusedRowCellValue("SUBFOLDERP")?.ToString
        Dim Filename1 As String = view.GetFocusedRowCellValue("FILENAME1")?.ToString
        Dim Filename2 As String = view.GetFocusedRowCellValue("FILENAME2")?.ToString
        parentpathimage = Directory.GetCurrentDirectory()
        Dim filePath1 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename1, False)
        Dim filePath2 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename2, False)
        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
            End If
        End If
    End Sub
</code>```

Body:
Why FocusrowChanged GridView in DevExpress runs slowly in vb.net?

Is there a solution so it doesn't get slow? And the image data there are four thousand. If I run FocusedRowChanged in gridview in the image in pictureedit it immediately appears but the row shift is not direct and becomes slow.

Thanks

Private Sub GridView1_FocusedRowChanged(sender As Object, e As FocusedRowChangedEventArgs) Handles GridView1.FocusedRowChanged
        Dim view As GridView = TryCast(sender, GridView)

        If view.FocusedRowHandle = GridControl.AutoFilterRowHandle Then
            Return
        End If

        Dim SUBFOLDERP As String = view.GetFocusedRowCellValue("SUBFOLDERP")?.ToString
        Dim Filename1 As String = view.GetFocusedRowCellValue("FILENAME1")?.ToString
        Dim Filename2 As String = view.GetFocusedRowCellValue("FILENAME2")?.ToString
        parentpathimage = Directory.GetCurrentDirectory()
        Dim filePath1 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename1, False)
        Dim filePath2 = DevExpress.Utils.FilesHelper.FindingFileName(parentpathimage & "\" & SUBFOLDERP & "\", Filename2, False)
        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
            End If
        End If
    End Sub


问:
Post array on Laravel Request
I have a few inputs, and I need to receive them all as an array through a form sent by a POST request.

Blade template (into form):

```<code>    @foreach($langs as $lang)
        <input type = "text" class = "form-control" name = "text[first][{{ $lang->code }}]" value = "first">
        <input type = "text" class = "form-control" name = "text[second][{{ $lang->code }}]" value = "second">
    @endforeach
</code>```

But when receiving them through Request, they don't behave like an array, I receive them all separately, with "text[first][en]" as Key, in this example I get this:

```<code>"text[first][en]": first,
"text[first][it]": first,
...
"text[second][en]": second,
"text[second][it]": second,
</code>```

If I try to do a foreach for each "text", it tells me that it is not an array.

Title: Post array on Laravel Request

Body:
I have a few inputs, and I need to receive them all as an array through a form sent by a POST request.

Blade template (into form):

    @foreach($langs as $lang)
        <input type = "text" class = "form-control" name = "text[first][{{ $lang->code }}]" value = "first">
        <input type = "text" class = "form-control" name = "text[second][{{ $lang->code }}]" value = "second">
    @endforeach

But when receiving them through Request, they don't behave like an array, I receive them all separately, with "text[first][en]" as Key, in this example I get this:

"text[first][en]": first,
"text[first][it]": first,
...
"text[second][en]": second,
"text[second][it]": second,

If I try to do a foreach for each "text", it tells me that it is not an array.


问:
What can i use instead of "FUN=take" argument in this r code?
I am trying to run examples of chapter 14 of Multilevel Analysis book by Snijders and Bosker (2012).

This is the book's companion page. Relevant Dataset and r code. This is a PISA data. Below STRATUM variable is about regions of USA and  id2 is ID of the School.

After running sch_str <- aggregate(pisac$STRATUM,by=list(id2),FUN=take)[,2] i am getting this error

Error in match.fun(FUN) : object 'take' not found

There is no package related to this code as i see. So i investigated the FUN=take i only find this function in plyr package. But after attaching plyr i get this error

Error in FUN(X[[i]], ...) :
argument "indices" is missing, with no default

I looked at how the take function in the dplyr package works and came to the conclusion that this function is not the same as in the original code. The take argument has been used many times in the code and other functions have been defined with the help of it. I tried subset intstead but could not get any result.

I wonder if take deprecated? What can i use instead?


问:
How to write Redshift stored procedure using aggregate functions?
I want to write a stored procedure using aggregate functions. Is there some place where I could refer for this?

I couldn't find any concrete material.


问:
After adding an item to the cart, sometimes it undesirably gets removed a second later
I have a weird bug which I can't reproduce easily. In 90% times everything works ok but sometimes when I add a new product, I can see that minicart shows higher product number but then after a second that number goes back to the previous item count. On the cart page I can also see that in that case product really wasn't added to cart.

So basically, after a product is added to the cart it gets removed a second later

In the WooCommerce settings Ajax functionality is turned on. It is a custom theme with quantity buttons added but adding a product into the cart is all on the WooCommerce end. I have also temporarely disabled all WC templates in my theme trying to find the problem. What can I do to inspect the problem further? I don't see any errors in the logs (both debug.log in wp-content, error log in the root or WC logs in uploads/wc-logs). Everything is updated to last version with only needed plugins active (like ACF). The same bug happens on stage hosting and localhost (Wampserver)

If I hook into "woocommerce_ajax_added_to_cart" action (which is triggered after a product is successfully added into the cart https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-ajax.html#source-view.419) and there I write to a log, I can see that it is correctly triggered each time, even in cases when a product is after for some reason removed from the cart.

```<code>add_action('woocommerce_ajax_added_to_cart', 'ms_woocommerce_ajax_added_to_cart');
function ms_woocommerce_ajax_added_to_cart() {
    write_log('product is added to cart');
}
</code>```

Also when I hook into their JS hook, it is triggered.

```<code>jQuery( document.body ).on('added_to_cart', function(e){
    console.log('it worked')
});
</code>```

Example of the form inside li.product:

```<code><form action="?add-to-cart=4862" class="cart" method="post" enctype="multipart/form-data">
    <div class="loop-increments">
        <button type="button" class="btn-buyproduct btn-buyproduct--minus">-</button>
        <div class="quantity">
            <label class="screen-reader-text" for="quantity_63ac1f239e395">Product name</label>
            <input type="number" id="quantity_63ac1f239e395" class="input-text qty text" name="quantity" value="1" title="Qty" size="4" min="0" max="" step="1" placeholder="" inputmode="numeric" autocomplete="off">
        </div>
        <button type="button" class="btn-buyproduct btn-buyproduct--plus">+</button>
    </div>
    <a href="?add-to-cart=4862" class="button product_type_simple add_to_cart_button ajax_add_to_cart ms_add_to_cart_button" rel="nofollow">Add to cart</a>
</form>
</code>```

What could be the problem?

Body:
I have a weird bug which I can't reproduce easily. In 90% times everything works ok but sometimes when I add a new product, I can see that minicart shows higher product number but then after a second that number goes back to the previous item count. On the cart page I can also see that in that case product really wasn't added to cart.

So basically, after a product is added to the cart it gets removed a second later

In the WooCommerce settings Ajax functionality is turned on. It is a custom theme with quantity buttons added but adding a product into the cart is all on the WooCommerce end. I have also temporarely disabled all WC templates in my theme trying to find the problem. What can I do to inspect the problem further? I don't see any errors in the logs (both debug.log in wp-content, error log in the root or WC logs in uploads/wc-logs). Everything is updated to last version with only needed plugins active (like ACF). The same bug happens on stage hosting and localhost (Wampserver)

If I hook into "woocommerce_ajax_added_to_cart" action (which is triggered after a product is successfully added into the cart https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-ajax.html#source-view.419) and there I write to a log, I can see that it is correctly triggered each time, even in cases when a product is after for some reason removed from the cart.

add_action('woocommerce_ajax_added_to_cart', 'ms_woocommerce_ajax_added_to_cart');
function ms_woocommerce_ajax_added_to_cart() {
    write_log('product is added to cart');
}

Also when I hook into their JS hook, it is triggered.

jQuery( document.body ).on('added_to_cart', function(e){
    console.log('it worked')
});

Example of the form inside li.product:

<form action="?add-to-cart=4862" class="cart" method="post" enctype="multipart/form-data">

        <button type="button" class="btn-buyproduct btn-buyproduct--minus">-</button>

            Product name
            <input type="number" id="quantity_63ac1f239e395" class="input-text qty text" name="quantity" value="1" title="Qty" size="4" min="0" max="" step="1" placeholder="" inputmode="numeric" autocomplete="off">

        <button type="button" class="btn-buyproduct btn-buyproduct--plus">+</button>

    Add to cart
</form>

What could be the problem?


问:
Kafka out of order messages and kafka down error
I was having an error cannot CREATE PARTITIONS on my service logs and I rearranged my partitions in yml file according to partition count given in KafkaDrop and restarted services. But now I'm seeing related error and after some time kafka is going down. I couldn't find solution regarding this issue. Kafka Version : 0.11

WARN Received a PartitionLeaderEpoch assignment for an epoch < latestEpoch. This implies messages have arrived out of order. New: {epoch:12, offset:323051}, Current: {epoch:29, offset208082} for Partition: __consumer_offsets-48 (kafka.server.epoch.LeaderEpochFileCache)


问:
Prolog query doesn't work for some reason
I'm trying to write a simple game in Prolog. And here is my predicate for inventory:

```<code>:- dynamic have/1.

inv(0, []).
inv(N, [X | Rest]):- have(X),
                     \+ member(X, Rest),
                     N1 is N - 1,
                     inv(N1, Rest).
</code>```

So, I'm trying to choose every item which player has, and it works for this for example

```<code>?- inv(2, [classic_gun, medkit]).
true .
</code>```

but for inv(2, R) I get false.

```<code>?- inv(2, R).
false.
</code>```

What did I do wrong?

Body:
I'm trying to write a simple game in Prolog. And here is my predicate for inventory:

:- dynamic have/1.

inv(0, []).
inv(N, [X | Rest]):- have(X),
                     \+ member(X, Rest),
                     N1 is N - 1,
                     inv(N1, Rest).

So, I'm trying to choose every item which player has, and it works for this for example

?- inv(2, [classic_gun, medkit]).
true .

but for inv(2, R) I get false.

?- inv(2, R).
false.

What did I do wrong?


问:
How long will the sound play?
I am building an app that uses DartMeltySoundFont as a synthesizer and raw_sounds to play the sounds.

I init the synthesizer like this:

```<code>Synthesizer synthesizer = Synthesizer.loadByteData(
        bytes,
        SynthesizerSettings(
          sampleRate: 44100,
          blockSize: 980,
          maximumPolyphony: 64,
          enableReverbAndChorus: false,
        ));
</code>```

Then I add a block with some MIDI instructions and the sound plays.

But I don't know how long it plays.

How can I calculate how long it plays in seconds given the variables sampleRate, blockSize and amount of blocks added?

Full example app:

```<code>import 'dart:typed_data'; // for Uint8List
import 'package:flutter/material.dart';
import 'package:raw_sound/raw_sound_player.dart';
import 'package:dart_melty_soundfont/dart_melty_soundfont.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // Player instance to play raw PCM (16-bit integer) audio data
  final _playerPCMF32 = RawSoundPlayer();
  bool _playing = false;

  @override
  void initState() {
    super.initState();

    //  release any initialized player instances
    _playerPCMF32
        .initialize(
      sampleRate: 44100,
      pcmType: RawSoundPCMType.PCMF32,
    )
        .then((value) {
      setState(() {
        // Trigger rebuild to update UI
      });
    });
  }

  @override
  void dispose() {
    // Finally release any initialized player instances
    _playerPCMF32.release();
    super.dispose();
  }

  Widget build(BuildContext context) {
    debugPrint('_playerPCMF32 is inited? ${_playerPCMF32.isInited}');

    if (!_playerPCMF32.isInited) {
      return Container();
    }

    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.grey,
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('Raw Sound Plugin Example App'),
        ),
        body: Column(
          children: [
            Card(
              child: Row(
                children: [
                  IconButton(
                    icon: Icon(_playerPCMF32.isPlaying ? Icons.stop : Icons.play_arrow),
                    onPressed: () {
                      _playerPCMF32.isPlaying ? _pausePCMF32() : _playPCMF32();
                    },
                  ),
                  Text('Test PCMF32'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _playPCMF32() async {
    if (_playerPCMF32.isPlaying) {
      return;
    }
    await _playerPCMF32.play();
    setState(() {
      _playing = true;
    });
    // Continuously feed the player until the playback is paused/stopped
    //final dataBlock = _genPCMF32DataBlock(nPeriods: 20);
    final dataBlock = await _getMoreSound();
    print('new sound read');
    while (_playerPCMF32.isPlaying) {
      await _playerPCMF32.feed(dataBlock);
    }
  }

  Future<void> _pausePCMF32() async {
    await _playerPCMF32.stop();
    setState(() {
      _playing = false;
    });
  }

  _getMoreSound() async {
    int sampleRate = 44100;
    int blockSize = 980;
    int blockCount = sampleRate ~/ blockSize; // =45

    // Create the synthesizer.
    ByteData bytes = await rootBundle.load('assets/Mace-Drums.sf2');

    Synthesizer synthesizer = Synthesizer.loadByteData(
        bytes,
        SynthesizerSettings(
          sampleRate: sampleRate,
          blockSize: blockSize,
          maximumPolyphony: 64,
          enableReverbAndChorus: false,
        ));

    // Define the melody.
    // A single row indicates the start timing, end timing, and pitch.
    var data = [
      //[0, 15, 0],
      [15, 30, 36],
      [30, 45, 36],
    ];

    // The output buffer.
    List<double> left = List<double>.filled(sampleRate, 0);
    List<double> right = List<double>.filled(sampleRate, 0);
    final dataBlock = <int>[];

    for (var t = 0; t < blockCount; t++) {
      // Process the melody.
      for (var row in data) {
        if (t == row[0]) synthesizer.noteOn(channel: 9, key: row[2], velocity: 100);
        if (t == row[1]) synthesizer.noteOff(channel: 9, key: row[2]);
      }

      // Render the block.
      int start = blockSize * t;
      var blockLeft = left.sublist(start, start + blockSize);
      var blockRight = right.sublist(start, start + blockSize);
      synthesizer.render(blockLeft, blockRight);

      final dataBlockPerPeriod = ByteData(blockLeft.length << 2 /* one float32 is made of 4 bytes */);
      for (int i = 0; i < blockLeft.length; i++) {
        // amplitude is in the range of -1.0 to 1.0
        final value = blockLeft[i];
        dataBlockPerPeriod.setFloat32(i << 2, value, Endian.host /* native endianness */);
      }
      // Repeat dataBlockPerPeriod nPeriods times

      dataBlock.addAll(dataBlockPerPeriod.buffer.asUint8List());
      debugPrint('dataBlock nBytes: ${dataBlock.length}');
    }

    return Uint8List.fromList(dataBlock);
  }
}

</code>```

Title: How long will the sound play?

Body:
I am building an app that uses DartMeltySoundFont as a synthesizer and raw_sounds to play the sounds.

I init the synthesizer like this:

Synthesizer synthesizer = Synthesizer.loadByteData(
        bytes,
        SynthesizerSettings(
          sampleRate: 44100,
          blockSize: 980,
          maximumPolyphony: 64,
          enableReverbAndChorus: false,
        ));

Then I add a block with some MIDI instructions and the sound plays.

But I don't know how long it plays.

How can I calculate how long it plays in seconds given the variables sampleRate, blockSize and amount of blocks added?

Full example app:

import 'dart:typed_data'; // for Uint8List
import 'package:flutter/material.dart';
import 'package:raw_sound/raw_sound_player.dart';
import 'package:dart_melty_soundfont/dart_melty_soundfont.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // Player instance to play raw PCM (16-bit integer) audio data
  final _playerPCMF32 = RawSoundPlayer();
  bool _playing = false;

  @override
  void initState() {
    super.initState();

    //  release any initialized player instances
    _playerPCMF32
        .initialize(
      sampleRate: 44100,
      pcmType: RawSoundPCMType.PCMF32,
    )
        .then((value) {
      setState(() {
        // Trigger rebuild to update UI
      });
    });
  }

  @override
  void dispose() {
    // Finally release any initialized player instances
    _playerPCMF32.release();
    super.dispose();
  }

  Widget build(BuildContext context) {
    debugPrint('_playerPCMF32 is inited? ${_playerPCMF32.isInited}');

    if (!_playerPCMF32.isInited) {
      return Container();
    }

    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.grey,
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('Raw Sound Plugin Example App'),
        ),
        body: Column(
          children: [
            Card(
              child: Row(
                children: [
                  IconButton(
                    icon: Icon(_playerPCMF32.isPlaying ? Icons.stop : Icons.play_arrow),
                    onPressed: () {
                      _playerPCMF32.isPlaying ? _pausePCMF32() : _playPCMF32();
                    },
                  ),
                  Text('Test PCMF32'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _playPCMF32() async {
    if (_playerPCMF32.isPlaying) {
      return;
    }
    await _playerPCMF32.play();
    setState(() {
      _playing = true;
    });
    // Continuously feed the player until the playback is paused/stopped
    //final dataBlock = _genPCMF32DataBlock(nPeriods: 20);
    final dataBlock = await _getMoreSound();
    print('new sound read');
    while (_playerPCMF32.isPlaying) {
      await _playerPCMF32.feed(dataBlock);
    }
  }

  Future<void> _pausePCMF32() async {
    await _playerPCMF32.stop();
    setState(() {
      _playing = false;
    });
  }

  _getMoreSound() async {
    int sampleRate = 44100;
    int blockSize = 980;
    int blockCount = sampleRate ~/ blockSize; // =45

    // Create the synthesizer.
    ByteData bytes = await rootBundle.load('assets/Mace-Drums.sf2');

    Synthesizer synthesizer = Synthesizer.loadByteData(
        bytes,
        SynthesizerSettings(
          sampleRate: sampleRate,
          blockSize: blockSize,
          maximumPolyphony: 64,
          enableReverbAndChorus: false,
        ));

    // Define the melody.
    // A single row indicates the start timing, end timing, and pitch.
    var data = [
      //[0, 15, 0],
      [15, 30, 36],
      [30, 45, 36],
    ];

    // The output buffer.
    List<double> left = List<double>.filled(sampleRate, 0);
    List<double> right = List<double>.filled(sampleRate, 0);
    final dataBlock = <int>[];

    for (var t = 0; t < blockCount; t++) {
      // Process the melody.
      for (var row in data) {
        if (t == row[0]) synthesizer.noteOn(channel: 9, key: row[2], velocity: 100);
        if (t == row[1]) synthesizer.noteOff(channel: 9, key: row[2]);
      }

      // Render the block.
      int start = blockSize * t;
      var blockLeft = left.sublist(start, start + blockSize);
      var blockRight = right.sublist(start, start + blockSize);
      synthesizer.render(blockLeft, blockRight);

      final dataBlockPerPeriod = ByteData(blockLeft.length << 2 /* one float32 is made of 4 bytes */);
      for (int i = 0; i < blockLeft.length; i++) {
        // amplitude is in the range of -1.0 to 1.0
        final value = blockLeft[i];
        dataBlockPerPeriod.setFloat32(i << 2, value, Endian.host /* native endianness */);
      }
      // Repeat dataBlockPerPeriod nPeriods times

      dataBlock.addAll(dataBlockPerPeriod.buffer.asUint8List());
      debugPrint('dataBlock nBytes: ${dataBlock.length}');
    }

    return Uint8List.fromList(dataBlock);
  }
}


问:
Is it possible to send data via postMessage then let the target iframe store the data to react redux?
I have two React Apps with redux.
example1 has an iframe example2.

I want to pass data from example1 to example2 via postMessage, and let the example2 save the data to state once it received the post message.

Is it possible to achieve the goal? I have tried to do it like the below code, but nothing happened.

Thanks.

// example1.com

```<code>function App() {

  const sendPostMessage = () => {
    window.postMessage('hello there!', '*')
  }

  return (
    <div>
     <button onClick={sendPostMessage}>Click Me</button>
     <iframe
       title="iframe example"
       src="http://example2.com"
       width="600"
       height="400"
     />
    </div>
  )
}
</code>```

// exmaple2.com

```<code>function App() {
  const [message, setMessage] = useState("No data");
  useEffect(() => {
    window.addEventListener("message", (event) => {

      setMessage(event.data);  // want to save data to redux or state

    });
  }, []);

  return (
   <div>
    <p>{message}</p>
   </div>
  )
}
</code>```

Body:
I have two React Apps with redux.
example1 has an iframe example2.

I want to pass data from example1 to example2 via postMessage, and let the example2 save the data to state once it received the post message.

Is it possible to achieve the goal? I have tried to do it like the below code, but nothing happened.

Thanks.

// example1.com

function App() {

  const sendPostMessage = () => {
    window.postMessage('hello there!', '*')
  }

  return (

     <button onClick={sendPostMessage}>Click Me</button>

  )
}

// exmaple2.com

function App() {
  const [message, setMessage] = useState("No data");
  useEffect(() => {
    window.addEventListener("message", (event) => {

      setMessage(event.data);  // want to save data to redux or state

    });
  }, []);

  return (

{message}

  )
}


问:
I want to configure the Prometheus using kube-prom-stack to federate metrics from https server
I  have kube-prom-stack runnning on a node and i  have configure it using federate endpoint to scrape metrics from a remote server as below in my values.yaml file:

```<code>   additionalScrapeConfigs:
      - job_name: 'sp-federation'
        scrape_interval: 20s
        scrape_timeout: 20s
        scheme: http
        metrics_path: /federate
        honor_labels: true
        metric_relabel_configs:
          - source_labels: [id]
            regex: '^static-agent$'
            action: drop
        params:
          match[]:
            - '{__name__=~"kube_.*"}'
        static_configs:
          - targets: ['X.X.X.X:9090']
</code>```

But the remote server only accepts connection on https.
I want to configure it in such a way that it pull the metrics from https by skipping the certificate validation part as i don't have the remote server certificate now.
Please help, as i am a beginner in the networking and prometheus.

```<code>I used below configuration to deploy the kube-prom-stack, but not sure what to do next to skip the server  certificate validation.
</code>```

serviceMonitor:
## Scrape interval. If not set, the Prometheus default scrape interval is used.
##
interval: ""
selfMonitor: true

```<code>## proxyUrl: URL of a proxy that should be used for scraping.
##
proxyUrl: ""

## scheme: HTTP scheme to use for scraping. Can be used with `tlsConfig` for example if using istio mTLS.
scheme: ""

## enableHttp2: Whether to enable HTTP2.
## See https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/api.md#endpoint
enableHttp2: true
## tlsConfig: TLS configuration to use when scraping the endpoint. For example if using istio mTLS.
## Of type: https://github.com/coreos/prometheus-operator/blob/main/Documentation/api.md#tlsconfig
tlsConfig: {}

bearerTokenFile:
</code>```
```<code>
</code>```

Body:
I  have kube-prom-stack runnning on a node and i  have configure it using federate endpoint to scrape metrics from a remote server as below in my values.yaml file:

   additionalScrapeConfigs:
      - job_name: 'sp-federation'
        scrape_interval: 20s
        scrape_timeout: 20s
        scheme: http
        metrics_path: /federate
        honor_labels: true
        metric_relabel_configs:
          - source_labels: [id]
            regex: '^static-agent$'
            action: drop
        params:
          match[]:
            - '{__name__=~"kube_.*"}'
        static_configs:
          - targets: ['X.X.X.X:9090']

But the remote server only accepts connection on https.
I want to configure it in such a way that it pull the metrics from https by skipping the certificate validation part as i don't have the remote server certificate now.
Please help, as i am a beginner in the networking and prometheus.

I used below configuration to deploy the kube-prom-stack, but not sure what to do next to skip the server  certificate validation.

serviceMonitor:
## Scrape interval. If not set, the Prometheus default scrape interval is used.
##
interval: ""
selfMonitor: true

## proxyUrl: URL of a proxy that should be used for scraping.
##
proxyUrl: ""

## scheme: HTTP scheme to use for scraping. Can be used with `tlsConfig` for example if using istio mTLS.
scheme: ""

## enableHttp2: Whether to enable HTTP2.
## See https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/api.md#endpoint
enableHttp2: true
## tlsConfig: TLS configuration to use when scraping the endpoint. For example if using istio mTLS.
## Of type: https://github.com/coreos/prometheus-operator/blob/main/Documentation/api.md#tlsconfig
tlsConfig: {}

bearerTokenFile:


问:
Source Control disabled on Installshield
We are trying to use Installshield for our Windows-Installer project

In order to get it versionised we are trying Source Control Feature of Installshield but it seems to be disabled/grayed-out (attaching screenshot)
We refered to multiple Docs for Installshield but there is no mention of same issue
https://docs.revenera.com/installshield26helplib/helplibrary/IHelpSccAddProject.htm

Also found a link to same issue but no replies from developers or community
https://community.flexera.com/t5/InstallShield-Forum/Installshield-2021-IDE-integration-with-Azure-Devops-source/td-p/227273

We also thought of adding this project dirctly to git but this would just push the projects as binary files and large file which would not make sense and get versionised.
as Build-in SourceControl on Installshield converts the projects to XML form
Ref: https://docs.revenera.com/installshield24helplib/helplibrary/IHelpSccOverview.htm

Let us know if we are missing something


问:
have problem with bottom navigation view in android
guys i have bottom navigation view and it work good on android 7,8 but when i run app on higher android version like 10,11 have bottom navigation view error</p>
```<code>.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnItemSelectedListener(com.google.android.material.navigation.NavigationBarView$OnItemSelectedListener)' on a null object reference
</code>```
```<code>bottomNavigationView =(BottomNavigationView) findViewById(R.id.bottomNavigationView);
 bottomNavigationView.setOnItemSelectedListener(BaseActivity.this);

 FirstFragment  firstFragment = new FirstFragment();
// SecondFragment secondFragment = new SecondFragment();
// ThirdFragment thirdFragment = new ThirdFragment();
 bottomNavigationView.setOnItemSelectedListener(item -> {
     int id = item.getItemId();
     switch(id){
         case R.id.Profile_bottom:
            startActivity(new Intent(BaseActivity.this,Profile.class));
            finish();
          //   getSupportFragmentManager().beginTransaction().replace(R.id.firstFragment, firstFragment).commit();

             return true;

         case R.id.home_bottom:
             startActivity(new Intent(BaseActivity.this, MainActivity.class));
             finish();
             return true;
         case R.id.Settings_bottom:
             Intent intent=new Intent(BaseActivity.this,Setting.class);
             startActivity(intent);
             finish();
             return true;
         case R.id.tamirkaran_bottom:
             Intent intent1=new Intent(BaseActivity.this,Tamirkaran.class);
             startActivity(intent1);
             finish();
             return true;

     }
     return true;
 });
</code>```

Body:
guys i have bottom navigation view and it work good on android 7,8 but when i run app on higher android version like 10,11 have bottom navigation view error

.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnItemSelectedListener(com.google.android.material.navigation.NavigationBarView$OnItemSelectedListener)' on a null object reference

bottomNavigationView =(BottomNavigationView) findViewById(R.id.bottomNavigationView);
 bottomNavigationView.setOnItemSelectedListener(BaseActivity.this);

 FirstFragment  firstFragment = new FirstFragment();
// SecondFragment secondFragment = new SecondFragment();
// ThirdFragment thirdFragment = new ThirdFragment();
 bottomNavigationView.setOnItemSelectedListener(item -> {
     int id = item.getItemId();
     switch(id){
         case R.id.Profile_bottom:
            startActivity(new Intent(BaseActivity.this,Profile.class));
            finish();
          //   getSupportFragmentManager().beginTransaction().replace(R.id.firstFragment, firstFragment).commit();

             return true;

         case R.id.home_bottom:
             startActivity(new Intent(BaseActivity.this, MainActivity.class));
             finish();
             return true;
         case R.id.Settings_bottom:
             Intent intent=new Intent(BaseActivity.this,Setting.class);
             startActivity(intent);
             finish();
             return true;
         case R.id.tamirkaran_bottom:
             Intent intent1=new Intent(BaseActivity.this,Tamirkaran.class);
             startActivity(intent1);
             finish();
             return true;

     }
     return true;
 });


问:
Playtika's OSS Feign Client: org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response

The issue

I've stumbled upon the issue:

```<code>Error message: org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response; nested exception is reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
</code>```

General info about the issue

It's a Spring Boot app (2.4.5) running on Reactive (WebFlux) stack.
The app also uses Playtika OSS reactive Feign Client (starter 3.0.3) for synchronious REST API communication.
Underlying web client is Netty.
There are no any special Feign or WebClient configs in the app.

All the other microservice parties are running on embedded Tomcat with default Spring Boot autoconfigurations.

All apps are running in Kubernetes cluster.

The error log observed from time to time (not every day).

Guesses

After some investigation, my best guess would be that some long-lived connections are being dropped from the pool on certain conditions. This causing the error log.
This thought is based on Instana that connects the error log to the span that spans accross a lot of subcalls.
Also no data losses/ other inconsistencies were noticed so far  xD

Questions

Does Feign has a connection pool by default?

How to know if those are live or idle connections from the pool being closed?

How the connection pool can be configured or dropped to avoid long-running connections ?

Is it possible that Kubernetes can somehow close these connections?

What else can close connections?

Body:
The issue

I've stumbled upon the issue:

Error message: org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response; nested exception is reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response

General info about the issue

It's a Spring Boot app (2.4.5) running on Reactive (WebFlux) stack.
The app also uses Playtika OSS reactive Feign Client (starter 3.0.3) for synchronious REST API communication.
Underlying web client is Netty.
There are no any special Feign or WebClient configs in the app.

All the other microservice parties are running on embedded Tomcat with default Spring Boot autoconfigurations.

All apps are running in Kubernetes cluster.

The error log observed from time to time (not every day).

Guesses

After some investigation, my best guess would be that some long-lived connections are being dropped from the pool on certain conditions. This causing the error log.
This thought is based on Instana that connects the error log to the span that spans accross a lot of subcalls.
Also no data losses/ other inconsistencies were noticed so far  xD

Questions

Does Feign has a connection pool by default?

How to know if those are live or idle connections from the pool being closed?

How the connection pool can be configured or dropped to avoid long-running connections ?

Is it possible that Kubernetes can somehow close these connections?

What else can close connections?


问:
How can I record a rectangle centered around the mouse cursor when it last moved <X seconds ago, otherwise centered around the caret (text cursor)?
I would like an ffmpeg incantation that will do A, or B, or C where

A is…
The ffmpeg incantation will record a rectangle that is centered around the caret (the "text cursor") when text is being typed.

B is…
The ffmpeg incantation will record a rectangle that is centered around the mouse cursor when the mouse cursor is actually moving or when the mouse cursor had been moving less than, say, 2 seconds ago.

C is…
The ffmpeg incantation will stop recording video, yet continue to record audio, if the mouse cursor had not been moving for 2 seconds or longer and the caret (the "text cursor") had not been moving for 2 seconds or longer.

On Linux Mint 21.1 Cinnamon, although both of the following incantations…

```<code>ffmpeg -f x11grab -follow_mouse centered -framerate 25 -video_size cif -i :0.0 -preset slow output.mkv
</code>```

and

```<code>ffmpeg -f x11grab -follow_mouse centered -show_region 1 -framerate 25 -video_size cif -i :0.0 -c:v libx264 -crf 0 -preset slow output.mp4
</code>```

successfully record the mouse cursor as I would like, obviously both incantations fail to record the caret (the "text cursor") when text is being typed.

Here’s my use case…

As a form of documentation, I intend to create screencasts of my coding sessions which I will narrate. I realize that this unusual form of documentation would normally result in large video files. Therefore, instead of recording the entire screen, I would like to record a small rectangle around either the area where I am typing text or—when I am using my mouse—around the area my mouse cursor is located. As a result I hope to create video files which take up less storage space, yet are still useful to me.

For example, I hope that when I review my coding sessions I will be able to quickly be reminded that, for example, "Oh, yeah, that's what I was thinking when I wrote that line of code. Yes. Now I remember: I was stuck, then went to Stackoverflow, did some research, and found solution XYZ to solve my problem.”

In other words, I won’t exclusively be coding during my coding sessions; sometimes I will be doing research on, for example, Stackoverflow. When I am doing research on—for example, Stackoverflow—I want my mouse cursor recorded.

For your information, follow_mouse at 3.21.1 Options.

Body:
I would like an ffmpeg incantation that will do A, or B, or C where

A is…
The ffmpeg incantation will record a rectangle that is centered around the caret (the "text cursor") when text is being typed.

B is…
The ffmpeg incantation will record a rectangle that is centered around the mouse cursor when the mouse cursor is actually moving or when the mouse cursor had been moving less than, say, 2 seconds ago.

C is…
The ffmpeg incantation will stop recording video, yet continue to record audio, if the mouse cursor had not been moving for 2 seconds or longer and the caret (the "text cursor") had not been moving for 2 seconds or longer.

On Linux Mint 21.1 Cinnamon, although both of the following incantations…

ffmpeg -f x11grab -follow_mouse centered -framerate 25 -video_size cif -i :0.0 -preset slow output.mkv

and

ffmpeg -f x11grab -follow_mouse centered -show_region 1 -framerate 25 -video_size cif -i :0.0 -c:v libx264 -crf 0 -preset slow output.mp4

successfully record the mouse cursor as I would like, obviously both incantations fail to record the caret (the "text cursor") when text is being typed.

Here’s my use case…

As a form of documentation, I intend to create screencasts of my coding sessions which I will narrate. I realize that this unusual form of documentation would normally result in large video files. Therefore, instead of recording the entire screen, I would like to record a small rectangle around either the area where I am typing text or—when I am using my mouse—around the area my mouse cursor is located. As a result I hope to create video files which take up less storage space, yet are still useful to me.

For example, I hope that when I review my coding sessions I will be able to quickly be reminded that, for example, "Oh, yeah, that's what I was thinking when I wrote that line of code. Yes. Now I remember: I was stuck, then went to Stackoverflow, did some research, and found solution XYZ to solve my problem.”

In other words, I won’t exclusively be coding during my coding sessions; sometimes I will be doing research on, for example, Stackoverflow. When I am doing research on—for example, Stackoverflow—I want my mouse cursor recorded.

For your information, follow_mouse at 3.21.1 Options.


Title: gpu is not detected by pytorch for spacy NER

Body:
I am trying to train a spacy3 NER model. I have GPU available on my machine with following specs:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 515.86.01    Driver Version: 515.86.01    CUDA Version: 11.7     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |
| N/A   68C    P0    29W /  70W |    567MiB / 15360MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1352      C   python                            563MiB |
+-----------------------------------------------------------------------------+

while GPU is active/available and running through following commands:

>>>import torch
>>>torch.backends.cudnn.is_available()
True

>>>torch.backends.cudnn.version()
8500

>>>torch.cuda.is_available()
True

>>>torch.zeros(1).cuda()
tensor([0.], device='cuda:0')

>>>torch.cuda.get_device_name()
'Tesla T4'

when I run the following command to train my spacy ner model,

 python3 -m spacy train configs/config.cfg --output training/ --path.train corpus/train.spacy --path.dev corpus/train.spacy --gpu-id 0

I am getting the following error:

 ValueError: No GPU devices detected

I have resolved version error and on top of it, GPU is available for normal tasks. I have gone through following stackoverflow questions but none of these is helpful.

GPU is not available for Pytorch

PyTorch is not finding GPU in Ubuntu

Why torch.cuda.is_available() returns False even after installing pytorch with cuda?

I am struck with this problem and unable to find a solution. Any sort of help is highly appreciated.

I am using following version of python and pytorch respectively

Python 3.10.6
1.13.1+cu117


问:
How to perform data validation from the DB and raise an nonFieldError in the form without saving using generic?
How best to perform data validation using Form_Class and CreateView.
How to cause an error in the form and not lose the entered data.
sing form_valid() or pre_save signal?

HOW COULD IT BE USING DEF VIEW & RENDER

```<code>if request.method == "POST":
    form = Buy_add_form(request.POST, instance=instance)
    if form.is_valid():
           hasPrice = SellingPrice.objects.filter(item=form.instance.item,  date=form.instance.date)
           if not hasPrice:
                 form.save()
                 return redirect("storage:index")
else:
    form = Buy_add_form(instance=instance)

return render(request, 'storage/add_flow.html', {
    'form': form,
})
</code>```

I'm writing a small inventory application.
Data on the price of each product should be recorded in the database no more than once a day.

In this example, I'm trying to see if there is a record in the table for this product on the date specified in the form.
If there is, I want to notify the user in the form and break the data saving process.
I need to save the filled form data.

MODELS.PY

```<code>class SellingPrice(models.Model):
    date = models.DateField(blank=False)
    item = models.ForeignKey(Items, on_delete=models.PROTECT, blank=False)
    price = models.FloatField(blank=False)

    def __str__(self):
        return f"{self.date}_{self.item}_{self.price}"
</code>```

FORMS.PY

```<code>class SetPrise_add_form(forms.ModelForm):
    date = forms.DateField(input_formats=['%d-%m-%Y'],
                               initial=now().strftime('%d-%m-%Y'),
                               widget=forms.DateInput(attrs={'data-mask': '00-00-0000'}))
    class Meta:
        model = SellingPrice
        fields = ["date", "item", "price"]
</code>```

VIEW.PY

```<code>class setPrice(CreateView):
    form_class = SetPrise_add_form
    template_name = "storage/setPrise_create.html"
    success_url = reverse_lazy('storage:prices-view')

    def form_valid(self, form):
        last = SellingPrice.objects.filter(item=form.instance.item, date=form.instance.date)
        if last:
            return redirect('storage:set-price')
        else:
            form.save()
            return HttpResponseRedirect(self.success_url)
</code>```

Body:
How best to perform data validation using Form_Class and CreateView.
How to cause an error in the form and not lose the entered data.
sing form_valid() or pre_save signal?

HOW COULD IT BE USING DEF VIEW & RENDER

if request.method == "POST":
    form = Buy_add_form(request.POST, instance=instance)
    if form.is_valid():
           hasPrice = SellingPrice.objects.filter(item=form.instance.item,  date=form.instance.date)
           if not hasPrice:
                 form.save()
                 return redirect("storage:index")
else:
    form = Buy_add_form(instance=instance)

return render(request, 'storage/add_flow.html', {
    'form': form,
})

I'm writing a small inventory application.
Data on the price of each product should be recorded in the database no more than once a day.

In this example, I'm trying to see if there is a record in the table for this product on the date specified in the form.
If there is, I want to notify the user in the form and break the data saving process.
I need to save the filled form data.

MODELS.PY

class SellingPrice(models.Model):
    date = models.DateField(blank=False)
    item = models.ForeignKey(Items, on_delete=models.PROTECT, blank=False)
    price = models.FloatField(blank=False)

    def __str__(self):
        return f"{self.date}_{self.item}_{self.price}"

FORMS.PY

class SetPrise_add_form(forms.ModelForm):
    date = forms.DateField(input_formats=['%d-%m-%Y'],
                               initial=now().strftime('%d-%m-%Y'),
                               widget=forms.DateInput(attrs={'data-mask': '00-00-0000'}))
    class Meta:
        model = SellingPrice
        fields = ["date", "item", "price"]

VIEW.PY

class setPrice(CreateView):
    form_class = SetPrise_add_form
    template_name = "storage/setPrise_create.html"
    success_url = reverse_lazy('storage:prices-view')

    def form_valid(self, form):
        last = SellingPrice.objects.filter(item=form.instance.item, date=form.instance.date)
        if last:
            return redirect('storage:set-price')
        else:
            form.save()
            return HttpResponseRedirect(self.success_url)


问:
How to open react app in Android Studio's emulator?
```<code>$ npx react-native run-android

info JS server already running.
info Launching emulator...
info Successfully launched emulator.
info Installing the app...
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.lastIndexOf(String)" because "path" is null
        at org.gradle.wrapper.PathAssembler.getDistName(PathAssembler.java:83)
        at org.gradle.wrapper.PathAssembler.getDistribution(PathAssembler.java:39)
        at org.gradle.wrapper.Install.createDist(Install.java:58)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:63)

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.lastIndexOf(String)" because "path" is null
        at org.gradle.wrapper.PathAssembler.getDistName(PathAssembler.java:83)
        at org.gradle.wrapper.PathAssembler.getDistribution(PathAssembler.java:39)
        at org.gradle.wrapper.Install.createDist(Install.java:58)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:63)

    at makeError (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.
</code>```

I have followed all the instructions in react docs but somehow i can't open the app in emulater.
after running npx react-native run-android it open emulater but can't dispaly the app in the emulater. I have strictly follow the doc and done every step mantioned there.

Body:
$ npx react-native run-android

info JS server already running.
info Launching emulator...
info Successfully launched emulator.
info Installing the app...
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.lastIndexOf(String)" because "path" is null
        at org.gradle.wrapper.PathAssembler.getDistName(PathAssembler.java:83)
        at org.gradle.wrapper.PathAssembler.getDistribution(PathAssembler.java:39)
        at org.gradle.wrapper.Install.createDist(Install.java:58)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:63)

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.lastIndexOf(String)" because "path" is null
        at org.gradle.wrapper.PathAssembler.getDistName(PathAssembler.java:83)
        at org.gradle.wrapper.PathAssembler.getDistribution(PathAssembler.java:39)
        at org.gradle.wrapper.Install.createDist(Install.java:58)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:63)

    at makeError (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (E:\Code Projects\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.

I have followed all the instructions in react docs but somehow i can't open the app in emulater.
after running npx react-native run-android it open emulater but can't dispaly the app in the emulater. I have strictly follow the doc and done every step mantioned there.


问:
Why is my firestore query not working for a specific collection?
I am trying to get a specific document from a firestore collection and get its ID.

Everything else works except the part where the fetching part (the query, I suppose).

If I change the collection to query, everything works peferctly.

My code

```<code>val country = binding.autoCompleteTv.text.toString().trim()
Log.d(BussinessDetailsFragment.TAG, country)
    firebaseFirestore.collection("Countries")
        .whereEqualTo("countryName", country)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(BussinessDetailsFragment.TAG, "${document.id} => ${document.data}")
                countryID = document.id
                Toast.makeText(this, countryID, Toast.LENGTH_SHORT).show()
            }
        }
        .addOnFailureListener { exception ->
            Log.w(BussinessDetailsFragment.TAG, "Error getting documents: ", exception)
        }
    }
}
</code>```

For some reason, this is not working. My logcat sometimes says tells me that my device internet might be weak but I don't think that is the problem.

As you can see, the auto-complete textview's value is being fetched successfully.

Any help will be much appreciated.

Body:
I am trying to get a specific document from a firestore collection and get its ID.

Everything else works except the part where the fetching part (the query, I suppose).

If I change the collection to query, everything works peferctly.

My code

val country = binding.autoCompleteTv.text.toString().trim()
Log.d(BussinessDetailsFragment.TAG, country)
    firebaseFirestore.collection("Countries")
        .whereEqualTo("countryName", country)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(BussinessDetailsFragment.TAG, "${document.id} => ${document.data}")
                countryID = document.id
                Toast.makeText(this, countryID, Toast.LENGTH_SHORT).show()
            }
        }
        .addOnFailureListener { exception ->
            Log.w(BussinessDetailsFragment.TAG, "Error getting documents: ", exception)
        }
    }
}

For some reason, this is not working. My logcat sometimes says tells me that my device internet might be weak but I don't think that is the problem.

As you can see, the auto-complete textview's value is being fetched successfully.

Any help will be much appreciated.


问:
WebFlux subscribe() method getting stuck
I am developing a Microservice application in SpringBoot. I am using Spring Cloud gateway there,now since Spring Cloud Gateway uses WebFlux module so,I want to extract username and password inside ServerAuthenticationConverter. But unfortunately flow is getting stuck on subscribe() method.

```<code>@Component
public class MyConverter implements ServerAuthenticationConverter {

@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
     String token = exchange.getRequest().getHeaders().getFirst("token");
     Map<String,String> credentialMap = new HashMap<>();

     if(StringUtils.containsIgnoreCase(exchange.getRequest().getPath().toString(),"/login")){

        exchange.getFormData().subscribe(data -> {
            for(Map.Entry<String,List<String>> mapEntry : data.entrySet()) {
                for (String value : mapEntry.getValue()) {
                    credentialMap.put(mapEntry.getKey(),value);
                    log.info("key=" + mapEntry.getKey() + "|value=" + mapEntry.getValue());
                }
            }
        });
        User user = new User(credentialMap.get("username"),credentialMap.get("password"));
        return  Mono.justOrEmpty(new UsernamePasswordAuthenticationToken(user,credentialMap.get("password"), List.of(new SimpleGrantedAuthority("ADMIN"))));
    }
    else{
       if(StringUtils.isNotBlank(token)){
           if(StringUtils.contains(token,"Bearer")){
               return  Mono.justOrEmpty(new MyToken(AuthorityUtils.NO_AUTHORITIES,token.substring(7)));
           }else{
               return  Mono.justOrEmpty(new MyToken(AuthorityUtils.NO_AUTHORITIES,token));
           }
       }
    }
}
throw  new IllegalArgumentException("Invalid Access");
}
  }
</code>```

But after printing log statement within subscribe method program flow is getting halted,no exception.
I think subscribe() method is causing some thread level issue.Can someone figureout the problem????

Body:
I am developing a Microservice application in SpringBoot. I am using Spring Cloud gateway there,now since Spring Cloud Gateway uses WebFlux module so,I want to extract username and password inside ServerAuthenticationConverter. But unfortunately flow is getting stuck on subscribe() method.

@Component
public class MyConverter implements ServerAuthenticationConverter {

@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
     String token = exchange.getRequest().getHeaders().getFirst("token");
     Map<String,String> credentialMap = new HashMap<>();

     if(StringUtils.containsIgnoreCase(exchange.getRequest().getPath().toString(),"/login")){

        exchange.getFormData().subscribe(data -> {
            for(Map.Entry<String,List<String>> mapEntry : data.entrySet()) {
                for (String value : mapEntry.getValue()) {
                    credentialMap.put(mapEntry.getKey(),value);
                    log.info("key=" + mapEntry.getKey() + "|value=" + mapEntry.getValue());
                }
            }
        });
        User user = new User(credentialMap.get("username"),credentialMap.get("password"));
        return  Mono.justOrEmpty(new UsernamePasswordAuthenticationToken(user,credentialMap.get("password"), List.of(new SimpleGrantedAuthority("ADMIN"))));
    }
    else{
       if(StringUtils.isNotBlank(token)){
           if(StringUtils.contains(token,"Bearer")){
               return  Mono.justOrEmpty(new MyToken(AuthorityUtils.NO_AUTHORITIES,token.substring(7)));
           }else{
               return  Mono.justOrEmpty(new MyToken(AuthorityUtils.NO_AUTHORITIES,token));
           }
       }
    }
}
throw  new IllegalArgumentException("Invalid Access");
}
  }

But after printing log statement within subscribe method program flow is getting halted,no exception.
I think subscribe() method is causing some thread level issue.Can someone figureout the problem????


问:
Issue where worker is not receiving `canvas` message when using NextJS (react)
I have a React Class component AudioVisualizer which is meant to take a MediaStream and display a visualizer of the audio on a canvas that's controlled by a worker. However I have an issue where the canvas is not being updated and after some debugging it looks like the worker is not receiving the canvas message, but I don't understand why. I far as I can see everything should work.

AudioVisualizer component

import { createRef, RefObject, Component } from "react";

type AudioAnalyserConfig = {
    fftSize?: number,
    smoothingTimeConstant?: number,
    minDecibels?: number,
    maxDecibels?: number
};

interface AudioVisualizerProps {
    stream: MediaStream,
    config?: AudioAnalyserConfig
}

export class AudioVisualizer extends Component<AudioVisualizerProps> {
    stream: MediaStream;
    config?: AudioAnalyserConfig;
    audioContext?: AudioContext;
    analyser?: AnalyserNode;
    canvas?: HTMLCanvasElement;
    bufferLength?: number;
    dataArray: Uint8Array = new Uint8Array();
    source?: MediaStreamAudioSourceNode;
    worker?: Worker;
    offscreenCanvas = false;

    constructor(props: AudioVisualizerProps) {
        super(props)
        this.stream = props.stream;
        this.config = props.config;

    }

    componentDidMount() {
        this.audioContext = new AudioContext();
        this.setAnalyser();
        this.setSource();
        this.worker = new Worker(new URL('../worker.ts', import.meta.url));

        if (!this.canvas) throw Error('No canvas');
        if (!this.offscreenCanvas && this.worker) {
            console.log(this.worker);
            const canvas = this.canvas.transferControlToOffscreen();
            this.worker.postMessage({ type: 'canvas', canvas }, [canvas]);
            this.offscreenCanvas = true;
        }

        this.animate();
    }

    componentWillUnmount(): void {
        if (this.worker) {
            this.worker.terminate();
        }
    }

    render() {
        return <canvas ref={this.setCanvasRef} ></canvas>
    }

    private setCanvasRef = (element: HTMLCanvasElement) => {
        this.canvas = element;
    }

    private setSource() {
        if (!this.audioContext) throw Error("No Audio Context");
        if (!this.analyser) throw Error("No Analyser");

        this.source = this.audioContext.createMediaStreamSource(this.stream);
        this.source.connect(this.analyser)
    }

    private setAnalyser() {
        if (!this.audioContext) throw Error('No Audio Context');
        if (!this.canvas) throw Error('No Current on Canvas Ref');

        this.analyser = this.audioContext.createAnalyser();
        this.bufferLength = this.analyser.frequencyBinCount;
        this.dataArray = new Uint8Array(this.bufferLength);

        if (!this.config) return;
        this.analyser.fftSize = this.config.fftSize || 2048;
        this.analyser.smoothingTimeConstant = this.config.smoothingTimeConstant || 0.8;
        this.analyser.minDecibels = this.config.minDecibels || -100;
        this.analyser.maxDecibels = this.config.maxDecibels || -30;
    }

    animate = () => {
        if (!this.analyser) throw Error("No Analyser");
        if (!this.worker) throw Error('No worker');

        this.analyser.getByteFrequencyData(this.dataArray);
        this.worker.postMessage({ type: 'frame', bufferLength: this.bufferLength, dataArray: this.dataArray }, {});
        requestAnimationFrame(this.animate);
    };
}
```
<h3><code>worker.ts</code></h3>
<pre class="lang-ts prettyprint-override"><code>let canvas: HTMLCanvasElement | null = null;

const drawVisualizer = ({ bufferLength, dataArray }: { bufferLength: number, dataArray: any[] }) => {
    if (!canvas) return;
    let barHeight;
    const barWidth = canvas.width / 2 / bufferLength;
    let firstX = 0;
    let secondX = bufferLength * barWidth;
    const ctx = canvas.getContext("2d");

    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < bufferLength; i++) {
        barHeight = dataArray[i];
        const red = (i * barHeight) / 10;
        const green = i * 4;
        const blue = barHeight / 4 - 12;
        ctx.fillStyle = `rgb(${red}, ${green}, ${blue})`;
        ctx.fillRect(
            canvas.width / 2 - firstX,
            canvas.height - barHeight,
            barWidth,
            barHeight
        );
        firstX += barWidth;
        ctx.fillRect(secondX, canvas.height - barHeight, barWidth, barHeight);
        secondX += barWidth;
    }
};

addEventListener('message', e => {
    // console.log("Worker: Message received from main script");
    const { type, bufferLength, dataArray, canvas: canvasMessage } = e.data;
    console.log(type); // only `frame` prints
    switch (type) {
        case 'canvas':
            canvas = canvasMessage;
            break;
        case 'frame':
            drawVisualizer({ bufferLength, dataArray });
            break;
        default:
            break;
    }
});

export { }
</code>```

Body:
I have a React Class component AudioVisualizer which is meant to take a MediaStream and display a visualizer of the audio on a canvas that's controlled by a worker. However I have an issue where the canvas is not being updated and after some debugging it looks like the worker is not receiving the canvas message, but I don't understand why. I far as I can see everything should work.

AudioVisualizer component

import { createRef, RefObject, Component } from "react";

type AudioAnalyserConfig = {
    fftSize?: number,
    smoothingTimeConstant?: number,
    minDecibels?: number,
    maxDecibels?: number
};

interface AudioVisualizerProps {
    stream: MediaStream,
    config?: AudioAnalyserConfig
}

export class AudioVisualizer extends Component<AudioVisualizerProps> {
    stream: MediaStream;
    config?: AudioAnalyserConfig;
    audioContext?: AudioContext;
    analyser?: AnalyserNode;
    canvas?: HTMLCanvasElement;
    bufferLength?: number;
    dataArray: Uint8Array = new Uint8Array();
    source?: MediaStreamAudioSourceNode;
    worker?: Worker;
    offscreenCanvas = false;

    constructor(props: AudioVisualizerProps) {
        super(props)
        this.stream = props.stream;
        this.config = props.config;

    }

    componentDidMount() {
        this.audioContext = new AudioContext();
        this.setAnalyser();
        this.setSource();
        this.worker = new Worker(new URL('../worker.ts', import.meta.url));

        if (!this.canvas) throw Error('No canvas');
        if (!this.offscreenCanvas && this.worker) {
            console.log(this.worker);
            const canvas = this.canvas.transferControlToOffscreen();
            this.worker.postMessage({ type: 'canvas', canvas }, [canvas]);
            this.offscreenCanvas = true;
        }

        this.animate();
    }

    componentWillUnmount(): void {
        if (this.worker) {
            this.worker.terminate();
        }
    }

    render() {
        return <canvas ref={this.setCanvasRef} ></canvas>
    }

    private setCanvasRef = (element: HTMLCanvasElement) => {
        this.canvas = element;
    }

    private setSource() {
        if (!this.audioContext) throw Error("No Audio Context");
        if (!this.analyser) throw Error("No Analyser");

        this.source = this.audioContext.createMediaStreamSource(this.stream);
        this.source.connect(this.analyser)
    }

    private setAnalyser() {
        if (!this.audioContext) throw Error('No Audio Context');
        if (!this.canvas) throw Error('No Current on Canvas Ref');

        this.analyser = this.audioContext.createAnalyser();
        this.bufferLength = this.analyser.frequencyBinCount;
        this.dataArray = new Uint8Array(this.bufferLength);

        if (!this.config) return;
        this.analyser.fftSize = this.config.fftSize || 2048;
        this.analyser.smoothingTimeConstant = this.config.smoothingTimeConstant || 0.8;
        this.analyser.minDecibels = this.config.minDecibels || -100;
        this.analyser.maxDecibels = this.config.maxDecibels || -30;
    }

    animate = () => {
        if (!this.analyser) throw Error("No Analyser");
        if (!this.worker) throw Error('No worker');

        this.analyser.getByteFrequencyData(this.dataArray);
        this.worker.postMessage({ type: 'frame', bufferLength: this.bufferLength, dataArray: this.dataArray }, {});
        requestAnimationFrame(this.animate);
    };
}

worker.ts

let canvas: HTMLCanvasElement | null = null;

const drawVisualizer = ({ bufferLength, dataArray }: { bufferLength: number, dataArray: any[] }) => {
    if (!canvas) return;
    let barHeight;
    const barWidth = canvas.width / 2 / bufferLength;
    let firstX = 0;
    let secondX = bufferLength * barWidth;
    const ctx = canvas.getContext("2d");

    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < bufferLength; i++) {
        barHeight = dataArray[i];
        const red = (i * barHeight) / 10;
        const green = i * 4;
        const blue = barHeight / 4 - 12;
        ctx.fillStyle = `rgb(${red}, ${green}, ${blue})`;
        ctx.fillRect(
            canvas.width / 2 - firstX,
            canvas.height - barHeight,
            barWidth,
            barHeight
        );
        firstX += barWidth;
        ctx.fillRect(secondX, canvas.height - barHeight, barWidth, barHeight);
        secondX += barWidth;
    }
};

addEventListener('message', e => {
    // console.log("Worker: Message received from main script");
    const { type, bufferLength, dataArray, canvas: canvasMessage } = e.data;
    console.log(type); // only `frame` prints
    switch (type) {
        case 'canvas':
            canvas = canvasMessage;
            break;
        case 'frame':
            drawVisualizer({ bufferLength, dataArray });
            break;
        default:
            break;
    }
});

export { }


问:
Force map to stay within image
I'm trying to use leaflet to create a GTA V map, however I would like for the map to not show the outside of the map boundaries, and instead be cut off, I don't know if this is possible, I'll try to show what I mean below.

I don't want the user to be able to move the map further out than where the image of the GTA V map ends, so no "grey area", is this possible?

Title: Force map to stay within image


问:
Django query to get frequency-per-day of events with a DateTimeField
I have a model with events that each have a DateTimeField and can readily write a query that gets me the count of events per day:

MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id'))
```
<p>which produces (Postgresql) SQL like:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT ("MyEvents"."date_time")::date AS "day",
       COUNT("MyEvents"."id") AS "count"
FROM "Doors_visit"
GROUP BY ("MyEvents"."date_time")::date
</code>```

which produces a QuerySet that returns dicts containing 'date' and 'count'.

What I would like is to produce a histogram of such counts, by which I mean plotting hte 'count' as a category along the x-axis and the number of times we've seen that 'count' on the y-axis.

In short, I want to aggregate the counts, or count the counts if you prefer.

Alas, Django complains vehemently when I try:

MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')).annotate(count_count=Count('count'))
```
<p>produces:</p>
```django.core.exceptions.FieldError: Cannot compute Count('count'): 'count' is an aggregate
```

Fair enough. Which raises the question, can this be done in one Django Query without resorting to Raw SQL? I mean in SQL it's easy enough to query the results of a query (subquerying). Django seems to lack the smarts for this (I mean, rather than complain it could just wrap the query to date as a subquery and build a query from there, but it elects not to).

I mean, one work around is to extract the count of counts in Python from the result of the first query above. But it can be done in SQL, and arguably should be done in SQL, and I'm left wondering if in the forward march of Django's evolution and my learning there isn't an overlooked feature of Django or some sly trick that makes this possible which I have simply not uncovered.

Body:
I have a model with events that each have a DateTimeField and can readily write a query that gets me the count of events per day:

MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id'))

which produces (Postgresql) SQL like:

SELECT ("MyEvents"."date_time")::date AS "day",
       COUNT("MyEvents"."id") AS "count"
FROM "Doors_visit"
GROUP BY ("MyEvents"."date_time")::date

which produces a QuerySet that returns dicts containing 'date' and 'count'.

What I would like is to produce a histogram of such counts, by which I mean plotting hte 'count' as a category along the x-axis and the number of times we've seen that 'count' on the y-axis.

In short, I want to aggregate the counts, or count the counts if you prefer.

Alas, Django complains vehemently when I try:

MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')).annotate(count_count=Count('count'))

produces:

django.core.exceptions.FieldError: Cannot compute Count('count'): 'count' is an aggregate

Fair enough. Which raises the question, can this be done in one Django Query without resorting to Raw SQL? I mean in SQL it's easy enough to query the results of a query (subquerying). Django seems to lack the smarts for this (I mean, rather than complain it could just wrap the query to date as a subquery and build a query from there, but it elects not to).

I mean, one work around is to extract the count of counts in Python from the result of the first query above. But it can be done in SQL, and arguably should be done in SQL, and I'm left wondering if in the forward march of Django's evolution and my learning there isn't an overlooked feature of Django or some sly trick that makes this possible which I have simply not uncovered.


问:
How to deploy to Vercel staging environment using bitbucket pipelines and Vercel CLI
I have 3 environments (preview, staging and production)
Also I followed these steps to set everything up but I noticed that staging is picking up preview environment variables because of this line:

```<code>- vercel pull --yes --environment=preview --token=$VERCEL_TOKEN
</code>```

I tried to find the correct value for --environment argument but i failed to do so.

Do you know what could it be?

Thanks in advance :)

Body:
I have 3 environments (preview, staging and production)
Also I followed these steps to set everything up but I noticed that staging is picking up preview environment variables because of this line:

- vercel pull --yes --environment=preview --token=$VERCEL_TOKEN

I tried to find the correct value for --environment argument but i failed to do so.

Do you know what could it be?

Thanks in advance :)


问:
how can i play video in tableview cell and load video in background swift ios
I'm creating an app like TikTok reels I want to load upcoming videos earlier. is there any custom library or AVPlayer functionality to apply this task?

I'm trying to load the video in the background is there any concept of cache?


问:
Is there a way to change running jobs created by srun, sbatch salloc to interactive mode?
The jobs are running with the slurm by executing the command below.

```<code>srun --pty --x11 ./my_work1
sbatch -p P1 ./mywork2
</code>```

Is there a way to change jobs that are already running to interactive mode?

Body:
The jobs are running with the slurm by executing the command below.

srun --pty --x11 ./my_work1
sbatch -p P1 ./mywork2

Is there a way to change jobs that are already running to interactive mode?


问:
The DateTimeField model field stores an incorrect value
models.py

```<code>class CollectCreativeDate(models.Model):
    date_changed = models.DateTimeField()
</code>```

migrations

```<code>class Migration(migrations.Migration):

    dependencies = [
        ('creative_performer', '0014_alter_creativecategory_labels_and_more'),
    ]

    operations = [
        migrations.AlterField(
            model_name='collectcreativedate',
            name='date_changed',
            field=models.DateTimeField(),
        ),
    ]
</code>```

logic.py

```<code>def foo():
.....
    logger.info(f'Database successfully updated at {now()}')
    CollectCreativeDate(date_changed=now()).save()
</code>```

settings.py

```<code>LANGUAGE_CODE = 'en-us'

USE_TZ = False

TIME_ZONE = 'Europe/Istanbul'
</code>```

The result values

log: Database successfully updated at 2022-12-28 15:03:57.218815

DB: 2022-12-28 12:03:57.219012+00

why different values in the database and in the logs ?

Body:
models.py

class CollectCreativeDate(models.Model):
    date_changed = models.DateTimeField()

migrations

class Migration(migrations.Migration):

    dependencies = [
        ('creative_performer', '0014_alter_creativecategory_labels_and_more'),
    ]

    operations = [
        migrations.AlterField(
            model_name='collectcreativedate',
            name='date_changed',
            field=models.DateTimeField(),
        ),
    ]

logic.py

def foo():
.....
    logger.info(f'Database successfully updated at {now()}')
    CollectCreativeDate(date_changed=now()).save()

settings.py

LANGUAGE_CODE = 'en-us'

USE_TZ = False

TIME_ZONE = 'Europe/Istanbul'

The result values

log: Database successfully updated at 2022-12-28 15:03:57.218815

DB: 2022-12-28 12:03:57.219012+00

why different values in the database and in the logs ?


问:
Matlab 2019 gives abnormal errors when launching
I have just downloaded Matlab toolbox and I think I did a mistake somewhere but don't know where. I have two versions of Matlab on my machine and I when I launch Matlab 19, the one I want to use, I get this two lines of error:

Unable to resolve the name slreq.utils.loadLinkSet.

Error in rmiml.getAll

When I run the first section, which is merely

```<code>clear all; close all; clc;
</code>```

I get this error

Cannot find builtin function '_LiveEvaluate'

I really don't know what happened and how I could solve it. I have checked the environment variables and they seem okay.

When I run the whole script (without doing by section), I have this error occurring

Attempt to execute SCRIPT mrdivide as a function:
C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\mrdivide.m
Error in Sandbox (line 25)
X=1/2*eye(n);

Body:
I have just downloaded Matlab toolbox and I think I did a mistake somewhere but don't know where. I have two versions of Matlab on my machine and I when I launch Matlab 19, the one I want to use, I get this two lines of error:

Unable to resolve the name slreq.utils.loadLinkSet.

Error in rmiml.getAll

When I run the first section, which is merely

clear all; close all; clc;

I get this error

Cannot find builtin function '_LiveEvaluate'

I really don't know what happened and how I could solve it. I have checked the environment variables and they seem okay.

When I run the whole script (without doing by section), I have this error occurring

Attempt to execute SCRIPT mrdivide as a function:
C:\Program Files\MATLAB\R2019b\toolbox\matlab\ops\mrdivide.m
Error in Sandbox (line 25)
X=1/2*eye(n);


问:
Flutter xCode iOS archive not working with provisional certificatte
xCode build is successful.

When I try to archive in xCode in Runner.app it has two option import profile and download profile. I tried import profile and selected project-name.mobileprovision it's not working. It showing the below error.

In distribution certificate when I tried to select the distribution certificate it's showing "No account for team 'Team Name'"

Don't know what I am missing here. Please help me with this.


问:
how to run an index.html file in build folder of the react application which was routed using react-router package?
I have a React Application where navigation and routing are achieved by React-Router Package ,
The Router Work Well in Localhost. when I take a build  and serve it in server it works well . but when I tried to Run the Index.html file in build folder without any server it doesn't work .

I Want to Run My application without any server and navigate between pages.
I do not Want to show # symbol in the address bar.