问:
Sharepoint Online automating the handling of pages with different versions of content
I'm currently learning how to extend Sharepoint Online (ie Sharepoint Modern) and am not sure how to achieve the below, so any pointers would help.

We want to create a site to be used as a knowledge base for pages on specific subjects.

(as this site would only have these pages would it matter f it were a Team Site or a Communication site? I suspect it dsoesn't matter)

There will be multiple revisions to each page, but we would like to keep earlier versions and just flag which is the current one.

Example :

Page 1 : Introduction to company systems
Initially this would be created as Version 1, and be visible to all users.

Later we create a new,edited copy that is Version 2.

Both remain published but we want to make sure visiters are offered Version 2.

What we would like:

A way to flag the version number against each page. I assume this would normally be done by a column in a list of the pages eg column 'Version'?

A way to flag the page that is the current version. Again, a list column eg column 'IsCurrentVersion'?

Is there any way to edit these columns (ie 'Version' and 'IsCurrentVersion') from within the page rather than having to open the  list and edit the list row? (eg Possibly using PowerApps?)

Is there a way so that when an editor flags a page as the current version, an automated process goes through all other version of that page, and sets 'IsCurrentVersion' to 'No', so only one page is ever seen as the current version? (eg using Power Automate?)

A way so that when a user views a page, it checks to see if it is the current version (eg by checking the list column 'IsCurrentVersion') and:
if it IS the current version it offers a link to a list of previous versions,
or if it IS NOT the current version, javascript adds a class to the page so it is obvious this is not the current version (eg, a tinted overlay, pseudo element watermark) and offers a link to the current verison (would this be done with spfx extensions)?

Finally, (this may not be needed) a way so that some users cann ONLY see the current version - -e if they manage to get the url to a page which is 'IsCurrentVersion' set to 'No', they can not open it, or it redirects them to the current version, or sets a class with styling to hide the content (the last option is least desirable as it it is easily overcome by the user).

I am hoping this is possible in Sharepoint, and showing me where to look for solutions would be fantastic.


来源: stackexchange

问:
Problem with file access in MSVC 2019 concerning Linker flag (No (/ALLOWISOLATION:NO))
I have an observation that I don't understand the reason. Can someone explain it?

I am doing a simple test console application using visual studio 2019. My OS is Windows 11.

There is a flag in visual studio project settings for Linker > Manifest file > Allow Isolation, which uses the default value "YES.

My test code is a simple file write access as follows:

```<code>#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream out;

    cout << "Enter out file path:\n";

    char path[1000];
    cin.getline(path, 1000);

    out.open(path, std::ofstream::out | std::ofstream::trunc);

    if (out.is_open()) {
        cout << "Target file opened.\n";

        out << "hello";
        out.flush();

        if (out.bad()) {
            cout << "Error : bad.\n";
        }
        else {
            cout << "Success : not bad!\n";
        }
    } else {
        cout << "Failed to open file.\n";
    }

    out.close();

    system("pause");

    return 0;
}
</code>```

I use a target directory namely "C:\Program files\Folder".

I have 3 users namely "User", "u1", "u2". among which "User" is an administrator type and the other two are standard type.

"User" can create a file in the target directory without changing any permissions.

"U1" has been given write and modify permission on the target directory.

"U2" has no write or modify permission there.

I am logged in with "User". I double-click the exe to run under "User" and use "Run as different user" to run as "U1" or "U2".

now the output without "Allow Isolation" flag is the same for all 3 users.

But only the execution under "U1" actually made the file!

```<code>Enter out file path:
C:\Program Files\Folder\test
Target file opened.
Success : not bad!
Press any key to continue . . .
</code>```

I need an explanation on how removing "Allow Isolation" flag led to not being able to detect file errors.

Are these errors still somehow detectable.

I have already read this:

When isolation is disabled for an executable, the Windows loader won't attempt to find an application manifest for the newly created process. The new process won't have a default activation context, even if there's a manifest inside the executable or placed in the same directory as the executable with name .exe.manifest.

I tried with and without this flag. With the flag, everything is fine. I only got a bit surprised that "User" had been denied to access but I noticed that I can get the expected result by changing "UAC Execution Level" flag to "highestLevel" in the same settings page.

ContentLicense: CC BY-SA 4.0

Body:
I have an observation that I don't understand the reason. Can someone explain it?

I am doing a simple test console application using visual studio 2019. My OS is Windows 11.

There is a flag in visual studio project settings for Linker > Manifest file > Allow Isolation, which uses the default value "YES.

My test code is a simple file write access as follows:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream out;

    cout << "Enter out file path:\n";

    char path[1000];
    cin.getline(path, 1000);

    out.open(path, std::ofstream::out | std::ofstream::trunc);

    if (out.is_open()) {
        cout << "Target file opened.\n";

        out << "hello";
        out.flush();

        if (out.bad()) {
            cout << "Error : bad.\n";
        }
        else {
            cout << "Success : not bad!\n";
        }
    } else {
        cout << "Failed to open file.\n";
    }

    out.close();

    system("pause");

    return 0;
}

I use a target directory namely "C:\Program files\Folder".

I have 3 users namely "User", "u1", "u2". among which "User" is an administrator type and the other two are standard type.

"User" can create a file in the target directory without changing any permissions.

"U1" has been given write and modify permission on the target directory.

"U2" has no write or modify permission there.

I am logged in with "User". I double-click the exe to run under "User" and use "Run as different user" to run as "U1" or "U2".

now the output without "Allow Isolation" flag is the same for all 3 users.

But only the execution under "U1" actually made the file!

Enter out file path:
C:\Program Files\Folder\test
Target file opened.
Success : not bad!
Press any key to continue . . .

I need an explanation on how removing "Allow Isolation" flag led to not being able to detect file errors.

Are these errors still somehow detectable.

I have already read this:

When isolation is disabled for an executable, the Windows loader won't attempt to find an application manifest for the newly created process. The new process won't have a default activation context, even if there's a manifest inside the executable or placed in the same directory as the executable with name .exe.manifest.

I tried with and without this flag. With the flag, everything is fine. I only got a bit surprised that "User" had been denied to access but I noticed that I can get the expected result by changing "UAC Execution Level" flag to "highestLevel" in the same settings page.


问:
Secure way to use a github access token in a docker image?
I'm building a docker image. I want the image to be able to pull from private repos. Per some advice I found on a blog, I have this line in the Dockerfile:

RUN git config --global url."https://<access_token_goes_here>:@github.com/".insteadOf "https://github.com/"

It works, but now I've got the access token embedded in the container and in the Dockerfile which doesn't seem secure.

What's the best practice for this?


问:
Why gcc throws "error: aggregate value used" error for struct but not for integer arrays?
gcc is able to compile with no problems
if I try to assign the address of global integer array into a field a global struct
as you can see in the snippet below

```<code>#include <stdio.h>
#include <stdint.h>

int integer_array[4] = {0, 1, 2, 3};

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};

int main() {
        printf("0x%lx\n", s.addr);
}
</code>```

However, If I modify the above code and instead of an array I pass a structure, gcc is throwing
the following error.

```<code>#include <stdio.h>
#include <stdint.h>

struct test {
        int integer_array[4];
};
struct test t;

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};

int main() {
        printf("0x%lx\n", s.addr);
}
</code>```
```<code>test.c:15:1: error: aggregate value used where an integer was expected
   15 | };
</code>```

Can anybody explain to me why this is happening ?

Body:
gcc is able to compile with no problems
if I try to assign the address of global integer array into a field a global struct
as you can see in the snippet below

#include <stdio.h>
#include <stdint.h>

int integer_array[4] = {0, 1, 2, 3};

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};

int main() {
        printf("0x%lx\n", s.addr);
}

However, If I modify the above code and instead of an array I pass a structure, gcc is throwing
the following error.

#include <stdio.h>
#include <stdint.h>

struct test {
        int integer_array[4];
};
struct test t;

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};

int main() {
        printf("0x%lx\n", s.addr);
}

test.c:15:1: error: aggregate value used where an integer was expected
   15 | };

Can anybody explain to me why this is happening ?


问:
How can I style validation errors in Codeigniter 4?
I have migrated from Codeigniter version 3 to 4.
In version 3, in the Validation.php file, I could style and add class errors like this:

original :

```<code>$lang['form_validation_required'] = 'The {field} field is required.';
</code>```

manipulated:

```<code>$lang['form_validation_required'] = 'The <strong class="text-danger">{field}</strong> field is required.';
</code>```

But this is not possible in version 4.

```<code>'required' => 'The <strong class="text-danger">{field}</strong> field is required.'
</code>```

** Validation.php path : system/language/en

Body:
I have migrated from Codeigniter version 3 to 4.
In version 3, in the Validation.php file, I could style and add class errors like this:

original :

$lang['form_validation_required'] = 'The {field} field is required.';

manipulated:

$lang['form_validation_required'] = 'The {field} field is required.';

But this is not possible in version 4.

'required' => 'The {field} field is required.'

** Validation.php path : system/language/en


问:
DateRangePicker display date-range-key instead of date on selected
How to display date-range-key instead of date except Custom Range? eg: Display "Yesterday" not "2022-12-13 - 2022-12-13" on selected/apply. But i still want to use the actual date value for form submission. Maybe i can put the actual date on hidden input. But again how to dislay date-range-key? eg: Yesterday, Last 7 Days, This Month, etc.

Form

```<code> <input type="text" class="form-control" placeholder="" aria-label="purchaseTime" aria-describedby="basic" name="dateFilter" id="dateFilter" value="{{ $datesFilter }}" readonly>
</code>```

Script

```<code>$(function() {
  $('input[name="dateFilter"]').daterangepicker({
        "autoApply": true,
        ranges: {
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(7, 'days'), moment().subtract(1, 'days')],
            'Last 30 Days': [moment().subtract(30, 'days'), moment().subtract(1, 'days')],
            'This Month': [moment().startOf('month'), moment().subtract(1, 'days')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },

        "maxDate": moment().subtract(1, 'days'),
        "alwaysShowCalendars": true,
        opens: "left",
        locale: {
          direction: "ltr",
          format: 'YYYY-MM-DD',
        //   separator: " ~ ",
        }
  });
});
</code>```

Body:
How to display date-range-key instead of date except Custom Range? eg: Display "Yesterday" not "2022-12-13 - 2022-12-13" on selected/apply. But i still want to use the actual date value for form submission. Maybe i can put the actual date on hidden input. But again how to dislay date-range-key? eg: Yesterday, Last 7 Days, This Month, etc.

Form

 <input type="text" class="form-control" placeholder="" aria-label="purchaseTime" aria-describedby="basic" name="dateFilter" id="dateFilter" value="{{ $datesFilter }}" readonly>

Script

