问:
how Get Multiple value in array with same id laravel & Angular
Here I am trying to get question. At first understand all system we have quiz making system in that we make quizzes but in there a problem if we put a question in any quiz then we creating other quiz the how can we know this particular question is putted in other quizzes or not if yes then which-which. So, here i am trying to get all quizzes title of particular question id.
here is controller code

```<code>$questions = DB::table('questionbank')
                ->leftJoin('questionbank_quizzes', function($join)
             {
                 $join->on('questionbank_quizzes.questionbank_id','=','questionbank.id');
             })
             ->leftJoin('quizzes', function($join)
             {
                 $join->on('quizzes.id','=','questionbank_quizzes.quize_id');

             })
            //  ->groupBy('questionbank.id')
                ->where('questionbank.subject_id', '=', $request->subject_id)
                ->select('questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status','quizzes.title')
                ->get(['questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status', 'quizzes.title']);

      return json_encode(array('topics'=>$topics, 'questions'=>$questions, 'subject'=>$subject));
</code>```

And This is angular code

```<code>$scope.subjectChanged = function(selected_number) {

        if(selected_number=='')
            selected_number = $scope.subject_id;
        subject_id = selected_number;
        if(subject_id === undefined)
            return;
        route = '{{URL_QUIZ_GET_QUESTIONS}}';
        data= {  _method: 'post',
                '_token':httpPreConfig.getToken(),
                 'subject_id': subject_id
               };

          httpPreConfig.webServiceCallPost(route, data).then(function(result){

            result = result.data;
            $scope.subjectQuestions = [];
            $scope.subject          = result.subject;
            $scope.subjectQuestions = result.questions;

            $scope.contentAvailable = true;

           $scope.removeDuplicates();

            });
        }

        $scope.removeDuplicates = function(){

            if($scope.savedQuestions.length<=0 || $scope.subjectQuestions.length<=0)
                return;

             angular.forEach($scope.savedQuestions,function(value,key){
                    if(value.subject_id != $scope.subjectQuestions[0].subject_id)
                        return;

                    res = httpPreConfig.findIndexInData($scope.subjectQuestions, 'id', value.question_id);
                    if(res >= 0)
                    {
                         $scope.subjectQuestions.splice(res, 1);
                    }

            });
        }
</code>```

This is blade view

```<code>    <div ng-if="subjectQuestions!=''" class="vertical-scroll" >

                                <h4 class="text-success">Questions @{{ subjectQuestions.length }} </h4>
                                <table  class="table table-hover">
                                    <th >{{getPhrase('subject')}}</th>

                                    <th>{{getPhrase('question')}}</th>

                                    <th>{{getPhrase('Placed In')}}</th>

                                    <th>{{getPhrase('type')}}</th>

                                    <th>{{getPhrase('marks')}}</th>

                                    <th>{{getPhrase('action')}}</th>
                                    <tr ng-repeat="question in subjectQuestions | filter: { difficulty_level:difficulty, question_type:question_type, show_in_front_end:show_in_front_end , topic_id:topic, sub_topic_id:sub_topic } | filter: question_model track by $index ">

                                        <td>@{{subject.subject_title}}</td>
                                        <td title="@{{subjectQuestions[$index].question}}" ng-bind-html="trustAsHtml(question.question)">
                                        </td>
                                        <td>  @{{question.title}} </td>
                                        <td>@{{question.question_type | uppercase}}</td>
                                        <td>@{{question.marks}}</td>
                                        <td><a ng-click="addQuestion(question, subject);" class="btn btn-primary" >{{getPhrase('add')}}</a>
                                          </td>
                                    </tr>
                                </table>
                                </div>
                                </div>
                            </div>
</code>```

Its result is like this

```<code>questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
1: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
3: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
4: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
5: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
6: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
7: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]
</code>```

In result you can see with same id title is different but i am stuck here how can i do that. Please help us in this problem.
I want result like this..

```<code>questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1" subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
1: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
3: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]
</code>```

Body:
Here I am trying to get question. At first understand all system we have quiz making system in that we make quizzes but in there a problem if we put a question in any quiz then we creating other quiz the how can we know this particular question is putted in other quizzes or not if yes then which-which. So, here i am trying to get all quizzes title of particular question id.
here is controller code

$questions = DB::table('questionbank')
                ->leftJoin('questionbank_quizzes', function($join)
             {
                 $join->on('questionbank_quizzes.questionbank_id','=','questionbank.id');
             })
             ->leftJoin('quizzes', function($join)
             {
                 $join->on('quizzes.id','=','questionbank_quizzes.quize_id');

             })
            //  ->groupBy('questionbank.id')
                ->where('questionbank.subject_id', '=', $request->subject_id)
                ->select('questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status','quizzes.title')
                ->get(['questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status', 'quizzes.title']);

      return json_encode(array('topics'=>$topics, 'questions'=>$questions, 'subject'=>$subject));

And This is angular code

$scope.subjectChanged = function(selected_number) {

        if(selected_number=='')
            selected_number = $scope.subject_id;
        subject_id = selected_number;
        if(subject_id === undefined)
            return;
        route = '{{URL_QUIZ_GET_QUESTIONS}}';
        data= {  _method: 'post',
                '_token':httpPreConfig.getToken(),
                 'subject_id': subject_id
               };

          httpPreConfig.webServiceCallPost(route, data).then(function(result){

            result = result.data;
            $scope.subjectQuestions = [];
            $scope.subject          = result.subject;
            $scope.subjectQuestions = result.questions;

            $scope.contentAvailable = true;

           $scope.removeDuplicates();

            });
        }

        $scope.removeDuplicates = function(){

            if($scope.savedQuestions.length<=0 || $scope.subjectQuestions.length<=0)
                return;

             angular.forEach($scope.savedQuestions,function(value,key){
                    if(value.subject_id != $scope.subjectQuestions[0].subject_id)
                        return;

                    res = httpPreConfig.findIndexInData($scope.subjectQuestions, 'id', value.question_id);
                    if(res >= 0)
                    {
                         $scope.subjectQuestions.splice(res, 1);
                    }

            });
        }

This is blade view

Questions @{{ subjectQuestions.length }}

                                    {{getPhrase('subject')}}

                                    {{getPhrase('question')}}

                                    {{getPhrase('Placed In')}}

                                    {{getPhrase('type')}}

                                    {{getPhrase('marks')}}

                                    {{getPhrase('action')}}

                                        @{{subject.subject_title}}

                                          @{{question.title}}
                                        @{{question.question_type | uppercase}}
                                        @{{question.marks}}
                                        {{getPhrase('add')}}

Its result is like this

questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
1: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
3: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
4: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
5: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
6: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
7: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]

In result you can see with same id title is different but i am stuck here how can i do that. Please help us in this problem.
I want result like this..

questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1" subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26(
 or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