$(function() {
  $('input[name="dateFilter"]').daterangepicker({
        "autoApply": true,
        ranges: {
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(7, 'days'), moment().subtract(1, 'days')],
            'Last 30 Days': [moment().subtract(30, 'days'), moment().subtract(1, 'days')],
            'This Month': [moment().startOf('month'), moment().subtract(1, 'days')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },

        "maxDate": moment().subtract(1, 'days'),
        "alwaysShowCalendars": true,
        opens: "left",
        locale: {
          direction: "ltr",
          format: 'YYYY-MM-DD',
        //   separator: " ~ ",
        }
  });
});


问:
TypeScript - how to define a type inside a tuple based on the combination of a generic + another value of the tuple? (like tuple[1]: T[tuple[0]])
As the title goes: how to define a type, based on the combination of a generic + another value, in a tuple, like tuple[1]: T[tuple[0]]?

Context:

I'm using a tuple to store different values, in order to then create a table.

I have an array of rows of a certain type (ex. MyDataDTO) that holds all the different properties of a row.

The tuple defines a single column of the table. The full table definition will be an array of these tuples.

The tuple has 2 values:

[0] -> field of the column, can only be one of the keys of MyDataDTO (no issues here)

[1] -> a function that accepts the value of the cell as parameter (here is the problem) and renders it.

This is what I tried:

```<code>
type ColumnDefinitionTuple<TRowData> = {
    [K in keyof TRowData]: [K, (cellValue: TRowData[K]) => string];
}[keyof TRowData];

type MyDataDTO = {
    id: number;
    name: string;
    code: number;
};

const tableData: MyDataDTO[] = [
    { id: 1, name: "test-1", code: 101 },
    { id: 2, name: "test-2", code: 102 },
    { id: 3, name: "test-3", code: 103 },
];

const tableColumnsDefinition: ColumnDefinitionTuple<MyDataDTO> = [
    "id", // OK -> works with type-safety and autocomplete
    (value) => "", // NOT OK -> the "value" parameter is typed as "any", it should be typed as "number" because MyDataDTO["id"] (TRowData[K]) is a number
];

</code>```

Does anyone know a solution for this?

Thanks!

Body:
As the title goes: how to define a type, based on the combination of a generic + another value, in a tuple, like tuple[1]: T[tuple[0]]?

Context:

I'm using a tuple to store different values, in order to then create a table.

I have an array of rows of a certain type (ex. MyDataDTO) that holds all the different properties of a row.

The tuple defines a single column of the table. The full table definition will be an array of these tuples.

The tuple has 2 values:

[0] -> field of the column, can only be one of the keys of MyDataDTO (no issues here)

[1] -> a function that accepts the value of the cell as parameter (here is the problem) and renders it.

This is what I tried:

type ColumnDefinitionTuple<TRowData> = {
    [K in keyof TRowData]: [K, (cellValue: TRowData[K]) => string];
}[keyof TRowData];

type MyDataDTO = {
    id: number;
    name: string;
    code: number;
};

const tableData: MyDataDTO[] = [
    { id: 1, name: "test-1", code: 101 },
    { id: 2, name: "test-2", code: 102 },
    { id: 3, name: "test-3", code: 103 },
];

const tableColumnsDefinition: ColumnDefinitionTuple<MyDataDTO> = [
    "id", // OK -> works with type-safety and autocomplete
    (value) => "", // NOT OK -> the "value" parameter is typed as "any", it should be typed as "number" because MyDataDTO["id"] (TRowData[K]) is a number
];

Does anyone know a solution for this?

Thanks!


问:
selenium Unable to locate tiktok caption
After login into tiktok with selenium the selenium can't find the caption input field. my code is this

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

cap = driver.find_element(By.CLASS_NAME, 'public-DraftStyleDefault-block')
cap.send_key('this is test caption')

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

Error Is this

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".public-DraftStyleDefault-block"}
  (Session info: chrome=108.0.5359.99)
Stacktrace:
Backtrace:
        (No symbol) [0x010EF243]
        (No symbol) [0x01077FD1]
        (No symbol) [0x00F6D04D]
        (No symbol) [0x00F9C0B0]
        (No symbol) [0x00F9C22B]
        (No symbol) [0x00FCE612]
        (No symbol) [0x00FB85D4]
        (No symbol) [0x00FCC9EB]
        (No symbol) [0x00FB8386]
        (No symbol) [0x00F9163C]
        (No symbol) [0x00F9269D]
        GetHandleVerifier [0x01389A22+2655074]
        GetHandleVerifier [0x0137CA24+2601828]
        GetHandleVerifier [0x01198C0A+619850]
        GetHandleVerifier [0x01197830+614768]
        (No symbol) [0x010805FC]
        (No symbol) [0x01085968]
        (No symbol) [0x01085A55]
        (No symbol) [0x0109051B]
        BaseThreadInitThunk [0x7680FEF9+25]
        RtlGetAppContainerNamedObjectPath [0x77357BBE+286]
        RtlGetAppContainerNamedObjectPath [0x77357B8E+238]
</code>```

How to fix this...

i try to automate tik tok video upload.

Body:
After login into tiktok with selenium the selenium can't find the caption input field. my code is this

cap = driver.find_element(By.CLASS_NAME, 'public-DraftStyleDefault-block')
cap.send_key('this is test caption')

Error Is this

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".public-DraftStyleDefault-block"}
  (Session info: chrome=108.0.5359.99)
Stacktrace:
Backtrace:
        (No symbol) [0x010EF243]
        (No symbol) [0x01077FD1]
        (No symbol) [0x00F6D04D]
        (No symbol) [0x00F9C0B0]
        (No symbol) [0x00F9C22B]
        (No symbol) [0x00FCE612]
        (No symbol) [0x00FB85D4]
        (No symbol) [0x00FCC9EB]
        (No symbol) [0x00FB8386]
        (No symbol) [0x00F9163C]
        (No symbol) [0x00F9269D]
        GetHandleVerifier [0x01389A22+2655074]
        GetHandleVerifier [0x0137CA24+2601828]
        GetHandleVerifier [0x01198C0A+619850]
        GetHandleVerifier [0x01197830+614768]
        (No symbol) [0x010805FC]
        (No symbol) [0x01085968]
        (No symbol) [0x01085A55]
        (No symbol) [0x0109051B]
        BaseThreadInitThunk [0x7680FEF9+25]
        RtlGetAppContainerNamedObjectPath [0x77357BBE+286]
        RtlGetAppContainerNamedObjectPath [0x77357B8E+238]

How to fix this...

i try to automate tik tok video upload.


问:
Find nearest test results before and after an medical appointment
I like to understand in general how to approach this problem at work. I have a list of dates for patient appointments. I also have another list of datas for patient test results (not necessarily on the same day of the appointments). How do I find the nearest testt results before and after an appointment date for the same patient.

I have tried to put all dates for both appointments and test results into a pandas dataframe and use a variable (event) to indicate the types of dates (test or appointment). There is a value column recording the values of the tests and null for appointment dates. Then I got stuck without knowing how to proceed. I am thinking to use groupby(patient) to get the records for each patient and go from there, but could not figure out the next step.


问:
Invalid argument (400) - Cannot find key of appropriate type to decrypt AP REP - AES256 CTS mode with HMAC SHA1-96
The issue is observed with "curl --service-name test --negotiate:u http://localhost:8080/api". The command is used to test an API running in the same host protected by Kerberos.
SPN = "test/localhost@EXAMPLE.COM".

I have tried providing all access to Keytab.

Keytab is generated with "/CRYPTO All" flag.

All suggestions provided on Stackover flow have been tried.


问:
How to create a section of cross infos from different tables in Django
I hope that the question below is well posed and it comfy to the rules of the community. Moreover, even if I tried to be more comprehensive as possible, if some more details are needed please feel free to ask for them.

I am developing a web server on the footsteps of Local library from Mozilla Developers

Among the pool of data, I have Odorants, Receptors and the interactions that they are able to make. Please find the models below:

```<code># Create your models here.

class Odorant(models.Model):
    Pubchem_ID = models.IntegerField(primary_key = True)
    Name = models.CharField(max_length =50)
    IUPAC_Name = models.CharField('IUPAC Name', max_length = 250)
    Synonim = models.CharField(max_length = 50)
    SMILES = models.CharField(max_length = 100) #NOT NULL by default
    Molecular_Formula = models.CharField(max_length = 20)
    Molecular_Weight = models.DecimalField(max_digits = 8, decimal_places =4)
    Atom_Count = models.IntegerField()
    Rotatable_Bonds = models.IntegerField()
    Molecular_Refractivity = models.DecimalField(null = True, blank = True, max_digits = 5, decimal_places =3)
    Volume = models.DecimalField(max_digits = 6, decimal_places =2)
    SASA = models.DecimalField('SASA', max_digits = 6, decimal_places =2)
    H_Bond_Donor = models.IntegerField()
    H_Bond_Acceptor = models.IntegerField()
    Total_Charge = models.IntegerField()
    pKa = models.DecimalField('pKa', null = True, blank = True, max_digits = 5, decimal_places =2)
    AlogP = models.DecimalField('AlogP', null = True, blank = True, max_digits = 5, decimal_places =2)
    Polar_Surface_Area = models.DecimalField(max_digits = 5, decimal_places =2)
    Target = models.ManyToManyField('Receptor', null = True, blank = True)

    def __str__(self):
        return f' {self.Name}'

    def get_absolute_url(self):
        return reverse('odorant-detail', kwargs={'pk' : self.pk})

class Receptor(models.Model):
    RepOdor_ID = models.IntegerField('RepOdor ID', primary_key = True)
    Name = models.CharField(max_length = 10)
    Former_Name = models.CharField(max_length = 10)
    Uniprot_ID = models.CharField(max_length = 10)
    Sequence = models.TextField (max_length = 1000)
    Ligand = models.ManyToManyField('Odorant', null = True, blank = True)

    def __str__(self):
        return f'{self.RepOdor_ID},{self.Name}'

    def get_absolute_url(self):
        return reverse('receptor-detail', kwargs={'pk' : self.pk})

class Target(models.Model):
    Pubchem_ID = models.ForeignKey(Odorant, on_delete=models.CASCADE)
    RepOdor_ID = models.ForeignKey(Receptor, on_delete=models.CASCADE)
    Reference_ID = models.ForeignKey(Publication, on_delete=models.CASCADE)
    Odorant = models.CharField(max_length = 50)
    Receptor = models.CharField(max_length = 10)
    EC50 = models.DecimalField('EC50', null = True, blank = True, max_digits = 6, decimal_places =2)

    def __str__(self):
        return f'{self.Receptor}, {self.Odorant}'

    def get_absolute_url(self):
        return reverse('target-detail', kwargs={'pk' : self.pk})

</code>```

The followings are my views.py and urls.py:

```<code>#views.py

from django.shortcuts import redirect, render
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .models import Odorant, Receptor, Target
from django.views import generic

#List view of all the data in the DB
class OdorantListView(generic.ListView):
    model = Odorant
    paginate_by = 98