1: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(
 or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(
 or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
3: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(
 or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]


来源: stackexchange

问:
Is it normal if i have more than 200 objectboxes declared in a project?
Im having a project where the requirement is to manage 200++ models persisted in objectbox. I've proceed with the plan, but i find it uncertain whenever i run "flutter packages pub run build-runner build" and it tooks around 15 - 20 minutes to finish. Is this normal??

I've created 200++ models with complex attributes and declared as Box for each of them, I'm not sure is this too overwhelm?

I expect the "flutter packages pub run build-runner build" process takes less than 3 minutes to complete.

ContentLicense: CC BY-SA 4.0


问:
Firebase dynamic link short url is not working while redirecting one domain to another domain in firebase hosting (Long link is working good)
I had redirect my new domain to old domain in firebase hosting, Everything fine in this except dynamic short url is not working, it shows dynamic url is not found, Long url is working good, Please help me on this</p>


问:
Execution of Python com object fails due incorrect username and password
I'm trying to automate something using pywin32. When I ran the script it is working fine but as soon when i trigger it through Jenkins the script will complain about the following:

```<code>pywintypes.com_error: (-2147467238, 'The server process could not be started because the configured identity is incorrect. Check the username and password.', None, None)
</code>```

I already set the user rights and so on but for some kind of reason it complains about this and I have no idea where to look as I use the same user on Jenkins as when I log in manually. Also the fact that If i'm logged in the pc manually and I start the build in Jenkins then for some kind of reason it works. To summarize:

When I'm logged in with rmd with user x and I trigger the build the Python script will just run

When I'm not logged in with rmd and user x, and I trigger the build the Python script will throw the exception.

Why does this behaviour happen?

Body:
I'm trying to automate something using pywin32. When I ran the script it is working fine but as soon when i trigger it through Jenkins the script will complain about the following:

pywintypes.com_error: (-2147467238, 'The server process could not be started because the configured identity is incorrect. Check the username and password.', None, None)

I already set the user rights and so on but for some kind of reason it complains about this and I have no idea where to look as I use the same user on Jenkins as when I log in manually. Also the fact that If i'm logged in the pc manually and I start the build in Jenkins then for some kind of reason it works. To summarize:

When I'm logged in with rmd with user x and I trigger the build the Python script will just run

When I'm not logged in with rmd and user x, and I trigger the build the Python script will throw the exception.

Why does this behaviour happen?


问:
GitHub Action throws a "a sequence was not expected"
I am trying to create a MegaLinter workflow.

According to the documentation, I should be able to use the following:

ENABLE_LINTERS:
- TERRAFORM_KICS
- TERRAFORM_TERRAFORM_FMT
- TERRAFORM_TERRAGRUNT
- TERRAFORM_TERRASCAN
- TERRAFORM_TFLINT
```

Some google searching lead to the possible fix of removing the '-' but this just causes MegaLinter to not include any linters.

I am expecting the workflow file to load and run the Linters that have been enabled.

Body:
I am trying to create a MegaLinter workflow.

According to the documentation, I should be able to use the following:

ENABLE_LINTERS:
- TERRAFORM_KICS
- TERRAFORM_TERRAFORM_FMT
- TERRAFORM_TERRAGRUNT
- TERRAFORM_TERRASCAN
- TERRAFORM_TFLINT

Some google searching lead to the possible fix of removing the '-' but this just causes MegaLinter to not include any linters.

I am expecting the workflow file to load and run the Linters that have been enabled.


问:
Python: Popen run py script in new cmd/terminal window and get output realtime?
I want to run .py script via python, and i need script run in a new cmd/terminal window, i try some code, it can do it, but i can't get cmd/terminal output, it always terminate immediately and running in background:

run_script.py:

```<code>cli = f'python test.py'
cmd = f"start cmd /c \"{cli}\""
# or:
# cmd = f'wt -w -0 nt --title tab1 {cli}'
p = Popen(cmd, shell=True, stdout=PIPE, encoding='utf-8')

# p.poll() == 0 here, but `test.py` script running in cmd/terminal window backgroud.

while True:
    output = p.stdout.readline().strip()
    print(output) # no output

    if output == '42':
        do_stuff()
</code>```

If i have a test.py:

```<code>for i in range(100):
    print(str(i))
    time.sleep(1)
</code>```

I want run test.py in new window via Popen, and get test.py live output in run_script.py.

Body:
I want to run .py script via python, and i need script run in a new cmd/terminal window, i try some code, it can do it, but i can't get cmd/terminal output, it always terminate immediately and running in background:

run_script.py:

cli = f'python test.py'
cmd = f"start cmd /c \"{cli}\""
# or:
# cmd = f'wt -w -0 nt --title tab1 {cli}'
p = Popen(cmd, shell=True, stdout=PIPE, encoding='utf-8')

# p.poll() == 0 here, but `test.py` script running in cmd/terminal window backgroud.

while True:
    output = p.stdout.readline().strip()
    print(output) # no output

    if output == '42':
        do_stuff()

If i have a test.py:

for i in range(100):
    print(str(i))
    time.sleep(1)

I want run test.py in new window via Popen, and get test.py live output in run_script.py.


问:
How can I display 'a' by adding a clear column if the same advertising group recorded event time 3 times within 1 minute?

This doesn't catch all the same advertising ID causing three events in a minute.

```<code>df = pd.read_csv('AOS.csv', parse_dates=['Event Time'])

df_clean = df.loc[:,['Attributed Touch Type','Attributed Touch Time','Install Time','Event Time','Event Name','Partner','Media Source','Channel','Keywords',
                     'Campaign','Adset','Ad','Ad Type','Region','Country Code','Carrier','Language','AppsFlyer ID','Android ID','Advertising ID',
                     'IDFA','IDFV','Device Category','Platform','OS Version','App Version','SDK Version','Is Retargeting','Retargeting Conversion Type',
                     'Is Primary Attribution','Attribution Lookback','Reengagement Window','Match Type','User Agent','Conversion Type','Campaign Type',
                     'Device Model','Keyword ID']]

df_clean['Event Time'] = pd.to_datetime(df_clean['Event Time'])

df_clean['flag'] = np.where( (df_clean['Retargeting Conversion Type'] == 're-engagement') & (df_clean['Attributed Touch Type'] != 're-attribution'), 'a', '')

df_clean['count'] = df_clean.groupby(['Advertising ID', pd.Grouper(key='Event Time', freq='1Min')])['flag'].transform('count')

df_clean['flag'] = np.where(df_clean['count'] >= 3, 'a', '')
</code>```

Body:
This doesn't catch all the same advertising ID causing three events in a minute.

df = pd.read_csv('AOS.csv', parse_dates=['Event Time'])

df_clean = df.loc[:,['Attributed Touch Type','Attributed Touch Time','Install Time','Event Time','Event Name','Partner','Media Source','Channel','Keywords',
                     'Campaign','Adset','Ad','Ad Type','Region','Country Code','Carrier','Language','AppsFlyer ID','Android ID','Advertising ID',
                     'IDFA','IDFV','Device Category','Platform','OS Version','App Version','SDK Version','Is Retargeting','Retargeting Conversion Type',
                     'Is Primary Attribution','Attribution Lookback','Reengagement Window','Match Type','User Agent','Conversion Type','Campaign Type',
                     'Device Model','Keyword ID']]

df_clean['Event Time'] = pd.to_datetime(df_clean['Event Time'])

df_clean['flag'] = np.where( (df_clean['Retargeting Conversion Type'] == 're-engagement') & (df_clean['Attributed Touch Type'] != 're-attribution'), 'a', '')

df_clean['count'] = df_clean.groupby(['Advertising ID', pd.Grouper(key='Event Time', freq='1Min')])['flag'].transform('count')

df_clean['flag'] = np.where(df_clean['count'] >= 3, 'a', '')


问:
How can I easily wrap the StackExchange.Redis `IDatabase`?
I want to override methods for specific commands on the IDatabase to modify the results.

FT.SEARCH should never return duplicate keys but it can when there is some sort of corruption.

I am using another library that calls FT.SEARCH in IDatabase so this part can only be done by changing IDatabase.

I can autogenerate a wrapper and then use this, but it would need to be maintained and updated every time the IDatabase interface changes. It would be unfortunate to need to update the wrapper class even when I didn't need to override the method that changed in IDatabase. Is there another option that would have similar performance that this wrapper does?

Assume I had a class called DatabaseWrapper all methods were virtual and that was in another package example code would look like:

    public sealed class MyDatabaseOverrides: DatabaseWrapper
    {
        private const string RediSearchSearchCommandName = "FT.SEARCH";

        public MyDatabaseOverrides(IDatabase wrapped) : base(wrapped)
        {
        }

        public override Task<RedisResult> ExecuteAsync(string command, params object[] args)
        {
            var resultTask = base.ExecuteAsync(command, args);
            if (string.Equals(RediSearchSearchCommandName, command, StringComparison.OrdinalIgnoreCase))
            {
                return SkipAndLogDuplicateKeys(resultTask);
            }

            return resultTask;
        }

        private async Task<RedisResult> SkipAndLogDuplicateKeys(Task<RedisResult> resultTask)
        {
// implementation omitted for brevity
           return await resultTask;
        }
    }

```


问:
C++: how gcc linker understands where to look for a functions definitions
I would like if possible know how I can resolve this issue:

I have 3 files, all 3 are in the same folder: function.h, function.cpp and main.cpp
The compiler is gcc.
the error message is:

```<code>undefined reference to `add(int, int)'
collect2.exe: error: ld returned 1 exit status
</code>```

function.h

```<code>int add(int a, int b);
</code>```

function.cpp

```<code>int add(int a, int b)
{
    return a + b;
}
</code>```

main.cpp

```<code>#include<iostream>
#include "functions.h"
using namespace std;

int main()
{
    int n1 = 0; int n2 = 0; int sum = 0;
    cout << "Please insert two numbers:" << endl;
    cin >> n1; cin >> n2 ;
    sum = add(n1, n2) ;
    cout << "The sum is:" << sum << endl ;
}
</code>```

Command line

```<code>g++ main.cpp
</code>```

if I include function.cpp to header of main.cpp the error message disapears

Should I add some extra config to let gcc linker know where to look for functions definitions?

thanks

Body:
I would like if possible know how I can resolve this issue:

I have 3 files, all 3 are in the same folder: function.h, function.cpp and main.cpp
The compiler is gcc.
the error message is:

undefined reference to `add(int, int)'
collect2.exe: error: ld returned 1 exit status

function.h

int add(int a, int b);

function.cpp

int add(int a, int b)
{
    return a + b;
}

main.cpp

#include<iostream>
#include "functions.h"
using namespace std;

int main()
{
    int n1 = 0; int n2 = 0; int sum = 0;
    cout << "Please insert two numbers:" << endl;
    cin >> n1; cin >> n2 ;
    sum = add(n1, n2) ;
    cout << "The sum is:" << sum << endl ;
}

Command line

g++ main.cpp

if I include function.cpp to header of main.cpp the error message disapears

Should I add some extra config to let gcc linker know where to look for functions definitions?

thanks


问:
CSS Browser Compability Border Bug using TailwindCSS
I'm having a little browser compatibility problem right now and couldn't find a working solution. When copying an HTML element, the content is rendered differently depending on the browser. In Firefox, everything works fine. However, in Chrome and Brave, a gray border is put around all content.

My goal is to achieve a working method to copy the content into the clipboard and pasting at in Outlook and other Mail programs in the right style.

```

I use TailwindCSS and have already tried border-0, border-none and even border-transparent. The gray box remains when the clipboard is inserted. Through my DevTools, I was able to figure out that it is actually due to the "border-style: solid;" value. By using border-none over the content I should be able to override a global value though, right? (Already tried !important, doesn't change anything).

Body:
I'm having a little browser compatibility problem right now and couldn't find a working solution. When copying an HTML element, the content is rendered differently depending on the browser. In Firefox, everything works fine. However, in Chrome and Brave, a gray border is put around all content.

My goal is to achieve a working method to copy the content into the clipboard and pasting at in Outlook and other Mail programs in the right style.

I use TailwindCSS and have already tried border-0, border-none and even border-transparent. The gray box remains when the clipboard is inserted. Through my DevTools, I was able to figure out that it is actually due to the "border-style: solid;" value. By using border-none over the content I should be able to override a global value though, right? (Already tried !important, doesn't change anything).


问:
Processing just one service bus topic message at a time
I am subscribed to a Azure servicebus topic made by an external department. The way I want the code to work is as follows:

Trigger an http endpoint that starts processorClient and listens to the topic.

Fetches one message

Does required actions to that message

Closes processorClient connection.

Repeat

I am using the ServiceBusProcessorClient class as shown in the following documentation Receive messages from a subscription

Is there a way to utilize this code in order to only fetch one message from the topic at a time before calling the processorClient.close();

I have tried using setting maxConcurrentCalls and setting prefetchCount(0).


问:
Initialize a Object having multiple Object as Properties
I have a class as

```<code>public class Root
    {
        public Child1 child1 { get; set; }
        public Child2 child2 { get; set; }
    }
    public class Child1
    {
        public Grandchild grandChild { get; set; }
    }
    public class Grandchild
    {
        public string a { get; set; }
    }
</code>```

I am trying to get the output in json as

```<code>{
    "Child1": {
        "Grandchild": {
            "a": ""
        }
    },
    "Child2":{...}
}
</code>```

I am having a constraint of not using a constructor, is there a better way instead of manually initializing each and every class?

Have tried using a contactResolver but from that only till child1 and child2 are getting initializd

```<code>{
    "Child1": {
        "Grandchild": null
    },
    "Child2":{...}
}
</code>```

If I serialize new Root() then I will get the json as

```<code>{
"Child1" : null,
"Child2": null
}
</code>```

Is there a way without defining the constructor to get the expected output?

Body:
I have a class as

public class Root
    {
        public Child1 child1 { get; set; }
        public Child2 child2 { get; set; }
    }
    public class Child1
    {
        public Grandchild grandChild { get; set; }
    }
    public class Grandchild
    {
        public string a { get; set; }
    }

I am trying to get the output in json as

{
    "Child1": {
        "Grandchild": {
            "a": ""
        }
    },
    "Child2":{...}
}

I am having a constraint of not using a constructor, is there a better way instead of manually initializing each and every class?

Have tried using a contactResolver but from that only till child1 and child2 are getting initializd

{
    "Child1": {
        "Grandchild": null
    },
    "Child2":{...}
}

If I serialize new Root() then I will get the json as

{
"Child1" : null,
"Child2": null
}

Is there a way without defining the constructor to get the expected output?


问:
Gradle: download only transitive dependencies
I want to changed jar from local file but i need all transitive dependencies.
Gradle doesn't download transitive dependencies for locaal jar file.

How to download only transitive dependencies and exclude main dependencies as it will be load from local?
Or how can i download transitive dependencies for local jar?


问:
Correctly publish a Flux to multiple streams being merged later on
I am developing on a project utilizing Project Reactor, and due to requirements of the
project, I often have to retrieve values from an API, and then both store the result and return it.
What is the best way to do this?
Currently, I implemented it in the following way:

```<code>void main() {
    getAndSaveBirds()
      .subscribe(bird -> System.out.println(bird));
}

Flux<Bird> getAndSaveBirds() {
    Flux<Bird> birds = api.getBirds().cache();
    return birds.collectList()
            .doOnSuccess(birdList -> performSideEffect(birdList))
            .thenMany(birds);
}
</code>```

But I am thinking that this might be a wasteful approach, as I now would save each Bird
unnecessarily.
I was considering the .share() operator, but the documentation regarding it is very sparse.

Which operator/program flow would be the correct here?

Body:
I am developing on a project utilizing Project Reactor, and due to requirements of the
project, I often have to retrieve values from an API, and then both store the result and return it.
What is the best way to do this?
Currently, I implemented it in the following way:

void main() {
    getAndSaveBirds()
      .subscribe(bird -> System.out.println(bird));
}

Flux<Bird> getAndSaveBirds() {
    Flux<Bird> birds = api.getBirds().cache();
    return birds.collectList()
            .doOnSuccess(birdList -> performSideEffect(birdList))
            .thenMany(birds);
}

But I am thinking that this might be a wasteful approach, as I now would save each Bird
unnecessarily.
I was considering the .share() operator, but the documentation regarding it is very sparse.

Which operator/program flow would be the correct here?


问:
Why can't I search a populated data in MUI DataGrid?
How can I search studentId under seller_id? I can search every thing that is not nested

so for example, this is my JSON file.

```<code>{
        "_id": "63b4f0ede5aa347e5edd0b9f",
        "seller_id": {
            "_id": "63b3b74156b8664b50a1fe86",
            "firstname": "test1",
            "lastname": "test1",
            "department": "CASE",
            "studentId": "1234567891"
        },
        "title": "product 1 2",
        "status": "available",
        "category": "CBMA",
        "price": "50",
        "quantity": 17,
    },
</code>```

datatable.js

```<code>const productColumn = [
  {field: '_id', headerName: "Product ID", width: 250},
  {
    field: "seller_id",
    headerName: "Student ID",
    width: 250,
    renderCell: (params) => {
      console.log(params.row)
      return (
        <div className="cellWithImg">
          <img className="cellImg" src={params.row?.seller_id?.img || avatarImage} />
          {params.row.seller_id.studentId}
        </div>
      )
    },
  },
  {
    field: 'title',
    headerName: 'Item',
    width: 250,
    renderCell: (params) => {
      return (
        <div className="cellWithImg">
          <img className="cellImg" src={params.row?.img} alt="avatar" />
          {params.row?.title}
        </div>
      )
    },
  },

  {
    field: 'price',
    headerName: 'Price',
    width: 230,
    renderCell: (params) => {
      console.log(params)
      return (
        <div className="cellWithImg">
          ₱ {params.row?.price}
        </div>
      )
    },

  },
  {
    field: 'quantity',
    headerName: 'Quantity',
    width: 230,
  },

]
</code>```

So in this image, I can search the _id which is not in a nested

But when I tried to search studentId under seller_id. I get an empty

Body:
How can I search studentId under seller_id? I can search every thing that is not nested

so for example, this is my JSON file.

{
        "_id": "63b4f0ede5aa347e5edd0b9f",
        "seller_id": {
            "_id": "63b3b74156b8664b50a1fe86",
            "firstname": "test1",
            "lastname": "test1",
            "department": "CASE",
            "studentId": "1234567891"
        },
        "title": "product 1 2",
        "status": "available",
        "category": "CBMA",
        "price": "50",
        "quantity": 17,
    },

datatable.js

const productColumn = [
  {field: '_id', headerName: "Product ID", width: 250},
  {
    field: "seller_id",
    headerName: "Student ID",
    width: 250,
    renderCell: (params) => {
      console.log(params.row)
      return (

          {params.row.seller_id.studentId}

      )
    },
  },
  {
    field: 'title',
    headerName: 'Item',
    width: 250,
    renderCell: (params) => {
      return (

          {params.row?.title}

      )
    },
  },

  {
    field: 'price',
    headerName: 'Price',
    width: 230,
    renderCell: (params) => {
      console.log(params)
      return (

          ₱ {params.row?.price}

      )
    },

  },
  {
    field: 'quantity',
    headerName: 'Quantity',
    width: 230,
  },

]

So in this image, I can search the _id which is not in a nested

But when I tried to search studentId under seller_id. I get an empty


问:
ASP.NET Core Web API - How to perform advanced Excel upload using EPPLUS
Using ASP.NET Core-6 Web API as backend, I am uploading Excel file with EPPLUS package. I have this code.

```<code>public class LeaveApplication
{
    public Guid Id { get; set; }
    public string EmployeeId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public LeaveType? LeaveType { get; set; }
    public decimal Amount { get; set; }
}
</code>```

EnumList:

```<code>public class EnumList
{
    public enum LeaveType : byte
    {
        Annual = 1,
        Casual = 2,
        Compassionate = 3,
        Maternity = 4
    }
}
</code>```

So I have this method for the Excel upload.

```<code>public async Task<List<LeaveApplication>> Import(IFormFile file)
{
    var list = new List<LeaveApplication>();
    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);
        using (var package = new ExcelPackage(stream))
        {

            ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
            var rowcount = worksheet.Dimension.Rows;
            var colcount = worksheet.Dimension.Columns;

            for (int row = 2; row < rowcount; row++)
            {
                list.Add(new LeaveApplication {
                    EmployeeId = worksheet.Cells[row,1].Value.ToString().Trim(),
                    StartDate = DateTime.Parse(worksheet.Cells[row, 2].Value.ToString()),
                    EndDate = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString()),
                    LeaveType = String.IsNullOrEmpty(worksheet.Cells[row, 4].Value.ToString())
                      ? (EnumList.LeaveType?)null
                      : (EnumList.LeaveType)byte.Parse(worksheet.Cells[row, 4].Value.ToString()),
                    Amount = decimal.Parse(worksheet.Cells[row, 5].Value.ToString())
                });
            }
        }
    }
    _dbContext.LeaveApplications.AddRange(list);
    await _dbContext.SaveChangesAsync();

    return list;
}
</code>```

As I upload the records:

I want the application to insert only the successful records and display them after upload.

The unsuccessful ones should not be inserted, but the fields that failed and the reasons for failure should  also be displayed for correction.

How do I achieve these?

Body:
Using ASP.NET Core-6 Web API as backend, I am uploading Excel file with EPPLUS package. I have this code.

public class LeaveApplication
{
    public Guid Id { get; set; }
    public string EmployeeId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public LeaveType? LeaveType { get; set; }
    public decimal Amount { get; set; }
}

EnumList:

public class EnumList
{
    public enum LeaveType : byte
    {
        Annual = 1,
        Casual = 2,
        Compassionate = 3,
        Maternity = 4
    }
}

So I have this method for the Excel upload.

public async Task<List<LeaveApplication>> Import(IFormFile file)
{
    var list = new List<LeaveApplication>();
    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);
        using (var package = new ExcelPackage(stream))
        {

            ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
            var rowcount = worksheet.Dimension.Rows;
            var colcount = worksheet.Dimension.Columns;

            for (int row = 2; row < rowcount; row++)
            {
                list.Add(new LeaveApplication {
                    EmployeeId = worksheet.Cells[row,1].Value.ToString().Trim(),
                    StartDate = DateTime.Parse(worksheet.Cells[row, 2].Value.ToString()),
                    EndDate = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString()),
                    LeaveType = String.IsNullOrEmpty(worksheet.Cells[row, 4].Value.ToString())
                      ? (EnumList.LeaveType?)null
                      : (EnumList.LeaveType)byte.Parse(worksheet.Cells[row, 4].Value.ToString()),
                    Amount = decimal.Parse(worksheet.Cells[row, 5].Value.ToString())
                });
            }
        }
    }
    _dbContext.LeaveApplications.AddRange(list);
    await _dbContext.SaveChangesAsync();

    return list;
}

As I upload the records:

I want the application to insert only the successful records and display them after upload.

The unsuccessful ones should not be inserted, but the fields that failed and the reasons for failure should  also be displayed for correction.

How do I achieve these?


问:
NetBeans IDE is not accepting any input after I run code scanner
I am using JDK19 on NetBeans IDE.

After I run the code with scanner the NetBeans IDE is not accepting any input from me, so I could not continue the code "but before I used jcreator and I could input numbers into the console"

I keep googling and YouTube on how people run the code, and even google how to run code in netbeans so I learn I can right click to run a single code, but the code ran but I could not type in any numbers "integer"


问:
How can I debug a launch configuration?
We have a new team member trying to get started with our Godot project. VSCode is our standard editor. Everyone is using Fedora Linux. You can find the relevant files here:

https://github.com/redhat-gamedev/srt-godot-server/tree/main/.vscode

On my machine, when trying to run the launch configuration, the build task succeeds, and then the program is launched. Everything works fine.

On the new team member's machine, when trying to run the launch configuration, the build task succeeds, and then nothing happens. There are no errors. There is no output.

We tried running VSCode with an increased log level (debug), but the VScode log files don't show anything meaningful or related. We tried executing the equivalent launch command from the terminal/shell and it works fine. There are no errors, but the resulting built program executes successfully. Interestingly, running code --verbose does produce a ton of output but nothing super specific to the execution of the steps in the launch configuration. Also, code --verbose --log debug does not cause messages spit out of VSCode to be at the DEBUG log level. Everything is still INFO:

```<code>[4183395:0112/092541.932947:INFO:CONSOLE(616)] "%cTRACE color: #888 [File Watcher (parcel)] [CHANGED] ...
</code>```

How can I debug a launch configuration in VSCode to see what's going on? Is there a way to make the launch configuration system of VSCode be more verbose?

Title: How can I debug a launch configuration?

Body:
We have a new team member trying to get started with our Godot project. VSCode is our standard editor. Everyone is using Fedora Linux. You can find the relevant files here:

https://github.com/redhat-gamedev/srt-godot-server/tree/main/.vscode

On my machine, when trying to run the launch configuration, the build task succeeds, and then the program is launched. Everything works fine.

On the new team member's machine, when trying to run the launch configuration, the build task succeeds, and then nothing happens. There are no errors. There is no output.

We tried running VSCode with an increased log level (debug), but the VScode log files don't show anything meaningful or related. We tried executing the equivalent launch command from the terminal/shell and it works fine. There are no errors, but the resulting built program executes successfully. Interestingly, running code --verbose does produce a ton of output but nothing super specific to the execution of the steps in the launch configuration. Also, code --verbose --log debug does not cause messages spit out of VSCode to be at the DEBUG log level. Everything is still INFO:

[4183395:0112/092541.932947:INFO:CONSOLE(616)] "%cTRACE color: #888 [File Watcher (parcel)] [CHANGED] ...

How can I debug a launch configuration in VSCode to see what's going on? Is there a way to make the launch configuration system of VSCode be more verbose?


问:
Firebase Realtime Database listeners not returning data
In our PWA iOS app (built with Outsystems) we are have an issue where the Firebase Realtime Database Javascript SDK .on() and .get() functions are not returning any data or an error. It seems to fail silently.

On first start up everything works perfectly. When the app is in a paused state for an undetermined amount of time, coming back to app and making the calls below do not return anything.

Before making the calls we check for connection and the status is true.

Here is the code:

```<code>  var _setConversationOnValue = function (conversationKey, successCallback) {
    try {
      _firebaseRefCheckConnection.on('value', (snap) => {
        if (snap.val() === true) {
          console.log('connected'); //This is TRUE and hit.
        } else {
          console.log('not connected');
        }
      });

      //Attempting a .get()
      _refs.Conversation.child(conversationKey)
        .get()
        .then(function (snapshot) {
          // NEVER GETS HERE
          console.log('IN GET() Conversation Callback');
        })
        .catch(function (error) {
          // NEVER GETS HERE
          console.error(error);
        });
      //Attempting a .on()
      return _refs.Conversation.child(conversationKey).on('value',
        successCallback, //NEVER GETS HERE
        function (error) {
          //NEVER GETS HERE
          console.error('Error Creating Lisenter');
          console.error(error);
      });
    } catch (error) {
      console.error('Error in _setConversationOnValue');
      console.error(error);
    }
  };