class ReceptorListView(generic.ListView):
    model = Receptor
    paginate_by = 98

class TargetListView(generic.ListView):
    model = Target
    print(model)
    paginate_by = 98

#View for the single entry of the DB
class OdorantDetailView(generic.DetailView):
    model = Odorant

class ReceptorDetailView(generic.DetailView):
    model = Receptor

class TargetDetailView(generic.DetailView):
    model = Target

</code>```
```<code>#urls.py

from django.urls import path
from . import views
from django.conf.urls import include

urlpatterns = [
        path('', views.index, name='index'),
    path('odorant/', views.OdorantListView.as_view(), name='odorant'),
    path('receptor/', views.ReceptorListView.as_view(), name='receptor'),
    path('target/', views.TargetListView.as_view(), name='target'),
    path('publication/', views.PublicationListView.as_view(), name='publication'),
    path('odorant/<int:pk>', views.OdorantDetailView.as_view(), name='odorant-detail'),
    path('odorant/<int:pk>', views.TargetListView.as_view(), name='odorant-detail'),
    path('receptor/<int:pk>', views.ReceptorDetailView.as_view(), name='receptor-detail'),
    path('target/<int:pk>', views.TargetDetailView.as_view(), name='target
</code>```

Finally, I render those information in this way:

You are looking to {{ odorant.Name }}

 General Information

Pubchem ID: {{ odorant.Pubchem_ID }}

IUPAC Name: {{ odorant.IUPAC_Name }}

```

To give a bit of background to better frame my work, different receptors can interact with different molecules and viceversa. All those interactions are collected in the Target table.

What I am trying to achieve is a new section on the Odorant page where all receptors capable of establishing an interaction with the particular odorous molecule selected are present as clickable links.
What I have tried to do so far is to use the filter function, but it is not effective because the word to be used as a filter has to change every time a different page is opened.

Thank you for the time spent to read my question and, hopefully, answer to it.

Body:
I hope that the question below is well posed and it comfy to the rules of the community. Moreover, even if I tried to be more comprehensive as possible, if some more details are needed please feel free to ask for them.

I am developing a web server on the footsteps of Local library from Mozilla Developers

Among the pool of data, I have Odorants, Receptors and the interactions that they are able to make. Please find the models below:

# Create your models here.

class Odorant(models.Model):
    Pubchem_ID = models.IntegerField(primary_key = True)
    Name = models.CharField(max_length =50)
    IUPAC_Name = models.CharField('IUPAC Name', max_length = 250)
    Synonim = models.CharField(max_length = 50)
    SMILES = models.CharField(max_length = 100) #NOT NULL by default
    Molecular_Formula = models.CharField(max_length = 20)
    Molecular_Weight = models.DecimalField(max_digits = 8, decimal_places =4)
    Atom_Count = models.IntegerField()
    Rotatable_Bonds = models.IntegerField()
    Molecular_Refractivity = models.DecimalField(null = True, blank = True, max_digits = 5, decimal_places =3)
    Volume = models.DecimalField(max_digits = 6, decimal_places =2)
    SASA = models.DecimalField('SASA', max_digits = 6, decimal_places =2)
    H_Bond_Donor = models.IntegerField()
    H_Bond_Acceptor = models.IntegerField()
    Total_Charge = models.IntegerField()
    pKa = models.DecimalField('pKa', null = True, blank = True, max_digits = 5, decimal_places =2)
    AlogP = models.DecimalField('AlogP', null = True, blank = True, max_digits = 5, decimal_places =2)
    Polar_Surface_Area = models.DecimalField(max_digits = 5, decimal_places =2)
    Target = models.ManyToManyField('Receptor', null = True, blank = True)

    def __str__(self):
        return f' {self.Name}'

    def get_absolute_url(self):
        return reverse('odorant-detail', kwargs={'pk' : self.pk})

class Receptor(models.Model):
    RepOdor_ID = models.IntegerField('RepOdor ID', primary_key = True)
    Name = models.CharField(max_length = 10)
    Former_Name = models.CharField(max_length = 10)
    Uniprot_ID = models.CharField(max_length = 10)
    Sequence = models.TextField (max_length = 1000)
    Ligand = models.ManyToManyField('Odorant', null = True, blank = True)

    def __str__(self):
        return f'{self.RepOdor_ID},{self.Name}'

    def get_absolute_url(self):
        return reverse('receptor-detail', kwargs={'pk' : self.pk})

class Target(models.Model):
    Pubchem_ID = models.ForeignKey(Odorant, on_delete=models.CASCADE)
    RepOdor_ID = models.ForeignKey(Receptor, on_delete=models.CASCADE)
    Reference_ID = models.ForeignKey(Publication, on_delete=models.CASCADE)
    Odorant = models.CharField(max_length = 50)
    Receptor = models.CharField(max_length = 10)
    EC50 = models.DecimalField('EC50', null = True, blank = True, max_digits = 6, decimal_places =2)

    def __str__(self):
        return f'{self.Receptor}, {self.Odorant}'

    def get_absolute_url(self):
        return reverse('target-detail', kwargs={'pk' : self.pk})

The followings are my views.py and urls.py:

#views.py

from django.shortcuts import redirect, render
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .models import Odorant, Receptor, Target
from django.views import generic

#List view of all the data in the DB
class OdorantListView(generic.ListView):
    model = Odorant
    paginate_by = 98

class ReceptorListView(generic.ListView):
    model = Receptor
    paginate_by = 98

class TargetListView(generic.ListView):
    model = Target
    print(model)
    paginate_by = 98

#View for the single entry of the DB
class OdorantDetailView(generic.DetailView):
    model = Odorant

class ReceptorDetailView(generic.DetailView):
    model = Receptor

class TargetDetailView(generic.DetailView):
    model = Target

#urls.py

from django.urls import path
from . import views
from django.conf.urls import include

urlpatterns = [
        path('', views.index, name='index'),
    path('odorant/', views.OdorantListView.as_view(), name='odorant'),
    path('receptor/', views.ReceptorListView.as_view(), name='receptor'),
    path('target/', views.TargetListView.as_view(), name='target'),
    path('publication/', views.PublicationListView.as_view(), name='publication'),
    path('odorant/<int:pk>', views.OdorantDetailView.as_view(), name='odorant-detail'),
    path('odorant/<int:pk>', views.TargetListView.as_view(), name='odorant-detail'),
    path('receptor/<int:pk>', views.ReceptorDetailView.as_view(), name='receptor-detail'),
    path('target/<int:pk>', views.TargetDetailView.as_view(), name='target

Finally, I render those information in this way:

You are looking to {{ odorant.Name }}

 General Information

Pubchem ID: {{ odorant.Pubchem_ID }}

IUPAC Name: {{ odorant.IUPAC_Name }}

To give a bit of background to better frame my work, different receptors can interact with different molecules and viceversa. All those interactions are collected in the Target table.

What I am trying to achieve is a new section on the Odorant page where all receptors capable of establishing an interaction with the particular odorous molecule selected are present as clickable links.
What I have tried to do so far is to use the filter function, but it is not effective because the word to be used as a filter has to change every time a different page is opened.

Thank you for the time spent to read my question and, hopefully, answer to it.


问:
Rails cross cluster join with dynamic join condition
So, I have multiple tables in multiple databases.

The user sends me database details, table names, columns to be selected and which column to use as condition for join. The structure is similar to:

```<code>[{ database, table_name, join_column_name }]
</code>```

My current implementation is like this,

Connect to the first DB

Fetch all data from the table

Store the data in a result variable (PG::Result instance)

Extract all unique values in current join_column_name from result to a filter_values array

Connect to next database

Fetch all data where value of current join_column_name is in filter_values

Store the data to a local_result variable (PG::Result instance)

Simulate inner join on result and local_result objects, and store in result

Repeat from step 4

Also, The join_column_name may or may not be an indexed column

In step 8, I have to create a new PG::Result object, and store mapped data from result and local_result objects. How do I attain this?

Is there a better way to do this, without all these custom logic?
I've looked into disable_joins: true, but don't know if it is applicable in this case.

Body:
So, I have multiple tables in multiple databases.

The user sends me database details, table names, columns to be selected and which column to use as condition for join. The structure is similar to:

[{ database, table_name, join_column_name }]

My current implementation is like this,

Connect to the first DB

Fetch all data from the table

Store the data in a result variable (PG::Result instance)

Extract all unique values in current join_column_name from result to a filter_values array

Connect to next database

Fetch all data where value of current join_column_name is in filter_values

Store the data to a local_result variable (PG::Result instance)

Simulate inner join on result and local_result objects, and store in result

Repeat from step 4

Also, The join_column_name may or may not be an indexed column

In step 8, I have to create a new PG::Result object, and store mapped data from result and local_result objects. How do I attain this?

Is there a better way to do this, without all these custom logic?
I've looked into disable_joins: true, but don't know if it is applicable in this case.


问:
AgGrid React checkbox selection by default
I have around 15k records usecase  with row selection as checkbox and it's under a overlay menu , how to preserve the state of selected checkbox on menu closed.

On close of menu , and when I reopen, the selected checkbox should be marked


问:
SDIO probe function isn't been called after moving SDIO device driver library to an old Linux platform using platform device and no device tree
I currently porting a sdio device driver (which's working on linux 4.3 or higher) to an old linux platform 3.10.14. The new one uses device tree to manage sdio bus and the driver uses some sdio api like sdio_register_driver, int sdio_probe(struct sdio_func*, struct sdio_device_id*), but the old one uses platform device with api platform_device_register used in the kernel. I installed the module to system have the old kernel and the probe function isn't called, please help me to fix this. I'm a newbie, I hope you guys can understand what I describe.

Thanks,

I tried replace field drv.of_match_table in struct sdio_driver (because of no device tree in old kernel) to drv.name (because platform device detects base on name field) but the probe function still isn't called


问:
How to adjust The Gamma value with EmguCv?
i want to adjust gamma value of a Dicomfile. The Dicomfile is in grayscale as you see in the image below.
I went through the API, then i found this function
public void _GammaCorrect(double gamma);, during the execution the compiler throws this exception : Gamma correction only implemented for image of Byte as Depth.

For information my image is raw data bytes.
My code is below:

This is the image i wanna correct its gamma:

.

Thank you.


问:
Persistent storage for groups of DataFrames and other values
In the past, I've used pickle to store collections of dataframes, using something like this:

with open('datadump.pkl', 'wb') as fh:
    pickle.dump({
        'Main Database': df,
        'Detailed Data': {'a': df1, 'b': df2, 'c': df3},
        'Description': 'Something something something',
        'Summation': 42,
    })
```

However, I've got more and more frustrated with this as I often move between computers that have different versions of python and/or pandas installed and I'll find that the second computer won't read the pickled data from the first computer.

Are there any good alternatives for this kind of dataset?  Ideally, I'd like something nice and portable like json but with automatic creation of (linked somehow) parquet files for the  dataframes as that feels like it would be a nice and portable solution.

At the moment, I'm using a crude home-rolled version using zip files containing text files, parquet files and nested zip files (https://gist.github.com/abudden/16b15ade0daa35f00e3d1a6c92c05ed5), but I was wondering if there was a better (and well maintained) library that would do the same job.

Body:
In the past, I've used pickle to store collections of dataframes, using something like this:

with open('datadump.pkl', 'wb') as fh:
    pickle.dump({
        'Main Database': df,
        'Detailed Data': {'a': df1, 'b': df2, 'c': df3},
        'Description': 'Something something something',
        'Summation': 42,
    })

However, I've got more and more frustrated with this as I often move between computers that have different versions of python and/or pandas installed and I'll find that the second computer won't read the pickled data from the first computer.

Are there any good alternatives for this kind of dataset?  Ideally, I'd like something nice and portable like json but with automatic creation of (linked somehow) parquet files for the  dataframes as that feels like it would be a nice and portable solution.

At the moment, I'm using a crude home-rolled version using zip files containing text files, parquet files and nested zip files (https://gist.github.com/abudden/16b15ade0daa35f00e3d1a6c92c05ed5), but I was wondering if there was a better (and well maintained) library that would do the same job.


问:
Yandex Maps API force balloon panel at bottom of maps
Yandex has the following example for displaying a balloon as a panel along the bottom of the map, but this only works when the viewport is small enough. Modern smartphones have higher resolution and this forces the balloon to be floating in an unpredicatble location.

Is there a way to force the balloon to be a panel along the bottom even at larger screen sizes?

Yandex Example: https://yandex.com/dev/maps/jsbox/2.1/placemark_balloon


问:
LInear regression: confidence interval, bootstrapping, by group
I am trying to do all 3 things in a linear regression at once:

bootstrapping

by a grouping variable

generate confidence intervals

at this time I'm able to do 2 & 3

```<code>df %>%
    group_by(group) %>%
    group_modify(~ parameters::model_parameters(stats::lm(y~x, data = .x)))
</code>```

But I'm not able to nest boot or lm.boot into the code above (says Error: 'lm.boot' is not an exported object from 'namespace:stats')

Can anyone advise?

The goal is to have this table but bootstrapped:

enter image description here

Body:
I am trying to do all 3 things in a linear regression at once:

bootstrapping

by a grouping variable

generate confidence intervals

at this time I'm able to do 2 & 3

df %>%
    group_by(group) %>%
    group_modify(~ parameters::model_parameters(stats::lm(y~x, data = .x)))

But I'm not able to nest boot or lm.boot into the code above (says Error: 'lm.boot' is not an exported object from 'namespace:stats')

Can anyone advise?

The goal is to have this table but bootstrapped:

enter image description here


问:
Using JQuery to select NEXT radio button in a Slider
I build a single Image with radio button slider/jcarousel and what it should do is that, When the user click NEXT or PREVIOUS button, it will load up the next image and having that radiobutton selected. I got this working on the Previous Button, but not the Next, somehow, it picks up the NEXT value instead.

HTML:

```<code><li>
    <div class="image-position"><img src="images.png" width="200" height="289"/></div>
    <input type="radio" class="getradiotomove" name="radio1" />Radio 1
</li>
<li>
    <div class="image-position"><img src="images.png" width="200" height="289"/></div>
    <input type="radio" class="getradiotomove" name="radio2" />Radio 2
</li>
 <li>
    <div class="image-position"><img src="images.png" width="200" height="289"/></div>
    <input type="radio" class="getradiotomove" name="radio2" />Radio 3
</li>

<div id="buttons">
    <a href="#" id="prev">prev</a>
    <a href="#" id="next">next</a>
    <div class="clear"></div>
</div>
</code>```

JavaScript:

```<code>jQuery('#prev').click(function() {
    jQuery(".getradiotomove").attr("checked", true);
    var left_indent = parseInt(jQuery('#slides ul').css('left')) + item_width;
    jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, 200,function(){
        jQuery('#slides li:first').before(jQuery('#slides li:last'));
        jQuery('#slides ul').css({'left' : left_value});
    });
    return false;

});

jQuery('#next').click(function() {
    //radio button value
    jQuery(".getradiotomove").attr("checked", true);
    var left_indent = parseInt(jQuery('#slides ul').css('left')) - item_width;
    jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, 200, function () {
        jQuery('#slides li:last').after(jQuery('#slides li:first'));
        jQuery('#slides ul').css({'left' : left_value});
    });
    return false;

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I build a single Image with radio button slider/jcarousel and what it should do is that, When the user click NEXT or PREVIOUS button, it will load up the next image and having that radiobutton selected. I got this working on the Previous Button, but not the Next, somehow, it picks up the NEXT value instead.

HTML:

    <input type="radio" class="getradiotomove" name="radio1" />Radio 1

    <input type="radio" class="getradiotomove" name="radio2" />Radio 2

    <input type="radio" class="getradiotomove" name="radio2" />Radio 3

    prev
    next

JavaScript:

jQuery('#prev').click(function() {
    jQuery(".getradiotomove").attr("checked", true);
    var left_indent = parseInt(jQuery('#slides ul').css('left')) + item_width;
    jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, 200,function(){
        jQuery('#slides li:first').before(jQuery('#slides li:last'));
        jQuery('#slides ul').css({'left' : left_value});
    });
    return false;

});

jQuery('#next').click(function() {
    //radio button value
    jQuery(".getradiotomove").attr("checked", true);
    var left_indent = parseInt(jQuery('#slides ul').css('left')) - item_width;
    jQuery('#slides ul:not(:animated)').animate({'left' : left_indent}, 200, function () {
        jQuery('#slides li:last').after(jQuery('#slides li:first'));
        jQuery('#slides ul').css({'left' : left_value});
    });
    return false;

});


问:
Using the same order as a subquery without the results getting sorted unnecessarily
I have a large table over which I want to execute some window functions by scanning over an index and I want to stop scanning and produce the row when one of a number of conditions hold involving these aggregates (so WHERE ... LIMIT 1 is out of question, since I can't have window functions inside the WHERE).

Let me expand further on my concrete case:

Here's my events table:

```<code>=> \d events
                      Table "public.events"
   Column   |       Type        | Collation | Nullable | Default
------------+-------------------+-----------+----------+---------
 block      | character varying |           | not null |
 chainid    | bigint            |           | not null |
 height     | bigint            |           | not null |
 idx        | bigint            |           | not null |
 module     | character varying |           | not null |
 modulehash | character varying |           | not null |
 name       | character varying |           | not null |
 params     | jsonb             |           | not null |
 paramtext  | character varying |           | not null |
 qualname   | character varying |           | not null |
 requestkey | character varying |           | not null |
Indexes:
    "events_pkey" PRIMARY KEY, btree (block, idx, requestkey)
    "events_height_chainid_idx" btree (height DESC, chainid, idx)
</code>```

After much experimentation, I've arrived at a query that returns exactly the row I want and it also produces exactly the query plan that I'm envisioning:

```<code>=> EXPLAIN ANALYZE SELECT *
FROM (
  SELECT *
       , ROW_NUMBER() OVER (ORDER BY height DESC, block, requestkey, idx) as scan_num
       , count(*) FILTER (WHERE qualname ILIKE '%transfer%') OVER
           ( ORDER BY height DESC, block, requestkey, idx
             ROWS BETWEEN unbounded PRECEDING AND CURRENT ROW
           ) AS foundCnt
  FROM events
  ORDER BY height DESC, block, requestkey, idx
) as scanned_events
WHERE foundCnt = 3 OR scan_num = 100000
LIMIT 1
;
                                                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=1065.81..1400.34 rows=1 width=397) (actual time=0.095..0.096 rows=1 loops=1)
   ->  Subquery Scan on scanned_events  (cost=1065.81..165535223.46 rows=494824 width=397) (actual time=0.095..0.095 rows=1 loops=1)
         Filter: ((scanned_events.foundcnt = 3) OR (scanned_events.scan_num = 100000))
         Rows Removed by Filter: 2
         ->  WindowAgg  (cost=1065.81..164791126.56 rows=49606460 width=397) (actual time=0.089..0.094 rows=3 loops=1)
               ->  WindowAgg  (cost=1065.81..163550965.06 rows=49606460 width=389) (actual time=0.081..0.083 rows=4 loops=1)
                     ->  Incremental Sort  (cost=1065.81..162434819.71 rows=49606460 width=381) (actual time=0.076..0.076 rows=5 loops=1)
                           Sort Key: events.height DESC, events.block, events.requestkey, events.idx
                           Presorted Key: events.height
                           Full-sort Groups: 1  Sort Method: quicksort  Average Memory: 56kB  Peak Memory: 56kB
                           ->  Index Scan using events_height_chainid_idx on events  (cost=0.56..158424783.98 rows=49606460 width=381) (actual time=0.015..0.035 rows=53 loops=1)
 Planning Time: 0.112 ms
 Execution Time: 0.128 ms
(13 rows)
</code>```

Here's what this query is trying to achieve: Scan through the events table counting the number of rows whose qualname contains 'transfers' and return the row as soon as you find the 3rd match OR you end up scanning 100000 rows.

So, my high-level intention is to look for some condition (involving a moving aggregate) but I want to put an upper bound on how many rows I'm willing to fetch. But if I happen to find what I'm looking for quickly, I also don't want to go through the rest of those 100000 rows unnecessarily (similar to the query plan above, where it ends up scanning just 53 rows).

If you inspect the query plan, this query is doing exactly what I want, but it has a serious flaw: It's not guaranteed to produce the correct result, it just happens to do it since the correct result is produced by the most natural way to execute the query, but the top-level SELECT has no ORDER BY clause, so Postgres could in theory execute it in a different way and end up returning any one row that happens to return foundCnt = 3.

In order to remedy this flaw, I've tried the following:

```<code>=> EXPLAIN ANALYZE SELECT *
FROM (
  SELECT *
       , ROW_NUMBER() OVER (ORDER BY height DESC, block, requestkey, idx) as scan_num
       , count(*) FILTER (WHERE qualname ILIKE '%transfer%') OVER
           ( ORDER BY height DESC, block, requestkey, idx
             ROWS BETWEEN unbounded PRECEDING AND CURRENT ROW
           ) AS foundCnt
  FROM events
  ORDER BY height DESC, block, requestkey, idx
) as scanned_events
WHERE foundCnt = 3 OR scan_num = 100000
ORDER BY height DESC, block, requestkey, idx
LIMIT 1
;
                                                                              QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=16173553.41..16173571.35 rows=1 width=397) (actual time=86703.480..88314.937 rows=1 loops=1)
   ->  Subquery Scan on scanned_events  (cost=16173553.41..25051383.19 rows=494821 width=397) (actual time=86435.692..88047.148 rows=1 loops=1)
         Filter: ((scanned_events.foundcnt = 3) OR (scanned_events.scan_num = 100000))
         Rows Removed by Filter: 2
         ->  WindowAgg  (cost=16173553.41..24307291.63 rows=49606104 width=397) (actual time=86435.682..88047.143 rows=3 loops=1)
               ->  WindowAgg  (cost=16173553.41..23067139.03 rows=49606104 width=389) (actual time=86435.662..88047.120 rows=4 loops=1)
                     ->  Gather Merge  (cost=16173553.41..21951001.69 rows=49606104 width=381) (actual time=86435.630..88047.085 rows=5 loops=1)
                           Workers Planned: 2
                           Workers Launched: 2
                           ->  Sort  (cost=16172553.39..16224226.41 rows=20669210 width=381) (actual time=86147.622..86147.642 rows=106 loops=3)
                                 Sort Key: events.height DESC, events.block, events.requestkey, events.idx
                                 Sort Method: external merge  Disk: 6535240kB
                                 Worker 0:  Sort Method: external merge  Disk: 6503568kB
                                 Worker 1:  Sort Method: external merge  Disk: 6506736kB
                                 ->  Parallel Seq Scan on events  (cost=0.00..2852191.10 rows=20669210 width=381) (actual time=43.151..4135.334 rows=16430767 loops=3)
 Planning Time: 0.353 ms
 JIT:
   Functions: 16
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 3.412 ms, Inlining 105.447 ms, Optimization 204.392 ms, Emission 87.327 ms, Total 400.578 ms
 Execution Time: 89345.338 ms
(21 rows)
</code>```

Now it ends up scanning the entire table, even though I've just explicitly specified what it was already doing. I've tried many variations on the latter query, such as moving the subquery to a CTE or ordering the outer SELECT by scan_num, ordering both SELECTs by scan_num, only ordering the outer SELECT by height DESC, block, requestkey, idx. I honestly lost track of the variations I've already tried, but as soon as I have an ORDER BY clause on the outer SELECT, Postgres ends up scanning the entire table.

So, my question is: Is there any way to achieve what I want without relying on fragile semantics (like the query that does exactly what I want). I.e. what would be the correct way to write a Postgres query that will scan a bounded number of rows and return as soon as a condition (involving window functions) is satisfied.

Addressing the comments

@nbk suggested trying to add an index on height DESC, block, requestkey, idx, i.e. the exact order we're looking for. Even though I want to avoid adding that index because I'm happy with the performance of my first query (so the index shouldn't be necessary), I still tried it, but it didn't change the query plan of the second query at all, it doesn't use any indexes anyway. It just made the first query slighly faster as expected, since that one does use indexes.

Body:
I have a large table over which I want to execute some window functions by scanning over an index and I want to stop scanning and produce the row when one of a number of conditions hold involving these aggregates (so WHERE ... LIMIT 1 is out of question, since I can't have window functions inside the WHERE).

Let me expand further on my concrete case:

Here's my events table:

=> \d events
                      Table "public.events"
   Column   |       Type        | Collation | Nullable | Default
------------+-------------------+-----------+----------+---------
 block      | character varying |           | not null |
 chainid    | bigint            |           | not null |
 height     | bigint            |           | not null |
 idx        | bigint            |           | not null |
 module     | character varying |           | not null |
 modulehash | character varying |           | not null |
 name       | character varying |           | not null |
 params     | jsonb             |           | not null |
 paramtext  | character varying |           | not null |
 qualname   | character varying |           | not null |
 requestkey | character varying |           | not null |
Indexes:
    "events_pkey" PRIMARY KEY, btree (block, idx, requestkey)
    "events_height_chainid_idx" btree (height DESC, chainid, idx)

After much experimentation, I've arrived at a query that returns exactly the row I want and it also produces exactly the query plan that I'm envisioning:

=> EXPLAIN ANALYZE SELECT *
FROM (
  SELECT *
       , ROW_NUMBER() OVER (ORDER BY height DESC, block, requestkey, idx) as scan_num
       , count(*) FILTER (WHERE qualname ILIKE '%transfer%') OVER
           ( ORDER BY height DESC, block, requestkey, idx
             ROWS BETWEEN unbounded PRECEDING AND CURRENT ROW
           ) AS foundCnt
  FROM events
  ORDER BY height DESC, block, requestkey, idx
) as scanned_events
WHERE foundCnt = 3 OR scan_num = 100000
LIMIT 1
;
                                                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=1065.81..1400.34 rows=1 width=397) (actual time=0.095..0.096 rows=1 loops=1)
   ->  Subquery Scan on scanned_events  (cost=1065.81..165535223.46 rows=494824 width=397) (actual time=0.095..0.095 rows=1 loops=1)
         Filter: ((scanned_events.foundcnt = 3) OR (scanned_events.scan_num = 100000))
         Rows Removed by Filter: 2
         ->  WindowAgg  (cost=1065.81..164791126.56 rows=49606460 width=397) (actual time=0.089..0.094 rows=3 loops=1)
               ->  WindowAgg  (cost=1065.81..163550965.06 rows=49606460 width=389) (actual time=0.081..0.083 rows=4 loops=1)
                     ->  Incremental Sort  (cost=1065.81..162434819.71 rows=49606460 width=381) (actual time=0.076..0.076 rows=5 loops=1)
                           Sort Key: events.height DESC, events.block, events.requestkey, events.idx
                           Presorted Key: events.height
                           Full-sort Groups: 1  Sort Method: quicksort  Average Memory: 56kB  Peak Memory: 56kB
                           ->  Index Scan using events_height_chainid_idx on events  (cost=0.56..158424783.98 rows=49606460 width=381) (actual time=0.015..0.035 rows=53 loops=1)
 Planning Time: 0.112 ms
 Execution Time: 0.128 ms
(13 rows)

Here's what this query is trying to achieve: Scan through the events table counting the number of rows whose qualname contains 'transfers' and return the row as soon as you find the 3rd match OR you end up scanning 100000 rows.

So, my high-level intention is to look for some condition (involving a moving aggregate) but I want to put an upper bound on how many rows I'm willing to fetch. But if I happen to find what I'm looking for quickly, I also don't want to go through the rest of those 100000 rows unnecessarily (similar to the query plan above, where it ends up scanning just 53 rows).

If you inspect the query plan, this query is doing exactly what I want, but it has a serious flaw: It's not guaranteed to produce the correct result, it just happens to do it since the correct result is produced by the most natural way to execute the query, but the top-level SELECT has no ORDER BY clause, so Postgres could in theory execute it in a different way and end up returning any one row that happens to return foundCnt = 3.

In order to remedy this flaw, I've tried the following:

=> EXPLAIN ANALYZE SELECT *
FROM (
  SELECT *
       , ROW_NUMBER() OVER (ORDER BY height DESC, block, requestkey, idx) as scan_num
       , count(*) FILTER (WHERE qualname ILIKE '%transfer%') OVER
           ( ORDER BY height DESC, block, requestkey, idx
             ROWS BETWEEN unbounded PRECEDING AND CURRENT ROW
           ) AS foundCnt
  FROM events
  ORDER BY height DESC, block, requestkey, idx
) as scanned_events
WHERE foundCnt = 3 OR scan_num = 100000
ORDER BY height DESC, block, requestkey, idx
LIMIT 1
;
                                                                              QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=16173553.41..16173571.35 rows=1 width=397) (actual time=86703.480..88314.937 rows=1 loops=1)
   ->  Subquery Scan on scanned_events  (cost=16173553.41..25051383.19 rows=494821 width=397) (actual time=86435.692..88047.148 rows=1 loops=1)
         Filter: ((scanned_events.foundcnt = 3) OR (scanned_events.scan_num = 100000))
         Rows Removed by Filter: 2
         ->  WindowAgg  (cost=16173553.41..24307291.63 rows=49606104 width=397) (actual time=86435.682..88047.143 rows=3 loops=1)
               ->  WindowAgg  (cost=16173553.41..23067139.03 rows=49606104 width=389) (actual time=86435.662..88047.120 rows=4 loops=1)
                     ->  Gather Merge  (cost=16173553.41..21951001.69 rows=49606104 width=381) (actual time=86435.630..88047.085 rows=5 loops=1)
                           Workers Planned: 2
                           Workers Launched: 2
                           ->  Sort  (cost=16172553.39..16224226.41 rows=20669210 width=381) (actual time=86147.622..86147.642 rows=106 loops=3)
                                 Sort Key: events.height DESC, events.block, events.requestkey, events.idx
                                 Sort Method: external merge  Disk: 6535240kB
                                 Worker 0:  Sort Method: external merge  Disk: 6503568kB
                                 Worker 1:  Sort Method: external merge  Disk: 6506736kB
                                 ->  Parallel Seq Scan on events  (cost=0.00..2852191.10 rows=20669210 width=381) (actual time=43.151..4135.334 rows=16430767 loops=3)
 Planning Time: 0.353 ms
 JIT:
   Functions: 16
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 3.412 ms, Inlining 105.447 ms, Optimization 204.392 ms, Emission 87.327 ms, Total 400.578 ms
 Execution Time: 89345.338 ms
(21 rows)

Now it ends up scanning the entire table, even though I've just explicitly specified what it was already doing. I've tried many variations on the latter query, such as moving the subquery to a CTE or ordering the outer SELECT by scan_num, ordering both SELECTs by scan_num, only ordering the outer SELECT by height DESC, block, requestkey, idx. I honestly lost track of the variations I've already tried, but as soon as I have an ORDER BY clause on the outer SELECT, Postgres ends up scanning the entire table.

So, my question is: Is there any way to achieve what I want without relying on fragile semantics (like the query that does exactly what I want). I.e. what would be the correct way to write a Postgres query that will scan a bounded number of rows and return as soon as a condition (involving window functions) is satisfied.

Addressing the comments

@nbk suggested trying to add an index on height DESC, block, requestkey, idx, i.e. the exact order we're looking for. Even though I want to avoid adding that index because I'm happy with the performance of my first query (so the index shouldn't be necessary), I still tried it, but it didn't change the query plan of the second query at all, it doesn't use any indexes anyway. It just made the first query slighly faster as expected, since that one does use indexes.


问:
Why I use Feign to send localDateTime request with multipart/form-data will generate extra double quote?
Feign config

```<code>    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
</code>```

Client

```<code>@PostMapping("/send")
@Headers("Content-Type: multipart/form-data")
void send (@ModelArttibute SendRequest request);
</code>```

Request

```<code>public class SendRequest {

  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime time;

  // Setter And Getter....
}
</code>```

If I send the request out with Feign, I can see my request will have extra double quote for the time value.

```<code>-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

"2022-12-14 11:47:20"
</code>```

The request should be like as below

```<code>-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

2022-12-14 11:47:20
</code>```

How can I solve it? And what is the reason?

Body:
Feign config

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

Client

@PostMapping("/send")
@Headers("Content-Type: multipart/form-data")
void send (@ModelArttibute SendRequest request);

Request

public class SendRequest {

  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime time;

  // Setter And Getter....
}

If I send the request out with Feign, I can see my request will have extra double quote for the time value.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

"2022-12-14 11:47:20"

The request should be like as below

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

2022-12-14 11:47:20

How can I solve it? And what is the reason?


问:
neo4j connecting from C#
I'm just trying to simply connect to a neo4j database (on the desktop app) from a C# console app
My username is 'neo4j' and my password is 'root'

Most sites say do:

```<code>var client = new GraphClient(new Uri("http://localhost:7474"), "neo4j", "root");
client.Connect();
</code>```

I then check with:

```<code>bool amIConnected = client.IsConnected // false
</code>```

I was expecting to connect and then try some cypher queries in the code.

So it doesn't work (amIConnected is false, I get something about parsing or a 404 error). I've tried replacing http with neo4j or bolt but no joy.
I've also tried using var client = new Boltgraphclient...and bolt in the uri, but also no joy.
I've also tried using the Driver which is or isn't necessary, I don't know, but anyway, didn't work.
I've also tried tweaking the Uri to localhost:7474/data/db and I've also tried different ports.
Any help, much appreciated.

Title: neo4j connecting from C#

Body:
I'm just trying to simply connect to a neo4j database (on the desktop app) from a C# console app
My username is 'neo4j' and my password is 'root'

Most sites say do:

var client = new GraphClient(new Uri("http://localhost:7474"), "neo4j", "root");
client.Connect();

I then check with:

bool amIConnected = client.IsConnected // false

I was expecting to connect and then try some cypher queries in the code.

So it doesn't work (amIConnected is false, I get something about parsing or a 404 error). I've tried replacing http with neo4j or bolt but no joy.
I've also tried using var client = new Boltgraphclient...and bolt in the uri, but also no joy.
I've also tried using the Driver which is or isn't necessary, I don't know, but anyway, didn't work.
I've also tried tweaking the Uri to localhost:7474/data/db and I've also tried different ports.
Any help, much appreciated.


问:
webdriverIO ERROR webdriver: unknown error: Illegal key values seen in w3c capabilities: [args]
when executing : npx run wdio ./wdio.conf.js
i get this error :

```<code>0-0] 2022-12-14T15:29:29.651Z ERROR webdriver: unknown error: Illegal key values seen in w3c capabilities: [args]
    at Object.getErrorFromResponseBody (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/utils.js:94:12)
    at WebDriverRequest._request (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/request.js:134:31)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at Object.startWebDriverSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/utils.js:29:20)
    at Function.newSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/index.js:35:45)
    at Object.exports.remote (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriverio/build/index.js:53:22)
    at Runner._startSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:123:56)
    at Runner._initSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:103:25)
    at Runner.run (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:52:19)
[0-0] 2022-12-14T15:29:29.652Z ERROR @wdio/runner: Error: Failed to create session.
Illegal key values seen in w3c capabilities: [args]
Make sure to add vendor prefix like "goog:", "appium:", "moz:", etc to non W3C capabilities.
See more https://www.w3.org/TR/webdriver/#capabilities
</code>```

Body:
when executing : npx run wdio ./wdio.conf.js
i get this error :

0-0] 2022-12-14T15:29:29.651Z ERROR webdriver: unknown error: Illegal key values seen in w3c capabilities: [args]
    at Object.getErrorFromResponseBody (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/utils.js:94:12)
    at WebDriverRequest._request (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/request.js:134:31)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at Object.startWebDriverSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/utils.js:29:20)
    at Function.newSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriver/build/index.js:35:45)
    at Object.exports.remote (/home/dodo/Desktop/PlateRate-Tester/node_modules/webdriverio/build/index.js:53:22)
    at Runner._startSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:123:56)
    at Runner._initSession (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:103:25)
    at Runner.run (/home/dodo/Desktop/PlateRate-Tester/node_modules/@wdio/runner/build/index.js:52:19)
[0-0] 2022-12-14T15:29:29.652Z ERROR @wdio/runner: Error: Failed to create session.
Illegal key values seen in w3c capabilities: [args]
Make sure to add vendor prefix like "goog:", "appium:", "moz:", etc to non W3C capabilities.
See more https://www.w3.org/TR/webdriver/#capabilities


问:
How to run some server-side JS then start a react app
I'm wondering how to run some server side JS which then starts a react app. Or if there is a way to explicitly segment sever vs client side JS, or do I have to just add and use Express to the react app?

Essentially I want to

```<code>node somefile.js
//do some server js stuff, then

npm run start
</code>```

For example, if I wanted to check a users authentication status from a separate Next app before starting and serving a Docusaurus app.

Body:
I'm wondering how to run some server side JS which then starts a react app. Or if there is a way to explicitly segment sever vs client side JS, or do I have to just add and use Express to the react app?

Essentially I want to

node somefile.js
//do some server js stuff, then

npm run start

For example, if I wanted to check a users authentication status from a separate Next app before starting and serving a Docusaurus app.


问:
Rsocket-java stream: How to replace/update the JWT token within Flux.retryWhen(...)?
Given the rsocket client retrieving data from server using stream semantic, I would like to utilize Flux.retryWhen(retryBackoffSpec) mechanizm to reconnect in case connection is lost. Streaming endpoint on server requires valid JWT tokens to be provided.

Initial connection works fine, however I'm having problems during reconnection:

if the reconnection happens while the JWT token is still valid the process is successful,

if the reconnection happens after JWT expired, it's failing with:

last failure={RejectedSetupException (0x3): Jwt expired at 2022-12-13T10:26:39Z} error

I was not able to find a way to replace a JWT token send as metadata to streaming endpoint before retry
is performed. In my attempt, original JWT token (expired one) sent during initial request is used, which of course causes the error:

```<code>this.rSocketRequester
        .route("stream")
        .metadata(getAccessToken(), AUTHENTICATION)
        .data(streamRequest)
        .retrieveFlux(GenericRecord.class)
        .retryWhen(retryBackoffSpec); // ?? how to replace the JWT token ??
</code>```

I'm looking for a way to replace the metadata send during the retry with newly obtained JWT token (via getAccessToken() method).

Client

Connection initialization:

```<code>private static final MimeType AUTHENTICATION = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

public void connect() {
    final SocketAcceptor responder = RSocketMessageHandler.responder(rSocketStrategies, new ClientHandler());

    //@formatter:off
    retryBackoffSpec = Retry
            .fixedDelay(10, Duration.ofSeconds(10))
            .doBeforeRetry(signal -> log.warn("Connecting retry: {}", signal));

    final RSocketRequester.Builder rSocketRequesterTpl = rSocketRequesterBuilder
            .setupRoute("subscriber")
            .setupData(CLIENT_ID)
            .rsocketStrategies(builder -> {
                builder.encoders(encoders -> {
                    encoders.add(new BearerTokenAuthenticationEncoder());
                });
            })
            .rsocketConnector(connector -> {
                connector.acceptor(responder);
                connector.reconnect(retryBackoffSpec);
            });
    //@formatter:on

    this.rSocketRequester = rSocketRequesterTpl.tcp("localhost", 7000);
}
</code>```

Stream subscription:

```<code>public void stream(final MessageCallback callback, final StreamRequest streamRequest) {
    final Flux<GenericRecord> streamFlux = this.rSocketRequester
            .route("stream")
            .metadata(getAccessToken(), AUTHENTICATION)
            .data(streamRequest)
            .retrieveFlux(GenericRecord.class)
            .retryWhen(retryBackoffSpec); // ?? how to replace the JWT token ??

    streamFlux.publishOn(scheduler).subscribe(m -> callback.doOnMessage(m), t -> callback.doOnError(t));
}
</code>```

Server controller

```<code>
    @ConnectMapping("subscriber")
    void connectSubscriber(final RSocketRequester requester, @Payload final String client) {
    // removed for clarity
    }

@PreAuthorize("isAuthenticated()")
@MessageMapping({ "stream" })
Flux<StreamMessage > stream(@AuthenticationPrincipal(expression = "@authenticationConverter.convert(#this)") final JwtAuthenticationToken user,
        @Payload(required = false) StreamRequest streamRequest) {
        return Flux.interval(Duration.ofMillis(100)).map(i -> {
            final StreamMessage message = new StreamMessage();
            message.setIndex(i);
            return message;
        });
}
</code>```

Relevant dependencies:

```<code>spring-boot-starter-parent 2.7.6
rsocket-core 1.1.3
</code>```

Body:
Given the rsocket client retrieving data from server using stream semantic, I would like to utilize Flux.retryWhen(retryBackoffSpec) mechanizm to reconnect in case connection is lost. Streaming endpoint on server requires valid JWT tokens to be provided.

Initial connection works fine, however I'm having problems during reconnection:

if the reconnection happens while the JWT token is still valid the process is successful,

if the reconnection happens after JWT expired, it's failing with:

last failure={RejectedSetupException (0x3): Jwt expired at 2022-12-13T10:26:39Z} error

I was not able to find a way to replace a JWT token send as metadata to streaming endpoint before retry
is performed. In my attempt, original JWT token (expired one) sent during initial request is used, which of course causes the error:

this.rSocketRequester
        .route("stream")
        .metadata(getAccessToken(), AUTHENTICATION)
        .data(streamRequest)
        .retrieveFlux(GenericRecord.class)
        .retryWhen(retryBackoffSpec); // ?? how to replace the JWT token ??

I'm looking for a way to replace the metadata send during the retry with newly obtained JWT token (via getAccessToken() method).

Client

Connection initialization:

private static final MimeType AUTHENTICATION = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

public void connect() {
    final SocketAcceptor responder = RSocketMessageHandler.responder(rSocketStrategies, new ClientHandler());

    //@formatter:off
    retryBackoffSpec = Retry
            .fixedDelay(10, Duration.ofSeconds(10))
            .doBeforeRetry(signal -> log.warn("Connecting retry: {}", signal));

    final RSocketRequester.Builder rSocketRequesterTpl = rSocketRequesterBuilder
            .setupRoute("subscriber")
            .setupData(CLIENT_ID)
            .rsocketStrategies(builder -> {
                builder.encoders(encoders -> {
                    encoders.add(new BearerTokenAuthenticationEncoder());
                });
            })
            .rsocketConnector(connector -> {
                connector.acceptor(responder);
                connector.reconnect(retryBackoffSpec);
            });
    //@formatter:on

    this.rSocketRequester = rSocketRequesterTpl.tcp("localhost", 7000);
}

Stream subscription:

public void stream(final MessageCallback callback, final StreamRequest streamRequest) {
    final Flux<GenericRecord> streamFlux = this.rSocketRequester
            .route("stream")
            .metadata(getAccessToken(), AUTHENTICATION)
            .data(streamRequest)
            .retrieveFlux(GenericRecord.class)
            .retryWhen(retryBackoffSpec); // ?? how to replace the JWT token ??

    streamFlux.publishOn(scheduler).subscribe(m -> callback.doOnMessage(m), t -> callback.doOnError(t));
}

Server controller

    @ConnectMapping("subscriber")
    void connectSubscriber(final RSocketRequester requester, @Payload final String client) {
    // removed for clarity
    }

@PreAuthorize("isAuthenticated()")
@MessageMapping({ "stream" })
Flux<StreamMessage > stream(@AuthenticationPrincipal(expression = "@authenticationConverter.convert(#this)") final JwtAuthenticationToken user,
        @Payload(required = false) StreamRequest streamRequest) {
        return Flux.interval(Duration.ofMillis(100)).map(i -> {
            final StreamMessage message = new StreamMessage();
            message.setIndex(i);
            return message;
        });
}

Relevant dependencies:

spring-boot-starter-parent 2.7.6
rsocket-core 1.1.3


问:
Generate widgets automatically for a generic layer's fields attributes in a custom feature form in QGIS
I'm trying to create a custom attribute form in QGIS useful to modify the current layer. I have already created a custom interface in Qt-Designer with QLabels and QLineEdits. In particular, a generic QLineEdit is used to show the attribute of layer's feature and to achieve this I know that the objectName of a QLineEdit istance must have the same name as the field whose attribute I want to show. Like showed in the picture below. Until now no problem.

My goal is to create a custom attribute form usable with more than a specific layer so I need to generate automatically, from python code, the instances of QLineEdit class, each with specific objectName based on fields' name I want to show. I'm able to add custom widgets to the myDialog object, each named as the field I want to show, but QGIS seems not recognize the object and doesn't put the attributes inside the generic QLineEdit instance.

With these lines of code

```<code>...

def formOpen(dialog,layerid,featureid):

    global myDialog
    myDialog = dialog
    global nameField

    main_layer = myDialog.layer()
    main_feature = myDialog.feature()

    # get useful widgets
    title_main_layer = myDialog.findChild(QLabel, "title_main_layer")
    title_target_layer = myDialog.findChild(QLabel,"title_target_layer")
    ok_button = dialog.findChild(QPushButton,"ok_button")
    frame_main_layer = myDialog.findChild(QFrame, "frame_main_layer")
    # set the layout of this frame
    layout = QGridLayout(frame_main_layer)

    # get the list of layer's fields
    fields = [field.name() for field in main_layer.fields()]
    # add QLabels and QLineEdits inside frame
    for row, field_name in enumerate(fields):
        # label as illustrative scope
        label = QLabel(field_name)
        # lineedit to show the attribute of field
        lineedit = QLineEdit()
        lineedit.setObjectName(field_name)
        # add widgets to layout
        layout.addWidget(label,row,1)
        layout.addWidget(lineedit,row,2)

    ...
</code>```

and I get this result on QGIS

where the frame highlighted in cyan is the frame_main_layer where I added the label and lineedit. Within the bottom frame the result I want to get. Any suggestions?

Body:
I'm trying to create a custom attribute form in QGIS useful to modify the current layer. I have already created a custom interface in Qt-Designer with QLabels and QLineEdits. In particular, a generic QLineEdit is used to show the attribute of layer's feature and to achieve this I know that the objectName of a QLineEdit istance must have the same name as the field whose attribute I want to show. Like showed in the picture below. Until now no problem.

My goal is to create a custom attribute form usable with more than a specific layer so I need to generate automatically, from python code, the instances of QLineEdit class, each with specific objectName based on fields' name I want to show. I'm able to add custom widgets to the myDialog object, each named as the field I want to show, but QGIS seems not recognize the object and doesn't put the attributes inside the generic QLineEdit instance.

With these lines of code

...

def formOpen(dialog,layerid,featureid):

    global myDialog
    myDialog = dialog
    global nameField

    main_layer = myDialog.layer()
    main_feature = myDialog.feature()

    # get useful widgets
    title_main_layer = myDialog.findChild(QLabel, "title_main_layer")
    title_target_layer = myDialog.findChild(QLabel,"title_target_layer")
    ok_button = dialog.findChild(QPushButton,"ok_button")
    frame_main_layer = myDialog.findChild(QFrame, "frame_main_layer")
    # set the layout of this frame
    layout = QGridLayout(frame_main_layer)

    # get the list of layer's fields
    fields = [field.name() for field in main_layer.fields()]
    # add QLabels and QLineEdits inside frame
    for row, field_name in enumerate(fields):
        # label as illustrative scope
        label = QLabel(field_name)
        # lineedit to show the attribute of field
        lineedit = QLineEdit()
        lineedit.setObjectName(field_name)
        # add widgets to layout
        layout.addWidget(label,row,1)
        layout.addWidget(lineedit,row,2)

    ...

and I get this result on QGIS

where the frame highlighted in cyan is the frame_main_layer where I added the label and lineedit. Within the bottom frame the result I want to get. Any suggestions?


问:
In react, how can i call a useImperativeHandle function and normal function on a button onClick, at the same time
In one component, I have

```<code>import { useState, useImperativeHandle, forwardRef } from 'react'

export const ChildComponent = forwardRef((props: {onClick}, ref) => {
  const defaultFirst = 'some value'

  const [dateOne, setDateOne] = useState(defaultFirst);

useImperativeHandle(ref, () => ({
    resetFilter() {
      setDateOne(defaultFirst)
  }
}))

return (
  <div> some stuff </div>
 )
})
</code>```

On my other component I am trying to call the resetFilter function with another function on the onClick prop for a button

```<code>import { useCallback } from 'react'

export const ParentComponent = () => {
  const buttonRef = useRef(null)

  const handleRefresh = useCallback (
  (e) => {
      refetch({
        input: {
          start: e.start,
          end: e.end
        }
      })
    },
    [refetch]
  );
}
return (
  <div>
    <button
      onClick={handleRefresh}
    </button>
  </div>
)

}
</code>```

What im trying to accomplish is onClick, call handleRefresh and buttonRef.current.resetFilter() in one click.

currently, handleRefresh works as shown above

resetFilter() will work if i set it up like so:

```<code>onClick={() => { buttonRef.current.resetFilter() }}
</code>```

I need to call them both onClick

Body:
In one component, I have

import { useState, useImperativeHandle, forwardRef } from 'react'

export const ChildComponent = forwardRef((props: {onClick}, ref) => {
  const defaultFirst = 'some value'

  const [dateOne, setDateOne] = useState(defaultFirst);

useImperativeHandle(ref, () => ({
    resetFilter() {
      setDateOne(defaultFirst)
  }
}))

return (

 some stuff

 )
})

On my other component I am trying to call the resetFilter function with another function on the onClick prop for a button

import { useCallback } from 'react'

export const ParentComponent = () => {
  const buttonRef = useRef(null)

  const handleRefresh = useCallback (
  (e) => {
      refetch({
        input: {
          start: e.start,
          end: e.end
        }
      })
    },
    [refetch]
  );
}
return (

    <button
      onClick={handleRefresh}
    </button>

)

}

What im trying to accomplish is onClick, call handleRefresh and buttonRef.current.resetFilter() in one click.

currently, handleRefresh works as shown above

resetFilter() will work if i set it up like so:

onClick={() => { buttonRef.current.resetFilter() }}

I need to call them both onClick


问:
How to achieve slide effect in page transformer in viewpager after notifyDataSetChanged?
I have a view pager with a list of Fragments as views, the transaction between view is the normal slide to left or right. I move to next or previous pages by buttons.

At some point I need to update the fragment list by adding another or removing a fragment, and then I do a pagerAdapter.notifyDataSetChanged(), but the transaction after that is bold, there is no transaction.

Reading some google cases I saw that I can add a setPageTransformer after the notifyDataSetChanged and it works well, but the effect I get is a fade one not a normal slide and I don't know how to get the slide effect, so any help would be appreciated.

This is what I use now:

```<code>pagerAdapter.notifyDataSetChanged()
viewPager.setPageTransformer(false) { page, position ->
    page.alpha = 0f
    page.visibility = View.VISIBLE

    page.animate().alpha(1).duration = page.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
}
</code>```

Body:
I have a view pager with a list of Fragments as views, the transaction between view is the normal slide to left or right. I move to next or previous pages by buttons.

At some point I need to update the fragment list by adding another or removing a fragment, and then I do a pagerAdapter.notifyDataSetChanged(), but the transaction after that is bold, there is no transaction.

Reading some google cases I saw that I can add a setPageTransformer after the notifyDataSetChanged and it works well, but the effect I get is a fade one not a normal slide and I don't know how to get the slide effect, so any help would be appreciated.

This is what I use now:

pagerAdapter.notifyDataSetChanged()
viewPager.setPageTransformer(false) { page, position ->
    page.alpha = 0f
    page.visibility = View.VISIBLE

    page.animate().alpha(1).duration = page.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
}


问:
SDL2_TTF: During startup program exited with code 0xc0000135
I'm trying to use the SDL2_TTF library to render text in my application. My code compiles with no warnings or errors using GCC, but running through GDB produces this output:

[Thread 14488.0x369c exited with code 3221225781]
[Thread 14488.0x4f24 exited with code 3221225781]
[Thread 14488.0x2ab8 exited with code 3221225781]
During startup program exited with code 0xc0000135.
```
<p>Here is my makefile:</p>
```OBJS = $(wildcard *.cpp)

CXX = g++

INCLUDE_PATHS = -ID:\VSCode\SDLDevTools\include\SDL2

#LIBRARY_PATHS specifies the additional library paths we'll need
LIBRARY_PATHS = -LD:\VSCode\SDLDevTools\lib

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
# -Wl,-subsystem,windows gets rid of the console window
COMPILER_FLAGS = -w -g #-Wl,-subsystem,windows <- remove comment in final ver

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf

#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = main

#This is the target that compiles our executable
all : $(OBJS)
    $(CXX) $(OBJS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)
```

I've verified I didn't accidentally install the 32-bit version of SDL2_ttf (I reinstalled SDL2 and SDL2_ttf and tried to recompile, same issue). Not sure how I should proceed here - everything I've found points to the program not finding a DLL properly, but I looked and every DLL I need is in the /bin folder of my library path for SDL.

If it helps, I'm using VSCode as my editor and compiling everything using MinGW/GCC on the command line.

Body:
I'm trying to use the SDL2_TTF library to render text in my application. My code compiles with no warnings or errors using GCC, but running through GDB produces this output:

[Thread 14488.0x369c exited with code 3221225781]
[Thread 14488.0x4f24 exited with code 3221225781]
[Thread 14488.0x2ab8 exited with code 3221225781]
During startup program exited with code 0xc0000135.

Here is my makefile:

OBJS = $(wildcard *.cpp)

CXX = g++

INCLUDE_PATHS = -ID:\VSCode\SDLDevTools\include\SDL2

#LIBRARY_PATHS specifies the additional library paths we'll need
LIBRARY_PATHS = -LD:\VSCode\SDLDevTools\lib

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
# -Wl,-subsystem,windows gets rid of the console window
COMPILER_FLAGS = -w -g #-Wl,-subsystem,windows <- remove comment in final ver

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf

#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = main

#This is the target that compiles our executable
all : $(OBJS)
    $(CXX) $(OBJS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)

I've verified I didn't accidentally install the 32-bit version of SDL2_ttf (I reinstalled SDL2 and SDL2_ttf and tried to recompile, same issue). Not sure how I should proceed here - everything I've found points to the program not finding a DLL properly, but I looked and every DLL I need is in the /bin folder of my library path for SDL.

If it helps, I'm using VSCode as my editor and compiling everything using MinGW/GCC on the command line.


问:
How can I publish mqtt messages on iot core using AWS credential(sigv4) using python?
I'm interested if it's possible to use python paho library to publish mqtt messages on AWS iot core and how it's done. Until now I just managed to send mqtt messages using certificates.
The credentials are sigv4(access key id, secret key, session token ) obtained through a Congnito Identity pool.

I just found information on connecting to iot core using certificates and I have already some scripts which use certificates. What I'm interested is how do I handle these credentials in paho.


问:
place a home icon on top of interactive content?
I want to add an image (which serves as a home icon that when clicked takes you to the index page) on top of everything else in the top left hand corner. I have tried simply using:

```<code><a href="Desktop.html">
<img class="homeicon"

  <img src="img/home-icon.png">
 </a>
</div>

</code>```

then styling it in css using position: absolute but that doesn't work. The image just doesn't appear. I have looked online for various solutions but none have worked yet.

My code is
HTML:

```<code><!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Our Main Targets</title>
        <link href="https://fonts.googleapis.com/css?family=Pathway+Gothic+One|Source+Sans+Pro:400" rel="stylesheet">
<link rel="stylesheet" href="./stylemt1.css">

</head>
<body>

<section id="timeline">

  <div class="tl-item">

    <div class="tl-bg" style="background-image: url(img/Hannah.png)"></div>

    <div class="tl-year">
       <a href="hannatimeline.html"><p class="f2 heading--sanSerif">Hanna</p></a>
    </div>

    <div class="tl-content">
      <h1>Marin</h1>
      <p>text goes here .</p>
    </div>

  </div>

  <div class="tl-item">

    <div class="tl-bg" style="background-image: url(img/emily.png)"></div>

    <div class="tl-year">
       <a href="emilytimeline.html"><p class="f2 heading--sanSerif">Emily</p></a>
    </div>

    <div class="tl-content">
      <h1 class="f3 text--accent ttu">Fields</h1>
      <p>Suspendisse potenti. Sed sollicitudin eros lorem, eget accumsan risus dictum id. Maecenas dignissim ipsum vel mi rutrum egestas. Donec mauris nibh, facilisis ut hendrerit vel, fringilla sed felis. Morbi sed nisl et arcu.</p>
    </div>

  </div>

  <div class="tl-item">

    <div class="tl-bg" style="background-image: url(img/alison.png)"></div>

    <div class="tl-year">
      <a href="alisontimeline.html"> <p class="f2 heading--sanSerif">Alison</p></a>
    </div>

    <div class="tl-content">
      <h1 class="f3 text--accent ttu">DiLaurentis</h1>
      <p>text goes here .</p>
    </div>

  </div>

  <div class="tl-item">

    <div class="tl-bg" style="background-image: url(img/aria.png)"></div>

    <div class="tl-year">
     <a href="ariatimeline.html"> <p class="f2 heading--sanSerif">Aria</p> </a>
    </div>

    <div class="tl-content">
      <h1 class="f3 text--accent ttu">Montgomery</h1>
      <p>text goes here.</p>
    </div>

  </div>

  <div class="tl-item">

    <div class="tl-bg" style="background-image: url(img/spencer.png)"></div>

    <div class="tl-year">
       <a href="spencertimeline.html"><p class="f2 heading--sanSerif">Spencer</p></a>
    </div>

    <div class="tl-content">
      <h1 class="f3 text--accent ttu">Hastings</h1>
      <p>text goes here.</p>
    </div>

  </div>
</section>

</body>
</html>

</code>```

CSS:

```<code>body {
  font-family: "Source Sans Pro", Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 1.75;
}

#timeline {
  display: flex;
  background-color: #031625;
}
#timeline:hover .tl-item {
  width: 23.3333%;
}