</code>```

Javascript SDK version is 8.6.1

We have tried this workaround:

```<code>if (localStorage) { // fix for API
    localStorage.removeItem("firebase:previous_websocket_failure");
}

</code>```

But, this doesn't work as the item is not in localStorage when the app resumes.

Body:
In our PWA iOS app (built with Outsystems) we are have an issue where the Firebase Realtime Database Javascript SDK .on() and .get() functions are not returning any data or an error. It seems to fail silently.

On first start up everything works perfectly. When the app is in a paused state for an undetermined amount of time, coming back to app and making the calls below do not return anything.

Before making the calls we check for connection and the status is true.

Here is the code:

  var _setConversationOnValue = function (conversationKey, successCallback) {
    try {
      _firebaseRefCheckConnection.on('value', (snap) => {
        if (snap.val() === true) {
          console.log('connected'); //This is TRUE and hit.
        } else {
          console.log('not connected');
        }
      });

      //Attempting a .get()
      _refs.Conversation.child(conversationKey)
        .get()
        .then(function (snapshot) {
          // NEVER GETS HERE
          console.log('IN GET() Conversation Callback');
        })
        .catch(function (error) {
          // NEVER GETS HERE
          console.error(error);
        });
      //Attempting a .on()
      return _refs.Conversation.child(conversationKey).on('value',
        successCallback, //NEVER GETS HERE
        function (error) {
          //NEVER GETS HERE
          console.error('Error Creating Lisenter');
          console.error(error);
      });
    } catch (error) {
      console.error('Error in _setConversationOnValue');
      console.error(error);
    }
  };

Javascript SDK version is 8.6.1

We have tried this workaround:

if (localStorage) { // fix for API
    localStorage.removeItem("firebase:previous_websocket_failure");
}

But, this doesn't work as the item is not in localStorage when the app resumes.


问:
Is there another function that can find the list of all Packages starting with a Prefix in C#?
I have this code in the main method of my C# program and I am trying to find the UWP applications using this bit of code.

```<code>string packageFamilyName = "GenericName.";
PackageCatalog packageCatalog = PackageCatalog.OpenForCurrentUser();
foreach (Package p in packages)
      {
         Console.WriteLine(p.DisplayName)
      }
</code>```

I have the heading of my C# algorithm, and its dependencies and framework.

Just in case I am missing a dependency of any sorts I attached the following image showing my setup.

The code should look for a family of packages in AppData, Program Files, or Program Files(x86) in a Windows computer and return a list of packages installed for a user. This is part of a bigger code which already accomplishes the latter two in searching through Program Files, and Program Files(x86).

A sample output could be:

```<code>GenericName.StickNotes
GenericName.Calendar
GenericName.Calculator
</code>```

I would also like to mention that my program runs on a .NET6.0 Platform and I installed the Microsoft.Windows.SDK.Contracts using NuGet manager. My IDE is Visual Studio Professional 2022.

Body:
I have this code in the main method of my C# program and I am trying to find the UWP applications using this bit of code.

string packageFamilyName = "GenericName.";
PackageCatalog packageCatalog = PackageCatalog.OpenForCurrentUser();
foreach (Package p in packages)
      {
         Console.WriteLine(p.DisplayName)
      }

I have the heading of my C# algorithm, and its dependencies and framework.

Just in case I am missing a dependency of any sorts I attached the following image showing my setup.

The code should look for a family of packages in AppData, Program Files, or Program Files(x86) in a Windows computer and return a list of packages installed for a user. This is part of a bigger code which already accomplishes the latter two in searching through Program Files, and Program Files(x86).

A sample output could be:

GenericName.StickNotes
GenericName.Calendar
GenericName.Calculator

I would also like to mention that my program runs on a .NET6.0 Platform and I installed the Microsoft.Windows.SDK.Contracts using NuGet manager. My IDE is Visual Studio Professional 2022.


问:
A non-serializable value was detected in the state: redux toolkit
I am trying to implement Redux toolkit store in a react native application. It is my first time. I am using axios to make requests to the API.
I am getting this error on a post request:

```<code> A non-serializable value was detected in the state, in the path: `user`. Value: {"_A": null,
 "_x": 0, "_y": 0, "_z": null}
 Take a look at the reducer(s) handling this action type: userreg/fulfilled.
</code>```

Here are my codes:

```<code>const initialState={
token: '',
session: '',
loading: false,
}

  export const logInUser = createAsyncThunk('userreg', async(name, thunkAPI)=>{
  const {user_username, user_password} = name
  //const m =  JSON.stringify(name)
    const res = await axios.post(`${BASE_URL}/login`,
    {
        user_username, user_password
    }
    )
    //console.log(res.data)
    return res.data

  })

   const userSlice = createSlice({
   name: 'user',
   initialState,
   reducers:{
    addSession:(state, action)=>{
        state.session = AsyncStorage.getItem('sessionId')
    },
    addToken:(state, action)=>{
        state.token = AsyncStorage.getItem('token')
    }
    },
    extraReducers: (builders)=>{
    builders.addCase(logInUser.pending, (state, action)=>{
        state.loading = true
    })
   builders.addCase(logInUser.fulfilled, async(state, {payload})=>{
    console.log(payload, 'slode ier')
        state.loading = false
        state.token = payload.userToken;
        state.session = payload.session;
        await AsyncStorage.setItem('sessionId', payload.session);
       await AsyncStorage.setItem('token', payload.userToken)
    })
  }
  })

  export default  userSlice.reducer;

const handleUserLog = async ()=>{

const logDetails = {
    user_username: userLogin.user_username,
    user_password: userLogin.user_password,
   }
    dispatch(logInUser(logDetails))
   }