.tl-item {
  transform: translate3d(0, 0, 0);
  position: relative;
  width: 25%;
  height: 100vh;
  min-height: 600px;
  color: #fff;
  overflow: hidden;
  transition: width 0.5s ease;
}
.tl-item:before, .tl-item:after {
  transform: translate3d(0, 0, 0);
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.tl-item:after {
  background: rgba(3, 22, 37, 0.85);
  opacity: 1;
  transition: opacity 0.5s ease;
}
.tl-item:before {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, black 75%);
  z-index: 1;
  opacity: 0;
  transform: translate3d(0, 0, 0) translateY(50%);
  transition: opacity 0.5s ease, transform 0.5s ease;
}
.tl-item:hover {
  width: 30% !important;
}
.tl-item:hover:after {
  opacity: 0;
}
.tl-item:hover:before {
  opacity: 1;
  transform: translate3d(0, 0, 0) translateY(0);
  transition: opacity 1s ease, transform 1s ease 0.25s;
}
.tl-item:hover .tl-content {
  opacity: 1;
  transform: translateY(0);
  transition: all 0.75s ease 0.5s;
}
.tl-item:hover .tl-bg {
  filter: grayscale(0);
}

.tl-content {
  transform: translate3d(0, 0, 0) translateY(25px);
  position: relative;
  z-index: 1;
  text-align: center;
  margin: 0 1.618em;
  top: 55%;
  opacity: 0;
}
.tl-content h1 {
  font-family: "Pathway Gothic One", Helvetica Neue, Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  color: #1779cf;
  font-size: 1.44rem;
  font-weight: normal;
}