</code>```

When I implemented the same code with fetch instead of axios to make the same request to the API, it didn't give this error.

Body:
I am trying to implement Redux toolkit store in a react native application. It is my first time. I am using axios to make requests to the API.
I am getting this error on a post request:

 A non-serializable value was detected in the state, in the path: `user`. Value: {"_A": null,
 "_x": 0, "_y": 0, "_z": null}
 Take a look at the reducer(s) handling this action type: userreg/fulfilled.

Here are my codes:

const initialState={
token: '',
session: '',
loading: false,
}

  export const logInUser = createAsyncThunk('userreg', async(name, thunkAPI)=>{
  const {user_username, user_password} = name
  //const m =  JSON.stringify(name)
    const res = await axios.post(`${BASE_URL}/login`,
    {
        user_username, user_password
    }
    )
    //console.log(res.data)
    return res.data

  })

   const userSlice = createSlice({
   name: 'user',
   initialState,
   reducers:{
    addSession:(state, action)=>{
        state.session = AsyncStorage.getItem('sessionId')
    },
    addToken:(state, action)=>{
        state.token = AsyncStorage.getItem('token')
    }
    },
    extraReducers: (builders)=>{
    builders.addCase(logInUser.pending, (state, action)=>{
        state.loading = true
    })
   builders.addCase(logInUser.fulfilled, async(state, {payload})=>{
    console.log(payload, 'slode ier')
        state.loading = false
        state.token = payload.userToken;
        state.session = payload.session;
        await AsyncStorage.setItem('sessionId', payload.session);
       await AsyncStorage.setItem('token', payload.userToken)
    })
  }
  })

  export default  userSlice.reducer;

const handleUserLog = async ()=>{

const logDetails = {
    user_username: userLogin.user_username,
    user_password: userLogin.user_password,
   }
    dispatch(logInUser(logDetails))
   }

When I implemented the same code with fetch instead of axios to make the same request to the API, it didn't give this error.


问:
Best practice when using OpenIddict application properties
I'm using the Properties column in my OpenIddict applications to store some metadata about an application instead of using a custom entity - comments on this post custom properties within token imply that's what its meant for.

However, despite reading the above post I'm struggling to understand how best to implement this.

Currently my "create application" looks like this:

```<code>public interface IOpenIddictAppService
{
    Task<CreateOpenIddictAppResponseDto> CreateAsync(CreateOpenIddictAppRequestDto appDto);
}

public class OpenIddictAppService : IOpenIddictAppService
{
    private readonly IOpenIddictApplicationManager _appManager;

    public OpenIddictAppService(IOpenIddictApplicationManager appManager)
    {
        _appManager = appManager;
    }

    public async Task<CreateOpenIddictAppResponseDto> CreateAsync(CreateOpenIddictAppRequestDto appDto)
    {
        var sha = SHA512.Create();
        var clientId = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())));
        var clientSecret = SecureRandomStringHelper.Create(StaticData.ClientSecretSize);

        var data = new OpenIddictApplicationDescriptor
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            DisplayName = appDto.Name,
            Permissions =
            {
                OpenIddictConstants.Permissions.Endpoints.Token,
                OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                OpenIddictConstants.Permissions.Prefixes.Scope + "api",
                OpenIddictConstants.Permissions.ResponseTypes.Code
            }
        };

        // Postman test URL"https://oauth.pstmn.io/v1/callback"
        appDto.RedirectUrls.Split(" ").ToList().ForEach(x => data.RedirectUris.Add(new Uri(x)));
        data.Properties.Add("IdentityConfig", JsonSerializer.SerializeToElement(new AppIdentityProperties
        {
            ClientSystemId = appDto.ClientSystemId,
            CustomerAccountId = appDto.CustomerAccountId
        }));

        var app = await _appManager.CreateAsync(data);

        CreateOpenIddictAppResponseDto result = new()
        {
            Id = new Guid(await _appManager.GetIdAsync(app) ?? throw new ArgumentNullException("OpenIddictApplication not found")),
            ClientId = clientId, // Send back the client id used
            ClientSecret = clientSecret, // Send back the secret used so it can be displayed one-time-only for copy/paste
            RedirectUrls = string.Join(" ", await _appManager.GetRedirectUrisAsync(app))
        };

        return result;
    }
}
</code>```

And I'm loading it like this in my authorization controller:

```<code>[HttpPost("~/connect/token")]
public async Task<IActionResult> Exchange()
{
    var request = HttpContext.GetOpenIddictServerRequest() ??
                  throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

    ClaimsPrincipal claimsPrincipal;

    if (request.IsClientCredentialsGrantType())
    {
        // Note: the client credentials are automatically validated by OpenIddict:
        // if client_id or client_secret are invalid, this action won't be invoked.

        var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
        if (application == null)
        {
            throw new InvalidOperationException("The application details cannot be found in the database.");
        }

        // Create the claims-based identity that will be used by OpenIddict to generate tokens.
        var identity = new ClaimsIdentity(
            authenticationType: TokenValidationParameters.DefaultAuthenticationType,
            nameType: Claims.Name,
            roleType: Claims.Role);

        // Add the claims that will be persisted in the tokens (use the client_id as the subject identifier).
        identity.AddClaim(Claims.Subject, await _applicationManager.GetClientIdAsync(application))
                .AddClaim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application));

        var properties = await _applicationManager.GetPropertiesAsync(application);
        if (properties.Any(o => o.Key == "IdentityConfig"))
        {
            var identityConfig = JsonSerializer.Deserialize<AppIdentityProperties>(properties.FirstOrDefault(o => o.Key == "IdentityConfig").Value);
            if (identityConfig != null)
            {
                identity.AddClaim(StaticData.Claims.ClientSystem, identityConfig.ClientSystemId.ToString())
                        .AddClaim(StaticData.Claims.CustomerAccount, identityConfig.CustomerAccountId.ToString());
            }
        }

        identity.SetDestinations(static claim => claim.Type switch
        {
            // Allow the "name" claim to be stored in both the access and identity tokens
            // when the "profile" scope was granted (by calling principal.SetScopes(...)).
            Claims.Name when claim.Subject.HasScope(Scopes.Profile)
                => new[] { Destinations.AccessToken, Destinations.IdentityToken },

            // Otherwise, only store the claim in the access tokens.
            _ => new[] { Destinations.AccessToken }
        });

        // Note: In the original OAuth 2.0 specification, the client credentials grant
        // doesn't return an identity token, which is an OpenID Connect concept.
        //
        // As a non-standardized extension, OpenIddict allows returning an id_token
        // to convey information about the client application when the "openid" scope
        // is granted (i.e specified when calling principal.SetScopes()). When the "openid"
        // scope is not explicitly set, no identity token is returned to the client application.

        // Set the list of scopes granted to the client application in access_token.
        claimsPrincipal = new ClaimsPrincipal(identity);

        claimsPrincipal.SetScopes(request.GetScopes());

        claimsPrincipal.SetResources(await _scopeManager.ListResourcesAsync(claimsPrincipal.GetScopes()).ToListAsync());
    }
    else if (request.IsAuthorizationCodeGrantType())
    {
        // Retrieve the claims principal stored in the authorization code
        claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
    }
    else if (request.IsRefreshTokenGrantType())
    {
        // Retrieve the claims principal stored in the refresh token.
        claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
    }
    else
    {
        throw new InvalidOperationException("The specified grant type is not supported.");
    }

    // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
    return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
</code>```

Now - it's working...but I have a sneaky feeling that I'm just using it wrong especially based on Kevin Chalet's comments on that post... I think I'm probably also setting the redirect URLs the wrong way too!

Can anyone give me any more specific guidance on how I should really be doing this.

Body:
I'm using the Properties column in my OpenIddict applications to store some metadata about an application instead of using a custom entity - comments on this post custom properties within token imply that's what its meant for.

However, despite reading the above post I'm struggling to understand how best to implement this.

Currently my "create application" looks like this:

public interface IOpenIddictAppService
{
    Task<CreateOpenIddictAppResponseDto> CreateAsync(CreateOpenIddictAppRequestDto appDto);
}

public class OpenIddictAppService : IOpenIddictAppService
{
    private readonly IOpenIddictApplicationManager _appManager;

    public OpenIddictAppService(IOpenIddictApplicationManager appManager)
    {
        _appManager = appManager;
    }

    public async Task<CreateOpenIddictAppResponseDto> CreateAsync(CreateOpenIddictAppRequestDto appDto)
    {
        var sha = SHA512.Create();
        var clientId = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())));
        var clientSecret = SecureRandomStringHelper.Create(StaticData.ClientSecretSize);

        var data = new OpenIddictApplicationDescriptor
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            DisplayName = appDto.Name,
            Permissions =
            {
                OpenIddictConstants.Permissions.Endpoints.Token,
                OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                OpenIddictConstants.Permissions.Prefixes.Scope + "api",
                OpenIddictConstants.Permissions.ResponseTypes.Code
            }
        };

        // Postman test URL"https://oauth.pstmn.io/v1/callback"
        appDto.RedirectUrls.Split(" ").ToList().ForEach(x => data.RedirectUris.Add(new Uri(x)));
        data.Properties.Add("IdentityConfig", JsonSerializer.SerializeToElement(new AppIdentityProperties
        {
            ClientSystemId = appDto.ClientSystemId,
            CustomerAccountId = appDto.CustomerAccountId
        }));

        var app = await _appManager.CreateAsync(data);

        CreateOpenIddictAppResponseDto result = new()
        {
            Id = new Guid(await _appManager.GetIdAsync(app) ?? throw new ArgumentNullException("OpenIddictApplication not found")),
            ClientId = clientId, // Send back the client id used
            ClientSecret = clientSecret, // Send back the secret used so it can be displayed one-time-only for copy/paste
            RedirectUrls = string.Join(" ", await _appManager.GetRedirectUrisAsync(app))
        };

        return result;
    }
}

And I'm loading it like this in my authorization controller:

[HttpPost("~/connect/token")]
public async Task<IActionResult> Exchange()
{
    var request = HttpContext.GetOpenIddictServerRequest() ??
                  throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

    ClaimsPrincipal claimsPrincipal;

    if (request.IsClientCredentialsGrantType())
    {
        // Note: the client credentials are automatically validated by OpenIddict:
        // if client_id or client_secret are invalid, this action won't be invoked.

        var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
        if (application == null)
        {
            throw new InvalidOperationException("The application details cannot be found in the database.");
        }

        // Create the claims-based identity that will be used by OpenIddict to generate tokens.
        var identity = new ClaimsIdentity(
            authenticationType: TokenValidationParameters.DefaultAuthenticationType,
            nameType: Claims.Name,
            roleType: Claims.Role);

        // Add the claims that will be persisted in the tokens (use the client_id as the subject identifier).
        identity.AddClaim(Claims.Subject, await _applicationManager.GetClientIdAsync(application))
                .AddClaim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application));

        var properties = await _applicationManager.GetPropertiesAsync(application);
        if (properties.Any(o => o.Key == "IdentityConfig"))
        {
            var identityConfig = JsonSerializer.Deserialize<AppIdentityProperties>(properties.FirstOrDefault(o => o.Key == "IdentityConfig").Value);
            if (identityConfig != null)
            {
                identity.AddClaim(StaticData.Claims.ClientSystem, identityConfig.ClientSystemId.ToString())
                        .AddClaim(StaticData.Claims.CustomerAccount, identityConfig.CustomerAccountId.ToString());
            }
        }

        identity.SetDestinations(static claim => claim.Type switch
        {
            // Allow the "name" claim to be stored in both the access and identity tokens
            // when the "profile" scope was granted (by calling principal.SetScopes(...)).
            Claims.Name when claim.Subject.HasScope(Scopes.Profile)
                => new[] { Destinations.AccessToken, Destinations.IdentityToken },

            // Otherwise, only store the claim in the access tokens.
            _ => new[] { Destinations.AccessToken }
        });

        // Note: In the original OAuth 2.0 specification, the client credentials grant
        // doesn't return an identity token, which is an OpenID Connect concept.
        //
        // As a non-standardized extension, OpenIddict allows returning an id_token
        // to convey information about the client application when the "openid" scope
        // is granted (i.e specified when calling principal.SetScopes()). When the "openid"
        // scope is not explicitly set, no identity token is returned to the client application.

        // Set the list of scopes granted to the client application in access_token.
        claimsPrincipal = new ClaimsPrincipal(identity);

        claimsPrincipal.SetScopes(request.GetScopes());

        claimsPrincipal.SetResources(await _scopeManager.ListResourcesAsync(claimsPrincipal.GetScopes()).ToListAsync());
    }
    else if (request.IsAuthorizationCodeGrantType())
    {
        // Retrieve the claims principal stored in the authorization code
        claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
    }
    else if (request.IsRefreshTokenGrantType())
    {
        // Retrieve the claims principal stored in the refresh token.
        claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
    }
    else
    {
        throw new InvalidOperationException("The specified grant type is not supported.");
    }

    // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
    return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}

Now - it's working...but I have a sneaky feeling that I'm just using it wrong especially based on Kevin Chalet's comments on that post... I think I'm probably also setting the redirect URLs the wrong way too!

Can anyone give me any more specific guidance on how I should really be doing this.


问:
Oracle is using both full table scan instead of index scan
i am joining two tables and i have index on both columns but still oracle chooses full table scan on both instead of index scan.

i have mentioned below the query

SELECT * FROM Table 1, Table2 WHERE   Tab1_col= Tab2_col

and here it can been seen in execution plan that it is going on Full table scan


问:
C# Write to and read from txt file

Hallo! I have a specific question about my homework - C# window form app.
I enter data in text fields - first name, surname, last name, phone, email and date of birth (the last one is DateTimePicker control). And I save them with a button (
It's not actually saved at this stage, the data just goes to the other page of the app.)

Full names appear in ComboBox in other TabPage. When I select a name, I get the complete information about the person. I do that and it's works.(I'm using arrays).

The task done so far does not store any information. All input is lost when the application is closed.
The other part of the task gives me trouble - a link to an external text file in which the entered data is stored.

I create a text file and save information in it with this code :

```<code>               private void button3_Click(object sender, EventArgs e)
        {
            TextWriter txt = new StreamWriter("D:\\data.txt");
            for (int k = 0; k <= i; k++)
            {
                txt.Write(Names[k] + "\n" + Phone[k] + "\n" + Email[k] + "\n" + Birthday[k] + "\n");
            }
            txt.Close();
            MessageBox.Show("Data saved in data.txt file on drive D!", "Caution!", 0);

        }
</code>```

And the problem is that I can't open and read the file to load the data back into the app.
I need to be able to load the full names in my ComboBox and when I select a name to see all the personal information about that person.
I attach file with my app - page1 and page2 and my text file with store data.
Thanks in advance to everyone who responds :)

And the problem is that I can't open and read the file to load the data back into the app.
I need to be able to load the full names in my ComboBox and when I select a name to see all the personal information about that person.

Title: C# Write to and read from txt file

Body:
Hallo! I have a specific question about my homework - C# window form app.
I enter data in text fields - first name, surname, last name, phone, email and date of birth (the last one is DateTimePicker control). And I save them with a button (
It's not actually saved at this stage, the data just goes to the other page of the app.)

Full names appear in ComboBox in other TabPage. When I select a name, I get the complete information about the person. I do that and it's works.(I'm using arrays).

The task done so far does not store any information. All input is lost when the application is closed.
The other part of the task gives me trouble - a link to an external text file in which the entered data is stored.

I create a text file and save information in it with this code :

               private void button3_Click(object sender, EventArgs e)
        {
            TextWriter txt = new StreamWriter("D:\\data.txt");
            for (int k = 0; k <= i; k++)
            {
                txt.Write(Names[k] + "\n" + Phone[k] + "\n" + Email[k] + "\n" + Birthday[k] + "\n");
            }
            txt.Close();
            MessageBox.Show("Data saved in data.txt file on drive D!", "Caution!", 0);

        }

And the problem is that I can't open and read the file to load the data back into the app.
I need to be able to load the full names in my ComboBox and when I select a name to see all the personal information about that person.
I attach file with my app - page1 and page2 and my text file with store data.
Thanks in advance to everyone who responds :)

And the problem is that I can't open and read the file to load the data back into the app.
I need to be able to load the full names in my ComboBox and when I select a name to see all the personal information about that person.


问:
df = df.loc yield empty DataFrame in a loop [Python] [Pandas]
Sorry if this is a dumb question, I'm a very noob coder.

I'm trying to itinerate through a folder and create DataFrames for each file (then saving it).

Thing is, I changed nothing from when it was not in a for loop (for testing) and it was working perfectly fine, but now in the for loop it yields an empty DataFrame, so I can't do anything.

The important (failure) part of the code is as follows:

```<code>filePath=(insert pathFile here)

def CDPBot():

    fileItineration = filePath + '/' + files
    file = pd.read_excel(fileItineration)

    # Agarra el nombre de la empresa para despues
    companyName= str(file['Final Account Name'][2])
    #companyName=file.loc[3:2]
    #companyName=companyName.columns.values[2]

    #DMU
    faID=os.path.basename(files)
    faID=faID[-0:-5]

    #Arma el DF usando los filtros proporcionados
    f_file = file.loc[(f_file['Segment'] == ('SMB')) & (f_file['Final Account ID'] == faID) | (f_file['Segment'] == ('Commercial')) & (f_file['Final Account ID'] == faID)]

    if file.empty:
        print('file is empty!')
    elif f_file.empty:
        print('f_file is empty')

...
...
...

for files in os.listdir(filePath):
    CDPBot()