.tl-year {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  z-index: 1;
  border-top: 1px solid #fff;
  border-bottom: 1px solid #fff;
}
.tl-year p {
  font-family: "Pathway Gothic One", Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 1.728rem;
  line-height: 0;
}

.tl-bg {
  transform: translate3d(0, 0, 0);
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-size: cover;
  background-position: center center;
  transition: filter 0.5s ease;
  filter: grayscale(100%);
}

a:link {
  color: white;
  background-color: transparent;
  text-decoration: none;
}

a:visited {
  color: pink;
  background-color: transparent;
  text-decoration: none;
}

a:hover {
  color: red;
  background-color: transparent;
  text-decoration: underline;
}

a:active {
  color: yellow;
  background-color: transparent;
  text-decoration: underline;
}

</code>```

How would I do this? Thanks

Body:
I want to add an image (which serves as a home icon that when clicked takes you to the index page) on top of everything else in the top left hand corner. I have tried simply using:

<img class="homeicon"

then styling it in css using position: absolute but that doesn't work. The image just doesn't appear. I have looked online for various solutions but none have worked yet.

My code is
HTML:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Our Main Targets</title>
        <link href="https://fonts.googleapis.com/css?family=Pathway+Gothic+One|Source+Sans+Pro:400" rel="stylesheet">
<link rel="stylesheet" href="./stylemt1.css">

Hanna

Marin

text goes here .

Emily

Fields

Suspendisse potenti. Sed sollicitudin eros lorem, eget accumsan risus dictum id. Maecenas dignissim ipsum vel mi rutrum egestas. Donec mauris nibh, facilisis ut hendrerit vel, fringilla sed felis. Morbi sed nisl et arcu.

Alison

DiLaurentis

text goes here .

Aria

Montgomery

text goes here.

Spencer

Hastings

text goes here.

CSS:

body {
  font-family: "Source Sans Pro", Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 1.75;
}

#timeline {
  display: flex;
  background-color: #031625;
}
#timeline:hover .tl-item {
  width: 23.3333%;
}

.tl-item {
  transform: translate3d(0, 0, 0);
  position: relative;
  width: 25%;
  height: 100vh;
  min-height: 600px;
  color: #fff;
  overflow: hidden;
  transition: width 0.5s ease;
}
.tl-item:before, .tl-item:after {
  transform: translate3d(0, 0, 0);
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.tl-item:after {
  background: rgba(3, 22, 37, 0.85);
  opacity: 1;
  transition: opacity 0.5s ease;
}
.tl-item:before {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, black 75%);
  z-index: 1;
  opacity: 0;
  transform: translate3d(0, 0, 0) translateY(50%);
  transition: opacity 0.5s ease, transform 0.5s ease;
}
.tl-item:hover {
  width: 30% !important;
}
.tl-item:hover:after {
  opacity: 0;
}
.tl-item:hover:before {
  opacity: 1;
  transform: translate3d(0, 0, 0) translateY(0);
  transition: opacity 1s ease, transform 1s ease 0.25s;
}
.tl-item:hover .tl-content {
  opacity: 1;
  transform: translateY(0);
  transition: all 0.75s ease 0.5s;
}
.tl-item:hover .tl-bg {
  filter: grayscale(0);
}

.tl-content {
  transform: translate3d(0, 0, 0) translateY(25px);
  position: relative;
  z-index: 1;
  text-align: center;
  margin: 0 1.618em;
  top: 55%;
  opacity: 0;
}
.tl-content h1 {
  font-family: "Pathway Gothic One", Helvetica Neue, Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  color: #1779cf;
  font-size: 1.44rem;
  font-weight: normal;
}

.tl-year {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  z-index: 1;
  border-top: 1px solid #fff;
  border-bottom: 1px solid #fff;
}
.tl-year p {
  font-family: "Pathway Gothic One", Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 1.728rem;
  line-height: 0;
}

.tl-bg {
  transform: translate3d(0, 0, 0);
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-size: cover;
  background-position: center center;
  transition: filter 0.5s ease;
  filter: grayscale(100%);
}

a:link {
  color: white;
  background-color: transparent;
  text-decoration: none;
}

a:visited {
  color: pink;
  background-color: transparent;
  text-decoration: none;
}

a:hover {
  color: red;
  background-color: transparent;
  text-decoration: underline;
}

a:active {
  color: yellow;
  background-color: transparent;
  text-decoration: underline;
}

How would I do this? Thanks


问:
How to fix iOS Facebook login error with message: "Login error there is an error in logging you into this application"?
iOS Facebook login error

I spent a lot of time searching the internet for a solution. I found many solutions for android but not for iOS. I use react-native-fbsdk for log in Facebook. My react-native version is 0.66.5.

I tried change react-native version, re-integrated Facebook login on iOS