</code>```

Issue is f_file is an empty DataFrame no matter what I do or try. I don't know why it's yielding that result, any ideas? The rest of the code (I didn't paste everything because it's irrelevant) works just fine.

Thanks in advance!

Body:
Sorry if this is a dumb question, I'm a very noob coder.

I'm trying to itinerate through a folder and create DataFrames for each file (then saving it).

Thing is, I changed nothing from when it was not in a for loop (for testing) and it was working perfectly fine, but now in the for loop it yields an empty DataFrame, so I can't do anything.

The important (failure) part of the code is as follows:

filePath=(insert pathFile here)

def CDPBot():

    fileItineration = filePath + '/' + files
    file = pd.read_excel(fileItineration)

    # Agarra el nombre de la empresa para despues
    companyName= str(file['Final Account Name'][2])
    #companyName=file.loc[3:2]
    #companyName=companyName.columns.values[2]

    #DMU
    faID=os.path.basename(files)
    faID=faID[-0:-5]

    #Arma el DF usando los filtros proporcionados
    f_file = file.loc[(f_file['Segment'] == ('SMB')) & (f_file['Final Account ID'] == faID) | (f_file['Segment'] == ('Commercial')) & (f_file['Final Account ID'] == faID)]

    if file.empty:
        print('file is empty!')
    elif f_file.empty:
        print('f_file is empty')

...
...
...

for files in os.listdir(filePath):
    CDPBot()

Issue is f_file is an empty DataFrame no matter what I do or try. I don't know why it's yielding that result, any ideas? The rest of the code (I didn't paste everything because it's irrelevant) works just fine.

Thanks in advance!


问:
I want to display a page of the app on the lock screen (android studio)
I want to display a page(activity) of the app on the lock screen
For example if a certain time comes and then I turn on the phone "on the lock screen", the app is running
I hope that is clear
Don't forget to keep in mind that I am a newbie in android studio

I tried a lot to solve the problem by applying some tutorials on YouTube, but I didn't succeed in that

THANKS.


问:
How to set Wpf Prism Region ZIndex
If there are two prism regions defined in a shell, which one is on top is determined by how these are layed out in the shell one below the other.

<Grid Grid.Row="1" x:Name="_redGrid" >
    <ContentControl prism:RegionManager.RegionName="RedRegion" />
</Grid>
<Grid Grid.Row="1" x:Name="_greenGrid">
    <ContentControl prism:RegionManager.RegionName="GreenRegion" />
</Grid>
```
<p>For a simple example, you can take a look at this. It has got a red view and a green view.
When you run, it will look like the following.</p>
<p><img src="https://i.stack.imgur.com/TqAid.png" alt="Prism Region ZIndex" /></p>
<p>Is there a way to change this dynamically? Set the zindex of the prism region at run time?</p>
<p>I have extended the above example with a button, objective here is to click the button and change the top to bottom. You can see this example here.</p>
<p>I could do this in the backend file with brute force as follows.</p>
<pre class="lang-cs prettyprint-override"><code>private void btn1_Click(object sender, RoutedEventArgs e)
{
    _mainGrid.Children.Remove(_redGrid);
    _mainGrid.Children.Remove(_greenGrid);

    if (_toggleRegion)
    {
        _mainGrid.Children.Add(_redGrid);
        _mainGrid.Children.Add(_greenGrid);
    }
    else
    {
        _mainGrid.Children.Add(_greenGrid);
        _mainGrid.Children.Add(_redGrid);
    }
    _toggleRegion = !_toggleRegion;
}
</code>```

Click the button, and now the red is on top.

So whats the best way to do this? Is there a feature in Prism which can accomplish this?

Title: How to set Wpf Prism Region ZIndex

Body:
If there are two prism regions defined in a shell, which one is on top is determined by how these are layed out in the shell one below the other.

<Grid Grid.Row="1" x:Name="_redGrid" >
    <ContentControl prism:RegionManager.RegionName="RedRegion" />
</Grid>
<Grid Grid.Row="1" x:Name="_greenGrid">
    <ContentControl prism:RegionManager.RegionName="GreenRegion" />
</Grid>

For a simple example, you can take a look at this. It has got a red view and a green view.
When you run, it will look like the following.

Is there a way to change this dynamically? Set the zindex of the prism region at run time?

I have extended the above example with a button, objective here is to click the button and change the top to bottom. You can see this example here.

I could do this in the backend file with brute force as follows.

private void btn1_Click(object sender, RoutedEventArgs e)
{
    _mainGrid.Children.Remove(_redGrid);
    _mainGrid.Children.Remove(_greenGrid);

    if (_toggleRegion)
    {
        _mainGrid.Children.Add(_redGrid);
        _mainGrid.Children.Add(_greenGrid);
    }
    else
    {
        _mainGrid.Children.Add(_greenGrid);
        _mainGrid.Children.Add(_redGrid);
    }
    _toggleRegion = !_toggleRegion;
}

Click the button, and now the red is on top.

So whats the best way to do this? Is there a feature in Prism which can accomplish this?


问:
How to write language syntax definition for Solr in Monarch (Monaco Editor)?
I have a Solr query like this one:

```<code>(content_language:English OR content_language:"American French") AND ("Los Angeles" OR Washington)
</code>```

I am trying to at least have a autocomplete for the "content_language" string but I was not able to make it. Here is my definition for Monarch that I don't know what I am missing:

```<code>return {
  defaultToken: 'invalid',
  ignoreCase: true,

  keywords: [
    'content_language'
  ],

  operators: [
    'AND', 'OR'
  ],

  tokenizer: {
    root: [
      {include: '@whitespace'},
      { include: '@strings' },
      [
        /[\w@#$]+/, {
          cases: {
            '@keywords': {token: 'keyword'},
            '@operators': 'operator',
          }
        }
      ]
    ],

    whitespace: [[/\s+/, 'white']],
        strings: [
            [/'/, { token: 'string', next: '@string' }],
            [/"/, { token: 'string.double', next: '@stringDouble' }]
        ],
        string: [
            [/[^']+/, 'string'],
            [/''/, 'string'],
            [/'/, { token: 'string', next: '@pop' }]
        ],
            stringDouble: [
            [/[^"]+/, 'string.double'],
            [/""/, 'string.double'],
            [/"/, { token: 'string.double', next: '@pop' }]
        ],
  },
};
</code>```

Body:
I have a Solr query like this one:

(content_language:English OR content_language:"American French") AND ("Los Angeles" OR Washington)

I am trying to at least have a autocomplete for the "content_language" string but I was not able to make it. Here is my definition for Monarch that I don't know what I am missing:

return {
  defaultToken: 'invalid',
  ignoreCase: true,

  keywords: [
    'content_language'
  ],

  operators: [
    'AND', 'OR'
  ],

  tokenizer: {
    root: [
      {include: '@whitespace'},
      { include: '@strings' },
      [
        /[\w@#$]+/, {
          cases: {
            '@keywords': {token: 'keyword'},
            '@operators': 'operator',
          }
        }
      ]
    ],

    whitespace: [[/\s+/, 'white']],
        strings: [
            [/'/, { token: 'string', next: '@string' }],
            [/"/, { token: 'string.double', next: '@stringDouble' }]
        ],
        string: [
            [/[^']+/, 'string'],
            [/''/, 'string'],
            [/'/, { token: 'string', next: '@pop' }]
        ],
            stringDouble: [
            [/[^"]+/, 'string.double'],
            [/""/, 'string.double'],
            [/"/, { token: 'string.double', next: '@pop' }]
        ],
  },
};


问:
The year is displayed wrong while using Date pipe and moment.js (Angular 13)
I'm using Moment.js to convert my date , but it displayed a wrong year

below a part of my code in localized-moment.ts file :

transform(value: any, pattern: string = 'short'): any {

```<code>if (value.toString().includes('-')) {

  return moment(value).locale(this.translateService.currentLang).format('L LTS');

} else {

  if (!Number.isInteger(value)) {

    value = moment.unix(value);

  }

  return moment(value).locale(this.translateService.currentLang).format('L LTS');

}
</code>```

}

then in my html , i'm using the pipe to convert :

```<code>        <td class="data-row">{{myTime | localizedMoment }}</td>
</code>```

For example if value=1672828478537 after the call of pipe , I m getting 06/01/2023 12:12:36 instead of 06/01/2022 12:12:36

Thanks for your help in advance .

Body:
I'm using Moment.js to convert my date , but it displayed a wrong year

below a part of my code in localized-moment.ts file :

transform(value: any, pattern: string = 'short'): any {

if (value.toString().includes('-')) {

  return moment(value).locale(this.translateService.currentLang).format('L LTS');

} else {

  if (!Number.isInteger(value)) {

    value = moment.unix(value);

  }

  return moment(value).locale(this.translateService.currentLang).format('L LTS');

}

}

then in my html , i'm using the pipe to convert :

        {{myTime | localizedMoment }}

For example if value=1672828478537 after the call of pipe , I m getting 06/01/2023 12:12:36 instead of 06/01/2022 12:12:36

Thanks for your help in advance .


问:
Read INT64 from Windows Registry
I'm having an issue reading the InstallTime value from the registry in Windows 11. I used this idea to read the value, but retCode gives me 2 (ERROR_FILE_NOT_FOUND). The value is there, and I guess there's no need for admin rights to read it. I'm using the following code snippet:

```<code>UINT64 RegGetQword(HKEY hKey, const std::wstring& subKey, const std::wstring& value)
{
    UINT64 data{};
    DWORD dataSize = sizeof(data);
    LONG retCode = ::RegGetValue(hKey, subKey.c_str(), value.c_str(), RRF_RT_REG_QWORD, nullptr, &data, &dataSize);

    if (retCode != ERROR_SUCCESS)
        throw RegistryError{ "Cannot read QWORD from registry.", retCode };
    return data;
}

int main(void)
{
    UINT64 dwInst;

    try
    {   double nTimeExpr = (double)RegGetQword(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"InstallTime");
        dwInst = _getSecondsFromEpoch(nTimeExpr)
    }
    catch (...)
    {
        dwInst = 0;
    }

    //... Do whatever needed with dwInst

    return 0;
}
</code>```

Title: Read INT64 from Windows Registry

Body:
I'm having an issue reading the InstallTime value from the registry in Windows 11. I used this idea to read the value, but retCode gives me 2 (ERROR_FILE_NOT_FOUND). The value is there, and I guess there's no need for admin rights to read it. I'm using the following code snippet:

UINT64 RegGetQword(HKEY hKey, const std::wstring& subKey, const std::wstring& value)
{
    UINT64 data{};
    DWORD dataSize = sizeof(data);
    LONG retCode = ::RegGetValue(hKey, subKey.c_str(), value.c_str(), RRF_RT_REG_QWORD, nullptr, &data, &dataSize);

    if (retCode != ERROR_SUCCESS)
        throw RegistryError{ "Cannot read QWORD from registry.", retCode };
    return data;
}

int main(void)
{
    UINT64 dwInst;

    try
    {   double nTimeExpr = (double)RegGetQword(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"InstallTime");
        dwInst = _getSecondsFromEpoch(nTimeExpr)
    }
    catch (...)
    {
        dwInst = 0;
    }

    //... Do whatever needed with dwInst

    return 0;
}


问:
This version of CLI is only compatible with Angular versions ^15.0.0, but Angular version 11.0.9 was found instead. Error
This version of CLI is only compatible with Angular versions ^15.0.0,
but Angular version 11.0.9 was found instead.

Please visit the link below to find instructions on how to update Angular.
https://update.angular.io/

I always get this error when I type ng serve.

npm install -g @angular/cli@11.0.9
npm install @angular/cli@11.0.9


问:
Validation messages don't show in Thymeleaf - kotlin - spring boot
I return the template of a form with this controller suspend method:

```<code>    @GetMapping("/checkout/customer")
    suspend fun checkoutCustomerView(model: Model): String {
        model["cart"] = shoppingCartService.getShoppingCartWithItems()
        model["checkout"] = checkoutService.getCheckout()
        return "checkout/checkoutCustomer"
    }
</code>```

I post form data with:

```<code>    @PostMapping("/checkout/customer")
    suspend fun updateCustomerData(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        model: Model,
        @Valid @ModelAttribute customerData: CheckoutCustomerData,
        bindingResult: BindingResult
    ): String {
        if (bindingResult.hasErrors()) {
            model["cart"] = shoppingCartService.getShoppingCartWithItems()
            model["checkout"] = checkoutService.getCheckout()
            return "checkout/checkoutCustomer"
        }
        model["checkout"] = checkoutWizardCookieService.updateCustomerData(customerData, request, response)
        return "redirect:/checkout/shipping"
    }
</code>```

the binding gets populated when there's an error, I can see it in debug mode.
Data is:

```<code>data class CheckoutCustomerData(
    @field:NotBlank
    val firstName: String?,
)
</code>```

and html file is:

```<code>              <form id="customer-form" th:action="@{/checkout/customer}" th:object="${checkout}"
                    method="post">
                <div class="mb-3 d-flex flex-row">
                  <input type="text" class="form-control me-3" th:field="*{firstName}" placeholder="First Name">
                  <p th:if="${#fields.hasErrors('firstName')}"
                     th:errorclass="invalid-feedback"
                     th:errors="*{firstName}" >The first name is mandatory</p>
</div>
</form>

</code>```

when I submit the form without a value for the field "firstName", I should expect some error showing under the input field, which doesn't happen, because the form is considered valid, so #fields.hasErrors() returns false.
I am not sure what I am doing wrong.
I am using Spring Boot Webflux with kotlin and coroutines. Is there some extra configuration due to the reactive nature of the project, maybe?
Thanks
Is

Body:
I return the template of a form with this controller suspend method:

    @GetMapping("/checkout/customer")
    suspend fun checkoutCustomerView(model: Model): String {
        model["cart"] = shoppingCartService.getShoppingCartWithItems()
        model["checkout"] = checkoutService.getCheckout()
        return "checkout/checkoutCustomer"
    }

I post form data with:

    @PostMapping("/checkout/customer")
    suspend fun updateCustomerData(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        model: Model,
        @Valid @ModelAttribute customerData: CheckoutCustomerData,
        bindingResult: BindingResult
    ): String {
        if (bindingResult.hasErrors()) {
            model["cart"] = shoppingCartService.getShoppingCartWithItems()
            model["checkout"] = checkoutService.getCheckout()
            return "checkout/checkoutCustomer"
        }
        model["checkout"] = checkoutWizardCookieService.updateCustomerData(customerData, request, response)
        return "redirect:/checkout/shipping"
    }

the binding gets populated when there's an error, I can see it in debug mode.
Data is:

data class CheckoutCustomerData(
    @field:NotBlank
    val firstName: String?,
)

and html file is:

              <form id="customer-form" th:action="@{/checkout/customer}" th:object="${checkout}"
                    method="post">

                  <input type="text" class="form-control me-3" th:field="*{firstName}" placeholder="First Name">

The first name is mandatory

</form>

when I submit the form without a value for the field "firstName", I should expect some error showing under the input field, which doesn't happen, because the form is considered valid, so #fields.hasErrors() returns false.
I am not sure what I am doing wrong.
I am using Spring Boot Webflux with kotlin and coroutines. Is there some extra configuration due to the reactive nature of the project, maybe?
Thanks
Is


问:
Coping Unbraco document type generating Unable to cast object of type Error
Using Umbraco 7.15 I have copied a document type, and used the original document types template but when I then try and see the generated page I get the following error

Unable to cast object of type 'Umbraco.Web.PublishedCache.XmlPublishedCache.XmlPublishedContent' to type 'Umbraco.Web.PublishedContentModels.UsnstandardPage'.

I have tried the health check and made sure the model builder is up to date.


问:
Pymavlink Type Mask ValueError
```<code>from pymavlink import mavutil

# Start a connection listening to a UDP port
the_connection = mavutil.mavlink_connection('udpin:localhost:14551')

# Wait for the first heartbeat
#   This sets the system and component ID of remote system for the link
the_connection.wait_heartbeat()
print("Heartbeat from system (system %u component %u)" %
      (the_connection.target_system, the_connection.target_component))

the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                         the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(0b110111111000), 70, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0))
</code>```

I have a function like below to move the drone. And the function works.(The drone goes to a designated area.)

```<code>the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                         the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(0b110111111000), 70, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0))
</code>```

there is a variable named type_mask in this function and the value of the variable in the function is int(0b11011111111000)

I want the user to enter the values from a bash interface and control the drone. I changed my function like this.

```<code>the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                          the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(type_mask), float(x), float(y), float(z), 0, 0, 0, 0, 0, 0, int(yaw),int(yaw_rate)))
</code>```

But when I get the type_mask value from the user in the interface using input(), I get a ValueError. I am aware of this because there is "b" in the type_mask.

How can I run the function by getting the type_mask value from the user with input().

Thank you kind regards..

Title: Pymavlink Type Mask ValueError

Body:
from pymavlink import mavutil

# Start a connection listening to a UDP port
the_connection = mavutil.mavlink_connection('udpin:localhost:14551')

# Wait for the first heartbeat
#   This sets the system and component ID of remote system for the link
the_connection.wait_heartbeat()
print("Heartbeat from system (system %u component %u)" %
      (the_connection.target_system, the_connection.target_component))

the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                         the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(0b110111111000), 70, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0))

I have a function like below to move the drone. And the function works.(The drone goes to a designated area.)

the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                         the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(0b110111111000), 70, 0, -10, 0, 0, 0, 0, 0, 0, 0, 0))

there is a variable named type_mask in this function and the value of the variable in the function is int(0b11011111111000)

I want the user to enter the values from a bash interface and control the drone. I changed my function like this.

the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(10, the_connection.target_system,
                          the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED, int(type_mask), float(x), float(y), float(z), 0, 0, 0, 0, 0, 0, int(yaw),int(yaw_rate)))

But when I get the type_mask value from the user in the interface using input(), I get a ValueError. I am aware of this because there is "b" in the type_mask.

How can I run the function by getting the type_mask value from the user with input().

Thank you kind regards..


问:
Neo4j Desktop in a disconnected environment takes a lot of time to start?
I installed Neo4j Desktop client on disconnected windows environment (no internet),when starting the programmer it takes a lot of time (more then 30m) to get ready ,actually it get stacked on the " Preparing application " step :

I'm looking for any way to tell Neo4j to skip checking for updates ?

The installation is on aws Appstream Stacks ,the stack has connection to my VPC  but  not to the internet :

This is a part of the log where it get stack requesting for a specific Url :

log file


问:
tailwind-elements - adding custom css
I am using this carousel:

https://tailwind-elements.com/docs/standard/components/carousel/

I don't know how to add custom CSS, instead default for bellow div:

```<code><div id="carouselExampleCaptions" class="carousel slide relative" data-bs-ride="carousel">

 <div class="carousel-indicators absolute right-0 bottom-0 left-0 flex justify-center p-0 mb-4">
 ...
</code>```

I should copy carousel-indicators to my CSS, and change it?
How practice is the best?

Title: tailwind-elements - adding custom css

Body:
I am using this carousel:

https://tailwind-elements.com/docs/standard/components/carousel/

I don't know how to add custom CSS, instead default for bellow div:

 ...

I should copy carousel-indicators to my CSS, and change it?
How practice is the best?


问:
VS Code: Connect to code server within docker container
Hi probably it feels odd to you, but for a project I need to setup VS Code Server in a docker container to setup a DevVM-like solution, although I know docker is not intended to be used like this.

To do so, I basically use this docker image: https://hub.docker.com/r/linuxserver/code-server

After starting the container I can access the containerized VS Code via the browser. But my team would prefer to access it directly with their locally installed VS Code.

Usually you can do so via the Remote Tunnel feature, that will create a tunnel through https://vscode.dev/tunnel/.

We would rather like not to do this for security reasons. That's why I am wondering if there are any solutions to connect directly to the VS Code Server from VS Code without the need to tunnel the connection over the internet, e.g. by giving VS Code the IP and port to the dockerized VS Code Server.

Thanks a lot for all input in advance!


问:
Cmake + Github CI/CD: Transferring the project version from Github Actions runner to Cmake
I want to make something like this but with GitHub Actions runner:

Number of CI build goes to CMake and it generates .h file

All I find is this:

searching of hash in git files

And it work, but it's terrible.

How can I use value ${{github.run_number}} in runner or something else for my purposes?

I would be grateful for any resources with a detailed explanation of Github Actions CI/CD effective usage.


问:
Join wide table from different starting dates
Hey guys I have 2 DBs:

BaseDB:

"id", "Main_event_date"

```<code>*id*  *Main_event_date*
1       01/01/2017
2       01/07/2018
3       01/11/2017
</code>```

DB_2

"id","event_date"

```<code>*id*   *event_date*
1       01/02/2017
1       19/12/2017
1       19/01/2018
2       01/10/2018
2       10/01/2019
</code>```

DB_2 might be duplicated in "id": every time an "id" has an event, I have a new row with a new "event_date".

I reshaped the DB_2 from long to wide using "reshape", so that now I have:
DB_2_wide

"id", "event_date0", "event_date1"...."event_date100".

I would like to join the BaseDB with DB_2_Wide considering only the first 30 events after the main_event_date for every "id" having a final table of the type:

Final_Table

id, t1, ... t30

```<code>*id* *t1* *t2* *t3*   ..... *t30*
1      x   NA    NA
2      NA  NA    x
3      NA  NA    NA

Considering also that t1 for 1 is Feb2017,
                      t1 for 2 is August 2018
                      t1 for 3 is December 2017

</code>```

Not sure how to do this because simply using left_join (or merge) I would get a table like:

"id", "event_date0", "event_date1"...."event_date100",

hence for every id I would also get a column for events before the main_event_date, which would be NA.

Not sure this is clear so let me know if have any questions.

Body:
Hey guys I have 2 DBs:

BaseDB:

"id", "Main_event_date"

*id*  *Main_event_date*
1       01/01/2017
2       01/07/2018
3       01/11/2017

DB_2

"id","event_date"

*id*   *event_date*
1       01/02/2017
1       19/12/2017
1       19/01/2018
2       01/10/2018
2       10/01/2019

DB_2 might be duplicated in "id": every time an "id" has an event, I have a new row with a new "event_date".

I reshaped the DB_2 from long to wide using "reshape", so that now I have:
DB_2_wide

"id", "event_date0", "event_date1"...."event_date100".

I would like to join the BaseDB with DB_2_Wide considering only the first 30 events after the main_event_date for every "id" having a final table of the type:

Final_Table

id, t1, ... t30

*id* *t1* *t2* *t3*   ..... *t30*
1      x   NA    NA
2      NA  NA    x
3      NA  NA    NA

Considering also that t1 for 1 is Feb2017,
                      t1 for 2 is August 2018
                      t1 for 3 is December 2017

Not sure how to do this because simply using left_join (or merge) I would get a table like:

"id", "event_date0", "event_date1"...."event_date100",

hence for every id I would also get a column for events before the main_event_date, which would be NA.

Not sure this is clear so let me know if have any questions.


问:
What are the "default packages" in a python environment before using pip install?
As a newbe in Python I have used pip install before I started using any virtual environments.
So now I think that I have to remove some of the packages listed by pip list -v that should not be there by default. But what should be there as default?


问:
redirect to app using an external payment service
I have created a dot net maui app. I'm using an external payment service called payfast.

When I want to make a transaction it directs me to a different page on the browser where I make my transactions. When the transactions are complete, I need to redirect back to the maui app.

The issue is that the service does not allow maui's url for example "myapp://". I get an error 400 bad request. "return_url: The return url format is invalid"

I tried to let it redirect to my API which is successful, but then I can't redirect the API back to my app

I have tried both return RedirectToPage("myapp://") and Request.HttpContext.Response.Redirect("myapp://") but it does not redirect back to my app