问:
Laravel eloquent query with multiple child relations
I am working on a query but can't find the solution to this one.

The structure i have at the moment is:

A project has 1 machine, but a machine can belong to multiple projects.
A machine can have multiple issues.

Now i want to get all projects with the issues created after the project got created.

The query that i have at the moment, but doesn't work:

```<code>        $allProjects = Project::with(['machine',
        'machine.issues' => function ($query) {
                $query->where('created_at', '>=', 'project.created_at');
            }
        ])
        ->orderBy('id')
        ->get();
</code>```

I am not getting the issues at all by using this query, when i switch the operator to: < then i get all the issues even the ones after project.created_at

答:
You can have a pivot do most of the work for you. I tried reproducing your problem statement as below.

 <?php

 class Project extends Model
 {
    use HasFactory;

    public function machine()
    {
       return $this->hasOneThrough(Machine::class, MachineProject::class, 'machine_id', 'id', 'id', 'project_id');
    }

    public function issues()
    {
       return $this->hasManyThrough(Issue::class, Machine::class, 'id', 'machine_id')->whereDate('issues.created_at', '<=', $this->created_at);
    }
}

class Machine extends Model
{
    use HasFactory;

    public $with = ['issues'];

    public function projects()
    {
        return $this->belongsToMany(Project::class);
    }

    public function issues()
    {
        return $this->hasMany(Issue::class);
    }
}

class Issue extends Model
{
    use HasFactory;

    public function machine()
    {
        return $this->belongsTo(Machine::class);
    }
}

class MachineProject extends Pivot
{
    //
}
```
<p>To retrieve the Project with issues, you just do</p>
<pre class="lang-php prettyprint-override"><code>$allProjects = Project::with(['machine' => function ($machine) {
    $machine->with('issues');
}])->get();
</code>```

Body:
I am working on a query but can't find the solution to this one.

The structure i have at the moment is:

A project has 1 machine, but a machine can belong to multiple projects.
A machine can have multiple issues.

Now i want to get all projects with the issues created after the project got created.

The query that i have at the moment, but doesn't work:

        $allProjects = Project::with(['machine',
        'machine.issues' => function ($query) {
                $query->where('created_at', '>=', 'project.created_at');
            }
        ])
        ->orderBy('id')
        ->get();

I am not getting the issues at all by using this query, when i switch the operator to: < then i get all the issues even the ones after project.created_at

Body:
You can have a pivot do most of the work for you. I tried reproducing your problem statement as below.

 <?php

 class Project extends Model
 {
    use HasFactory;

    public function machine()
    {
       return $this->hasOneThrough(Machine::class, MachineProject::class, 'machine_id', 'id', 'id', 'project_id');
    }

    public function issues()
    {
       return $this->hasManyThrough(Issue::class, Machine::class, 'id', 'machine_id')->whereDate('issues.created_at', '<=', $this->created_at);
    }
}

class Machine extends Model
{
    use HasFactory;

    public $with = ['issues'];

    public function projects()
    {
        return $this->belongsToMany(Project::class);
    }

    public function issues()
    {
        return $this->hasMany(Issue::class);
    }
}

class Issue extends Model
{
    use HasFactory;

    public function machine()
    {
        return $this->belongsTo(Machine::class);
    }
}

class MachineProject extends Pivot
{
    //
}

To retrieve the Project with issues, you just do

$allProjects = Project::with(['machine' => function ($machine) {
    $machine->with('issues');
}])->get();


来源: stackexchange

问:
Material - no provider for DateAdapter in lazily loaded third party module
In my applicaiton I'm using a custom DateAdapter based on dayJs.

This is the definition of the module that provides it:

@NgModule({
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: MAT_DAYJS_DATE_FORMATS },
    { provide: DateAdapter, useClass: DayJsDateAdapter, deps: [MAT_DATE_LOCALE]}
  ],
})
export class MatDayjsDateModule {}
```
<p>which is imported like this in my application bootstrap module:</p>
<pre class="lang-js prettyprint-override"><code>const MODULES_TO_EXPORT = [
    MatDatepickerModule,
    MatDayjsDateModule,
];

const formats = { parse: { ... }, display: { ... } }

@NgModule({
    imports: [...MODULES_TO_EXPORT],
    declarations: [ ],
    providers: [{ provide: MAT_DATE_LOCALE, useValue: 'it-IT' }, { provide: MAT_DATE_FORMATS, useValue: formats }]
})
export class AppModule { }
</code>```

This works without issues for eager and lazy modules, as long as they are defined in the application, but when i try to transform a lazy module into a library and load it into the application like this:

const appRoutes: Routes = [
    { path: "", redirectTo: "/pages/dashboard", pathMatch: "full" },
    {
        path: "pages", component: PagesComponent, children:
            [
                ...
                { path: "adm", loadChildren: () => import('@template/admin-module').then(m => m.AdmModule) },
            ]
    }
];
```

As soon as i navigate to a component declared by that module that has Date Inputs i receive the usual No provider found for DateAdapter. I have no problems with any other service injections inside this kind of modules, only with the DateAdapter.

Any idea?
Thanks for your time!

答:
with a lazy-loaded module, you need to register the provider at the component level to get a new instance of the service, and this is a requirement for DateAdapter.

this is an example:

```<code>@Component({
 /* . . . */
 providers: [
   { provide: MAT_DATE_FORMATS, useValue: MAT_DAYJS_DATE_FORMATS },
   { provide: DateAdapter, useClass: DayJsDateAdapter, deps: [MAT_DATE_LOCALE]}
 ]
})
</code>```

I've created a working example on Stackblitz with a custom Format and a custom locale

ContentLicense: CC BY-SA 4.0

Body:
In my applicaiton I'm using a custom DateAdapter based on dayJs.

This is the definition of the module that provides it:

@NgModule({
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: MAT_DAYJS_DATE_FORMATS },
    { provide: DateAdapter, useClass: DayJsDateAdapter, deps: [MAT_DATE_LOCALE]}
  ],
})
export class MatDayjsDateModule {}

which is imported like this in my application bootstrap module:

const MODULES_TO_EXPORT = [
    MatDatepickerModule,
    MatDayjsDateModule,
];

const formats = { parse: { ... }, display: { ... } }

@NgModule({
    imports: [...MODULES_TO_EXPORT],
    declarations: [ ],
    providers: [{ provide: MAT_DATE_LOCALE, useValue: 'it-IT' }, { provide: MAT_DATE_FORMATS, useValue: formats }]
})
export class AppModule { }

This works without issues for eager and lazy modules, as long as they are defined in the application, but when i try to transform a lazy module into a library and load it into the application like this:

const appRoutes: Routes = [
    { path: "", redirectTo: "/pages/dashboard", pathMatch: "full" },
    {
        path: "pages", component: PagesComponent, children:
            [
                ...
                { path: "adm", loadChildren: () => import('@template/admin-module').then(m => m.AdmModule) },
            ]
    }
];

As soon as i navigate to a component declared by that module that has Date Inputs i receive the usual No provider found for DateAdapter. I have no problems with any other service injections inside this kind of modules, only with the DateAdapter.

Any idea?
Thanks for your time!

Body:
with a lazy-loaded module, you need to register the provider at the component level to get a new instance of the service, and this is a requirement for DateAdapter.

this is an example:

@Component({
 /* . . . */
 providers: [
   { provide: MAT_DATE_FORMATS, useValue: MAT_DAYJS_DATE_FORMATS },
   { provide: DateAdapter, useClass: DayJsDateAdapter, deps: [MAT_DATE_LOCALE]}
 ]
})

I've created a working example on Stackblitz with a custom Format and a custom locale


问:
Dynamically Changing jQuery UI dialog box Button Text
I am using  jQuery UI Dialog box for ajax form submit. I want change the text of my
save button to wait , when user click on it and back to Save when ajax call complete. pls
help me</p>

答:
If it helps anyone: full implementation with example (PS: I borrowed getDialogButton() from another post on this site but can't remember link).</p>

```<code>//-> Change to Loading Notice:
setButton('.settingsDialog', 'Save', 'Saving...', false);
setTimeout(function() { setButton('.settingsDialog', 'Saving...', 'Save', true); }, 800 );},

//Select the Dialog Buttons
function getDialogButton( dialog_selector, button_name ) {
  var buttons = $( dialog_selector + ' .ui-dialog-buttonpane button' );
  for ( var i = 0; i < buttons.length; ++i ) {
     var jButton = $( buttons[i] );
     if ( jButton.text() == button_name )
     {
         return jButton;
     }
  }
  return null;
}

//Button Controller for AJAX Loading:
function setButton(sDialogClass, sButtonName, sNewButtonName, bEnabled){
    var btn = getDialogButton(sDialogClass, sButtonName);
    btn.find('.ui-button-text').html(sNewButtonName);

    if (bEnabled) {
        btn.removeAttr('disabled', 'true');
        btn.removeClass( 'ui-state-disabled' );
    } else {
        btn.attr('disabled', 'true');
        btn.addClass( 'ui-state-disabled' );
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If it helps anyone: full implementation with example (PS: I borrowed getDialogButton() from another post on this site but can't remember link).

//-> Change to Loading Notice:
setButton('.settingsDialog', 'Save', 'Saving...', false);
setTimeout(function() { setButton('.settingsDialog', 'Saving...', 'Save', true); }, 800 );},

//Select the Dialog Buttons
function getDialogButton( dialog_selector, button_name ) {
  var buttons = $( dialog_selector + ' .ui-dialog-buttonpane button' );
  for ( var i = 0; i < buttons.length; ++i ) {
     var jButton = $( buttons[i] );
     if ( jButton.text() == button_name )
     {
         return jButton;
     }
  }
  return null;
}

//Button Controller for AJAX Loading:
function setButton(sDialogClass, sButtonName, sNewButtonName, bEnabled){
    var btn = getDialogButton(sDialogClass, sButtonName);
    btn.find('.ui-button-text').html(sNewButtonName);

    if (bEnabled) {
        btn.removeAttr('disabled', 'true');
        btn.removeClass( 'ui-state-disabled' );
    } else {
        btn.attr('disabled', 'true');
        btn.addClass( 'ui-state-disabled' );
    }
}

ContentLicense: CC BY-SA 3.0


问:
Not able to launch Flutter app on Android device
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

```<code>Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

```<code>export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home
</code>```

答:
Set the JAVA_HOME environment variable to the JRE for Android Studio. For example:

C:\Program Files\Android\Android Studio\jre

Then invalidate and restart Android Studio before trying again.

Body:
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home


问:
@singledispatchmethod is not working correctly
@singledispatchmethod is not working correctly. I have this code

```<code>class Stream:
    @singledispatchmethod
    def subscribe(self, arg_1, arg_2):
        pass

    @subscribe.register
    def _(self, msg_type: type, action: Callable):
        pass

    @subscribe.register
    def _(self, msg_type: type, context: bool):
        pass

def aaa() -> None:
    pass

@pytest.mark.asyncio
async def test_can_subscribe_to_specific_event_types():
    stream = Stream()
    stream.subscribe(type(str), aaa)
</code>```

I want to call an overload of a method that takes

```<code>def _(self, msg_type: type, action: Callable):
</code>```

but python calls

```<code>def _(self, msg_type: type, context: bool):
</code>```

What am I doing wrong?

答:
From the docs

When defining a function using @singledispatchmethod, note that the
dispatch happens on the type of the first non-self or non-cls
argument

In your case it is msg_type.

Body:
@singledispatchmethod is not working correctly. I have this code

class Stream:
    @singledispatchmethod
    def subscribe(self, arg_1, arg_2):
        pass

    @subscribe.register
    def _(self, msg_type: type, action: Callable):
        pass

    @subscribe.register
    def _(self, msg_type: type, context: bool):
        pass

def aaa() -> None:
    pass

@pytest.mark.asyncio
async def test_can_subscribe_to_specific_event_types():
    stream = Stream()
    stream.subscribe(type(str), aaa)

I want to call an overload of a method that takes

def _(self, msg_type: type, action: Callable):

but python calls

def _(self, msg_type: type, context: bool):

What am I doing wrong?


问:
How to handle labels in a scripting language I'm writing?
So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.

```<code>:main
    dostuff
    otherlabel

:otherlabel
    dostuff
</code>```

Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?

At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.

I've thought of a few ways to do this:

First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.

Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.

I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.

答:
You could use "backpatching", although it sounds like that's what you've tried already; and it could be consstrued as a complex structure.

When you encounter a call to an undefined label, you emit the jump with a blank address field (probably into a buffer, otherwise this becomes the same as "multipass" if you have to re-read the file to patch it); and you also store a pointer to the blank field in a "patch-up" list in the dictionary. When you encounter the label definition, you fill-in all the blanks in the list, and proceed normally.

Body:
So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.

:main
    dostuff
    otherlabel

:otherlabel
    dostuff

Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?

At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.

I've thought of a few ways to do this:

First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.

Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.

I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.


问:
Flexible Search Issue SAP Hybris
I have a problem with a Flexible Query. This is my query:

```<code>Select
{pp.productCode} as 'Code',
{p.descriptionCics} as 'Desc CISC',
{bs.uid} as 'Store',
{evo.code} as 'Status',
{p.department} as 'Department',
{pca.name} as 'Category',
{p.grm} as 'GRM',
{p.buyerCode} as 'Code Buyer',
{p.buyerids} as 'Buyer',
{ps.planogramCode} as 'Code Planogram',
{pca.categoryCode} as 'Category Planogram',
{s.puvmBlock} as 'Blocked',
(CASE WHEN ({p.productDetailTypeList} is not null )THEN 'YES' else
'NO' END) as 'IMAGE'
from
{
Product as p
JOIN PlanogramProducts as pp on {p.code} = {pp.productCode}
JOIN StockLevel as s on {pp.productCode} = {s.productCode}
JOIN EnumerationValue as evo on {p.status} = {evo.pk}
JOIN PlanogramCategory as pc on {pp.planogramCode} =
 {pc.planogramCode}
JOIN PlamnogramCategoryAnag as pca on {pc.categoryCode}=
{pca.categoryCode}
JOIN BaseStore as bs JOIN PlanogramStore as ps on {bs.storeRef} =
{ps.storeRef} AND {bs.bramchOffice} = {ps.branchOffice}
}
WHERE 1=1
</code>```

and this my error when I execute it:

Can someone help me? Thanks a lot.

答:
Your statement contains errors. You join basestore with planogramStore. But neither planogram store, nor basestore is joined with any other part of your query. You need to join basestore or planogramstore with one of the other tables.

Now you have 2 detached parts in your from statement, which is why you are getting errors

```<code>Product as p
JOIN PlanogramProducts as pp on {p.code} = {pp.productCode}
JOIN StockLevel as s on {pp.productCode} = {s.productCode}
JOIN EnumerationValue as evo on {p.status} = {evo.pk}
JOIN PlanogramCategory as pc on {pp.planogramCode} =
 {pc.planogramCode}
JOIN PlamnogramCategoryAnag as pca on {pc.categoryCode}=
{pca.categoryCode}
</code>```

and

```<code>JOIN BaseStore as bs JOIN PlanogramStore as ps on {bs.storeRef} =
{ps.storeRef} AND {bs.bramchOffice} = {ps.branchOffice}
</code>```

you need to have a join between these 2 parts to get the correct data

Title: Flexible Search Issue SAP Hybris

Body:
I have a problem with a Flexible Query. This is my query:

Select
{pp.productCode} as 'Code',
{p.descriptionCics} as 'Desc CISC',
{bs.uid} as 'Store',
{evo.code} as 'Status',
{p.department} as 'Department',
{pca.name} as 'Category',
{p.grm} as 'GRM',
{p.buyerCode} as 'Code Buyer',
{p.buyerids} as 'Buyer',
{ps.planogramCode} as 'Code Planogram',
{pca.categoryCode} as 'Category Planogram',
{s.puvmBlock} as 'Blocked',
(CASE WHEN ({p.productDetailTypeList} is not null )THEN 'YES' else
'NO' END) as 'IMAGE'
from
{
Product as p
JOIN PlanogramProducts as pp on {p.code} = {pp.productCode}
JOIN StockLevel as s on {pp.productCode} = {s.productCode}
JOIN EnumerationValue as evo on {p.status} = {evo.pk}
JOIN PlanogramCategory as pc on {pp.planogramCode} =
 {pc.planogramCode}
JOIN PlamnogramCategoryAnag as pca on {pc.categoryCode}=
{pca.categoryCode}
JOIN BaseStore as bs JOIN PlanogramStore as ps on {bs.storeRef} =
{ps.storeRef} AND {bs.bramchOffice} = {ps.branchOffice}
}
WHERE 1=1

and this my error when I execute it:

Can someone help me? Thanks a lot.

Body:
Your statement contains errors. You join basestore with planogramStore. But neither planogram store, nor basestore is joined with any other part of your query. You need to join basestore or planogramstore with one of the other tables.

Now you have 2 detached parts in your from statement, which is why you are getting errors

Product as p
JOIN PlanogramProducts as pp on {p.code} = {pp.productCode}
JOIN StockLevel as s on {pp.productCode} = {s.productCode}
JOIN EnumerationValue as evo on {p.status} = {evo.pk}
JOIN PlanogramCategory as pc on {pp.planogramCode} =
 {pc.planogramCode}
JOIN PlamnogramCategoryAnag as pca on {pc.categoryCode}=
{pca.categoryCode}

and

JOIN BaseStore as bs JOIN PlanogramStore as ps on {bs.storeRef} =
{ps.storeRef} AND {bs.bramchOffice} = {ps.branchOffice}

you need to have a join between these 2 parts to get the correct data


问:
What does socket.htons(proto) = 43200 means?
While using socket.htons(proto) in my project it gives value of 43200. What does that mean?
I know socket.htons(0x0800) = 8 which means IPv4. If 8 is for IPv4, what does 43200 means?</p>

答:
43200 is A8C0 in hex. Since you're doing htons, and most hosts these days are little-endian, the bytes on the wire are probably c0, a8. Now in decimal, that is 192, 168, which is suspiciously like the first two bytes of a typical RFC1918 IP address, so my hunch is that you are interpreting the wrong bytes of some packet.

For example, here is someone who managed to get the same value by mistake.


问:
Encrypt Django project
I have a project (django) running in our office in server. There are some people who have access in server. But I want to do something so that other people (who have access in server) can not read, or write, or edit, or do anything in my project (django)'s source code.

Server is running using Ubuntu OS.

答:
You should take a look at Linux file permissions.

Grant read / write / execute access to the user that run Django app.

Maybe create a group, where this user and you are, and give the group read permissions.

Like that everyone else will not be able to Read / Write / Ex ecute files in the project folder.

This should give these two commands:

(create user / group before and maybe backup before anything if it's a prod server)

```<code>sudo chown -R django:django_group /your/folder
sudo chmod -R 750 /your/folder
</code>```

Title: Encrypt Django project

Body:
You should take a look at Linux file permissions.

Grant read / write / execute access to the user that run Django app.

Maybe create a group, where this user and you are, and give the group read permissions.

Like that everyone else will not be able to Read / Write / Ex ecute files in the project folder.

This should give these two commands:

(create user / group before and maybe backup before anything if it's a prod server)

sudo chown -R django:django_group /your/folder
sudo chmod -R 750 /your/folder


问:
Is it still loose coupling if we use @qualifier
we use interface for autowiring service into controller

this is for loose coupling , coz the interface can hold object of any of its implementations. so no need to write the implementation name and create tight coupling.

however when we have more than one implementations for an interface, we write the @qualifier .

my question is if we have to write qualifier to tell which implementation needs to be injected, then should we still call it loose coupling??

```<code>class ServiceInterface {
interfaceMethod();
}

implementation 1:
    @component("service1")
    class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
    }
implementation 2:
    @component("service2")
    class ServiceImpl2 implements ServiceInterface {
    interfaceMethod(){

    }

   now  only instead of directly creating Object of ServiceImpl1() using new
   ServiceImpl1 obj = new ServiceImpl1();
    we write in
    class Controller {
    @autowired
    @qualifier("service1")
    ServiceInterface se;

    sc.interfaceMethod();

    }
</code>```

答:
Partially yes, because the component that uses the injected qualified bean still didn't create it or handle its lifecycle.

But indeed using @Qualifier creates some sort of coupling. If you want to avoid this, consider making one of your ServiceInterface beans the primary implementation for the interface annotating its class with @Primary as follows:

@Component
@Primary
class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
}
```

With this, every time you need a ServiceInterface implementation but you don't actually specify which one you want (using @Qualifier) the primary one is injected by Spring.

Body:
we use interface for autowiring service into controller

this is for loose coupling , coz the interface can hold object of any of its implementations. so no need to write the implementation name and create tight coupling.

however when we have more than one implementations for an interface, we write the @qualifier .

my question is if we have to write qualifier to tell which implementation needs to be injected, then should we still call it loose coupling??

class ServiceInterface {
interfaceMethod();
}

implementation 1:
    @component("service1")
    class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
    }
implementation 2:
    @component("service2")
    class ServiceImpl2 implements ServiceInterface {
    interfaceMethod(){

    }

   now  only instead of directly creating Object of ServiceImpl1() using new
   ServiceImpl1 obj = new ServiceImpl1();
    we write in
    class Controller {
    @autowired
    @qualifier("service1")
    ServiceInterface se;

    sc.interfaceMethod();

    }

Body:
Partially yes, because the component that uses the injected qualified bean still didn't create it or handle its lifecycle.

But indeed using @Qualifier creates some sort of coupling. If you want to avoid this, consider making one of your ServiceInterface beans the primary implementation for the interface annotating its class with @Primary as follows:

@Component
@Primary
class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){

    }
}

With this, every time you need a ServiceInterface implementation but you don't actually specify which one you want (using @Qualifier) the primary one is injected by Spring.


问:
Cant output answer buttons and sort them in my project
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?</p>
```<code>
import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (
    <div className="App">
   <h1>{quiz.question}</h1>
   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }
    </div>

  );
}

export default App;
</code>```

答:
You can't set state and use it immediately, you need to await the set state changes.
You can handle that properly by adding a useEffect to be executed every time quiz changes
you code will look like that

  useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    if (quiz.length > 0)
      setAnswer([...quiz.incorrect_answers, quiz.correct_answer]);
  }, [quiz]);```
</div>
</div>
</p>
<p>OR You can use .then function to handle that in the same useEffect</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
      }).then(()=>setAnswer([...quiz.incorrect_answers, quiz.correct_answer]))

      .catch((err) => {
        console.log(err);
      });
  }, []);</code>```

Body:
im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{

      setQuiz(res.data.results[0])

       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })

  },[])

  return (

{quiz.question}

   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)

   }

  );
}

export default App;

Body:
You can't set state and use it immediately, you need to await the set state changes.
You can handle that properly by adding a useEffect to be executed every time quiz changes
you code will look like that

  useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    if (quiz.length > 0)
      setAnswer([...quiz.incorrect_answers, quiz.correct_answer]);
  }, [quiz]);

OR You can use .then function to handle that in the same useEffect

useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
      }).then(()=>setAnswer([...quiz.incorrect_answers, quiz.correct_answer]))

      .catch((err) => {
        console.log(err);
      });
  }, []);


问:
python dictionary sorting oddly (want non-alphabetical)
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

```<code>def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)
</code>```

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

```<code>for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '
</code>```

答: Python dictionaries order their keys based on its hash, which will make it seem random. I recommend using OrderedDict to get your keys in order.</p>

Body:
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '


问:
Can't install packages in docker container using Dockerfile
I'd like to install a package in a docker image, via a Dockerfile.

docker-compose.yml:

version: "3.5"
services:
  transmission:
    build:
      context: .
      dockerfile: Dockerfile
    image: ghcr.io/linuxserver/transmission
    container_name: transmission
    environment:
      - PUID=1000
      - PGID=1000
    volumes:
      - ./config/public:/config
      - /data:/data
    ports:
      - 60020:60020
      - 60010:60010
      - 60010:60010/udp
    restart: unless-stopped
    network_mode: host
```
<p>Dockerfile:</p>
```RUN apk update
RUN apk add --no-cache flac
```

In the Dockerfile, I specify that I'd like to install the flac package.
After that I run docker-compose up -d, and sudo docker exec -it transmission bash to check whether it's present, but it's not.

What am I doing wrong?

答:
Your Dockerfile isn't valid (if you've posted the whole file). You've also specified both build: and image: tags in your docker-compose file which is used when you want to build an image and give it a tag when built.

What I think you're trying to accomplish is to add flac to the transmission image. To do that, you'd create a Dockerfile like this

```<code>FROM ghcr.io/linuxserver/transmission
RUN apk update
RUN apk add --no-cache flac
</code>```

Then in your docker-compose file, you remove the image specification like this

```<code>version: "3.5"
services:
  transmission:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: transmission
    environment:
      - PUID=1000
      - PGID=1000
    volumes:
      - ./config/public:/config
      - /data:/data
    ports:
      - 60020:60020
      - 60010:60010
      - 60010:60010/udp
    restart: unless-stopped
    network_mode: host
</code>```

Body:
I'd like to install a package in a docker image, via a Dockerfile.

docker-compose.yml:

version: "3.5"
services:
  transmission:
    build:
      context: .
      dockerfile: Dockerfile
    image: ghcr.io/linuxserver/transmission
    container_name: transmission
    environment:
      - PUID=1000
      - PGID=1000
    volumes:
      - ./config/public:/config
      - /data:/data
    ports:
      - 60020:60020
      - 60010:60010
      - 60010:60010/udp
    restart: unless-stopped
    network_mode: host

Dockerfile:

RUN apk update
RUN apk add --no-cache flac

In the Dockerfile, I specify that I'd like to install the flac package.
After that I run docker-compose up -d, and sudo docker exec -it transmission bash to check whether it's present, but it's not.

What am I doing wrong?

Body:
Your Dockerfile isn't valid (if you've posted the whole file). You've also specified both build: and image: tags in your docker-compose file which is used when you want to build an image and give it a tag when built.

What I think you're trying to accomplish is to add flac to the transmission image. To do that, you'd create a Dockerfile like this

FROM ghcr.io/linuxserver/transmission
RUN apk update
RUN apk add --no-cache flac

Then in your docker-compose file, you remove the image specification like this

version: "3.5"
services:
  transmission:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: transmission
    environment:
      - PUID=1000
      - PGID=1000
    volumes:
      - ./config/public:/config
      - /data:/data
    ports:
      - 60020:60020
      - 60010:60010
      - 60010:60010/udp
    restart: unless-stopped
    network_mode: host


问:
How to get array of random doubles in C?
I want to generate an array with random doubles but get an "Segmentation Fault" instead of the result. When I use the same code but replace double with float, everything works. How is that?
Code below works:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int N = 1048576;

int main(void) {
    srand(time(NULL));

    float B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (float)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}
</code>```

And code below gives me segmentation fault

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int N = 1048576;

int main(void) {
    srand(time(NULL));

    double B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}
</code>```

I'm a noob in C, so any detailed explanation would be appreciated.

答:
The array has automatic storage duration and is too big for allocation with the automatic storage duration.

Either declare it in the file scope or with the storage specifier static within the function main to make it with static storage duration. Or allocate the array dynamically.

Body:
I want to generate an array with random doubles but get an "Segmentation Fault" instead of the result. When I use the same code but replace double with float, everything works. How is that?
Code below works:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int N = 1048576;

int main(void) {
    srand(time(NULL));

    float B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (float)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

And code below gives me segmentation fault

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int N = 1048576;

int main(void) {
    srand(time(NULL));

    double B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

I'm a noob in C, so any detailed explanation would be appreciated.


问:
How do I run several codes at once?
I work with OLAP Cubes and have created code on several occasions for different purposes but now I would like to combine several functions, how do I succeed with that?

This is what I need help putting together. I am a real beginner and have solved most things through google before but now I cant find anything that I understand or that helps me.

1)

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$5" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Casino].[Casino].[Casino]").CurrentPageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$3" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Month Number].[Month Number]").CurrentPageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$2" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Year].[Year]").CurrentPageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

答:
you can combine all the ones into a single code and use if-statements for the differences:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim fields As String
Dim pageName as String
If Target.Address = "$A$5" Then fields="[Casino].[Casino].[Casino]": pageName = "[Casino].[Casino].&["
If Target.Address = "$A$3" Then fields="[Date].[Month Number].[Month Number]": pageName = "[Date].[Month Number].&["
If Target.Address = "$A$2" Then fields="[Date].[Year].[Year]": pageName = "[Date].[Year].&["
If fields = "" Then Exit Sub
On Error Resume Next
Application.ScreenUpdating = False
Dim pt As PivotTable
Dim ws As Worksheet
For Each ws In Worksheets
For Each pt In ws.PivotTables
pt.PivotFields(fields).CurrentPageName = pageName & Format(Target.Value, "") & "]"
pt.PivotFields
Next pt
Next ws
GoTo Sluta
Fel:
MsgBox "Något gick fel :("
Sluta:
Application.ScreenUpdating = True

End Sub
</code>```

Also adding variables fields and pageName to simplify.

Title: How do I run several codes at once?

Body:
I work with OLAP Cubes and have created code on several occasions for different purposes but now I would like to combine several functions, how do I succeed with that?

This is what I need help putting together. I am a real beginner and have solved most things through google before but now I cant find anything that I understand or that helps me.

1)

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$5" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Casino].[Casino].[Casino]").CurrentPageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$3" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Month Number].[Month Number]").CurrentPageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$2" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Year].[Year]").CurrentPageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Body:
you can combine all the ones into a single code and use if-statements for the differences:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim fields As String
Dim pageName as String
If Target.Address = "$A$5" Then fields="[Casino].[Casino].[Casino]": pageName = "[Casino].[Casino].&["
If Target.Address = "$A$3" Then fields="[Date].[Month Number].[Month Number]": pageName = "[Date].[Month Number].&["
If Target.Address = "$A$2" Then fields="[Date].[Year].[Year]": pageName = "[Date].[Year].&["
If fields = "" Then Exit Sub
On Error Resume Next
Application.ScreenUpdating = False
Dim pt As PivotTable
Dim ws As Worksheet
For Each ws In Worksheets
For Each pt In ws.PivotTables
pt.PivotFields(fields).CurrentPageName = pageName & Format(Target.Value, "") & "]"
pt.PivotFields
Next pt
Next ws
GoTo Sluta
Fel:
MsgBox "Något gick fel :("
Sluta:
Application.ScreenUpdating = True

End Sub

Also adding variables fields and pageName to simplify.


问:
Sitecore Could not create controller : Sitecore.Mvc.Diagnostics.ControllerCreationException
I am using Sitecore v9

I have a two base class for all my controllers as follows

```<code>public abstract SiteCoreController : ControllerBase, IController, IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IAsyncManagerContainer

public abstract class ControllerBase : IController
</code>```

All controllers use something like

```<code>public class MyPageController : SiteCoreController
</code>```

In my log files I get heaps of errors

Sitecore.Mvc.Diagnostics.ControllerCreationException: Could not create
controller:  The context item is: '/sitecore/content/TEST/home'. The
current route url is: '{*pathInfo}'. This is the default Sitecore
route which is set up in the 'InitializeRoutes' processor of the
'initialize' pipeline. ---> Sitecore.Mvc.Diagnostics.ExceptionWrapper:
The controller for path '/' was not found or does not implement
IController. at
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext
requestContext, String controllerName)
--- End of inner exception stack trace --- at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
Sitecore.Mvc.Controllers.ControllerRunner.GetController() at
Sitecore.Mvc.Controllers.ControllerRunner.Execute() at
Sitecore.Mvc.Pipelines.Request.RequestBegin.ExecuteFormHandler.ExecuteHandler(String
controllerName, String actionName, RequestBeginArgs args) at (Object ,
Object[] ) at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String
pipelineName, PipelineArgs args, String pipelineDomain) at
Sitecore.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String
pipelineName, TArgs args) at
Sitecore.Mvc.Routing.RouteHttpHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)

My DI is setup as follows

```<code>public static void SetupControllers(this IServiceCollection serviceCollection, params Assembly[] assemblyArray)
{
    var controllers = GetTypesImplementing<IController>(assemblyArray)
        .Where(controller => controller.Name.EndsWith("Controller", StringComparison.Ordinal));

    foreach (var x in controllers)
    {
        serviceCollection.AddTransient(x);
    }

    var apis = GetTypesImplementing<ApiController>(assemblyArray)
        .Where(controller => controller.Name.EndsWith("Controller", StringComparison.Ordinal));

    foreach (var x in apis)
    {
        serviceCollection.AddTransient(x);
    }
}
</code>```

答:
This can also happen if by chance you missed to make the class as public.

```<code>class MyPageController : Controller{
}
</code>```

It should be

```<code>public class MyPageController : Controller{
}
</code>```

Body:
I am using Sitecore v9

I have a two base class for all my controllers as follows

public abstract SiteCoreController : ControllerBase, IController, IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IAsyncManagerContainer

public abstract class ControllerBase : IController

All controllers use something like

public class MyPageController : SiteCoreController

In my log files I get heaps of errors

Sitecore.Mvc.Diagnostics.ControllerCreationException: Could not create
controller:  The context item is: '/sitecore/content/TEST/home'. The
current route url is: '{*pathInfo}'. This is the default Sitecore
route which is set up in the 'InitializeRoutes' processor of the
'initialize' pipeline. ---> Sitecore.Mvc.Diagnostics.ExceptionWrapper:
The controller for path '/' was not found or does not implement
IController. at
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext
requestContext, String controllerName)
--- End of inner exception stack trace --- at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
Sitecore.Mvc.Controllers.ControllerRunner.GetController() at
Sitecore.Mvc.Controllers.ControllerRunner.Execute() at
Sitecore.Mvc.Pipelines.Request.RequestBegin.ExecuteFormHandler.ExecuteHandler(String
controllerName, String actionName, RequestBeginArgs args) at (Object ,
Object[] ) at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String
pipelineName, PipelineArgs args, String pipelineDomain) at
Sitecore.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String
pipelineName, TArgs args) at
Sitecore.Mvc.Routing.RouteHttpHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)

My DI is setup as follows

public static void SetupControllers(this IServiceCollection serviceCollection, params Assembly[] assemblyArray)
{
    var controllers = GetTypesImplementing<IController>(assemblyArray)
        .Where(controller => controller.Name.EndsWith("Controller", StringComparison.Ordinal));

    foreach (var x in controllers)
    {
        serviceCollection.AddTransient(x);
    }

    var apis = GetTypesImplementing<ApiController>(assemblyArray)
        .Where(controller => controller.Name.EndsWith("Controller", StringComparison.Ordinal));

    foreach (var x in apis)
    {
        serviceCollection.AddTransient(x);
    }
}

Body:
This can also happen if by chance you missed to make the class as public.

class MyPageController : Controller{
}

It should be

public class MyPageController : Controller{
}


问:
React Native app stuck on splash screen after turning proguard ON
My app is successfully build with and without proguard.
Running app without proguard gave no run time error.
Running app with proguard gave run time error. Crashes on splash screen.

package.json

```<code>{
  "name": "fitlink",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.17",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/drawer": "^6.3.0",
    "@react-navigation/native": "^6.0.8",
    "jetifier": "^1.6.8",
    "react": "17.0.2",
    "react-native": "0.67.2",
    "react-native-gesture-handler": "^2.2.0",
    "react-native-indicators": "^0.17.0",
    "react-native-reanimated": "^2.4.0",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.10.2",
    "react-native-share-menu": "^5.0.5",
    "react-native-splash-screen": "^3.3.0",
    "react-native-svg": "^12.1.1",
    "react-native-vector-icons": "^9.0.0",
    "rn-fetch-blob": "^0.12.0"
  },
  "devDependencies": {
    "@babel/core": "7.17.0",
    "@babel/runtime": "7.17.0",
    "@react-native-community/eslint-config": "2.0.0",
    "babel-jest": "26.6.3",
    "eslint": "7.14.0",
    "jest": "26.6.3",
    "metro-react-native-babel-preset": "0.66.2",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

</code>```

proguard-rules.pro in app folder

```<code># React Native

# Keep our interfaces so they can be used by other ProGuard rules.
# See http://sourceforge.net/p/proguard/bugs/466/
-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters

# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keepclassmembers class * {
    @com.facebook.proguard.annotations.DoNotStrip *;
}

-keep @com.facebook.proguard.annotations.DoNotStripAny class * {
    *;
}

-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
  void set*(***);
  *** get*();
}

-keep class * implements com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * implements com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }

-dontwarn com.facebook.react.**
-keep,includedescriptorclasses class com.facebook.react.bridge.** { *; }
-keep,includedescriptorclasses class com.facebook.react.turbomodule.core.** { *; }

# hermes
-keep class com.facebook.jni.** { *; }

# okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }

-dontwarn okhttp3.**
-dontwarn javax.annotation.**
-dontwarn org.conscrypt.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
</code>```

android/app/build.gradle

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: true,
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = true

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.fitlink"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            storeFile file('fk.keystore')
            storePassword '************'
            keyAlias 'your_key_alias'
            keyPassword '***********'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-share-menu')
    implementation project(':react-native-vector-icons')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-svg')
    implementation project(':react-native-splash-screen')
    implementation project(':react-native-safe-area-context')
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

project.ext.vectoricons = [
    iconFontNames: [ 'Ionicons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

</code>```

What am i doing wrong?
Why app crashes after showing splash screen?

答:
Resolved after changing proguard.pro to</p>
```<code>-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
-keep,allowobfuscation @interface com.facebook.jni.annotations.DoNotStrip

-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keep @com.facebook.common.internal.DoNotStrip class *
-keep @com.facebook.jni.annotations.DoNotStrip class *
-keepclassmembers class * {
    @com.facebook.proguard.annotations.DoNotStrip *;
    @com.facebook.common.internal.DoNotStrip *;
    @com.facebook.jni.annotations.DoNotStrip *;
}

-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
  void set*(***);
  *** get*();
}

-keep class * implements com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * implements com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }

-dontwarn com.facebook.react.**
-keep,includedescriptorclasses class com.facebook.react.bridge.** { *; }
-keep,includedescriptorclasses class com.facebook.react.turbomodule.core.** { *; }

-keep class com.facebook.jni.** { *; }

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

-dontobfuscate

-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }

# -keep @com.facebook.proguard.annotations.DoNotStripAny class * {
#     *;
# }
# -dontwarn javax.annotation.**
# -dontwarn org.conscrypt.**
# -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
</code>```

Body:
My app is successfully build with and without proguard.
Running app without proguard gave no run time error.
Running app with proguard gave run time error. Crashes on splash screen.

package.json

{
  "name": "fitlink",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.17",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/drawer": "^6.3.0",
    "@react-navigation/native": "^6.0.8",
    "jetifier": "^1.6.8",
    "react": "17.0.2",
    "react-native": "0.67.2",
    "react-native-gesture-handler": "^2.2.0",
    "react-native-indicators": "^0.17.0",
    "react-native-reanimated": "^2.4.0",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.10.2",
    "react-native-share-menu": "^5.0.5",
    "react-native-splash-screen": "^3.3.0",
    "react-native-svg": "^12.1.1",
    "react-native-vector-icons": "^9.0.0",
    "rn-fetch-blob": "^0.12.0"
  },
  "devDependencies": {
    "@babel/core": "7.17.0",
    "@babel/runtime": "7.17.0",
    "@react-native-community/eslint-config": "2.0.0",
    "babel-jest": "26.6.3",
    "eslint": "7.14.0",
    "jest": "26.6.3",
    "metro-react-native-babel-preset": "0.66.2",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

proguard-rules.pro in app folder

# React Native

# Keep our interfaces so they can be used by other ProGuard rules.
# See http://sourceforge.net/p/proguard/bugs/466/
-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters

# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keepclassmembers class * {
    @com.facebook.proguard.annotations.DoNotStrip *;
}

-keep @com.facebook.proguard.annotations.DoNotStripAny class * {
    *;
}

-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
  void set*(***);
  *** get*();
}

-keep class * implements com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * implements com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }

-dontwarn com.facebook.react.**
-keep,includedescriptorclasses class com.facebook.react.bridge.** { *; }
-keep,includedescriptorclasses class com.facebook.react.turbomodule.core.** { *; }

# hermes
-keep class com.facebook.jni.** { *; }

# okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }

-dontwarn okhttp3.**
-dontwarn javax.annotation.**
-dontwarn org.conscrypt.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

android/app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: true,
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = true

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.fitlink"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            storeFile file('fk.keystore')
            storePassword '************'
            keyAlias 'your_key_alias'
            keyPassword '***********'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-share-menu')
    implementation project(':react-native-vector-icons')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-svg')
    implementation project(':react-native-splash-screen')
    implementation project(':react-native-safe-area-context')
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

project.ext.vectoricons = [
    iconFontNames: [ 'Ionicons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

What am i doing wrong?
Why app crashes after showing splash screen?

Body:
Resolved after changing proguard.pro to

-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
-keep,allowobfuscation @interface com.facebook.jni.annotations.DoNotStrip

-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keep @com.facebook.common.internal.DoNotStrip class *
-keep @com.facebook.jni.annotations.DoNotStrip class *
-keepclassmembers class * {
    @com.facebook.proguard.annotations.DoNotStrip *;
    @com.facebook.common.internal.DoNotStrip *;
    @com.facebook.jni.annotations.DoNotStrip *;
}

-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
  void set*(***);
  *** get*();
}

-keep class * implements com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * implements com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }

-dontwarn com.facebook.react.**
-keep,includedescriptorclasses class com.facebook.react.bridge.** { *; }
-keep,includedescriptorclasses class com.facebook.react.turbomodule.core.** { *; }

-keep class com.facebook.jni.** { *; }

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**

-dontobfuscate

-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }

# -keep @com.facebook.proguard.annotations.DoNotStripAny class * {
#     *;
# }
# -dontwarn javax.annotation.**
# -dontwarn org.conscrypt.**
# -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase


问:
Iterate over a spark dataframe and create a nested json string
I'm having a dataframe with the below details and I need to iterate over each row to create the below formatted nested json string.

Employee name
Salary
sick_leave_day
paid_leave_day

Karthi
20000
10-10-2021
Y

Karthi
20000
11-12-2021
Y

Karthi
20000
13-12-2021
N

Rajesh
25000
15-12-2021
Y

Rajesh
25000
17-11-2021
N

Rajesh
25000
10-10-2021
Y

The output json should look like below, Here, Name and salary is having unique data and sick_leave_day,paid_leave_day changes for each row.

{
    "Name": "Karthi",
    "Salary": "20000",
    leave_details: [{
            "sick_leave_day": "10-10-2021",
            "paid_leave_day ": "Y"
        },
        {
            "sick_leave_day": "11-12-2021",
            "paid_leave_day ": "Y"
        },
        {
            "sick_leave_day": "13-12-2021",
            "paid_leave_day ": "N"
        }
    ]
}
```

I have tried to iterate over dataframe using foreach method, but I'm unable to get the logic. If I group the name and salary, I can't get the value of name and salary only once. So, please help me to write the logic by iterating over each row to create this logic. Thanks in advance.

Body:
I'm having a dataframe with the below details and I need to iterate over each row to create the below formatted nested json string.

Employee name
Salary
sick_leave_day
paid_leave_day

Karthi
20000
10-10-2021
Y

Karthi
20000
11-12-2021
Y

Karthi
20000
13-12-2021
N

Rajesh
25000
15-12-2021
Y

Rajesh
25000
17-11-2021
N

Rajesh
25000
10-10-2021
Y

The output json should look like below, Here, Name and salary is having unique data and sick_leave_day,paid_leave_day changes for each row.

{
    "Name": "Karthi",
    "Salary": "20000",
    leave_details: [{
            "sick_leave_day": "10-10-2021",
            "paid_leave_day ": "Y"
        },
        {
            "sick_leave_day": "11-12-2021",
            "paid_leave_day ": "Y"
        },
        {
            "sick_leave_day": "13-12-2021",
            "paid_leave_day ": "N"
        }
    ]
}

I have tried to iterate over dataframe using foreach method, but I'm unable to get the logic. If I group the name and salary, I can't get the value of name and salary only once. So, please help me to write the logic by iterating over each row to create this logic. Thanks in advance.

Body:
You can use the collect_list aggregation function to group by Employee and get the list of leave days.

For instance you can manually create a JSON with the 2 "leave_day" columns then aggregate using collect_list:

var result = df.withColumn("new_col", concat(lit("{ sick_leave_day:"), df.col("sick_leave_day"), lit(", paid_leave_day:"), df.col("paid_leave_day"), lit("}")))
    .groupBy("Employee name", "Salary")
    .agg(collect_list("new_col"))

result.show(truncate=false)

+-------------+------+------------------------------------------------------------------------------------------------------------------------------------------------+
|Employee name|Salary|collect_list(new_col)                                                                                |
+-------------+------+------------------------------------------------------------------------------------------------------------------------------------------------+
|Rajesh       |25000 |[{ sick_leave_day:15-12-2021, paid_leave_day:Y}, { sick_leave_day:17-11-2021, paid_leave_day:N}, { sick_leave_day:10-10-2021, paid_leave_day:Y}]|
|Karthi       |20000 |[{ sick_leave_day:10-10-2021, paid_leave_day:Y}, { sick_leave_day:11-12-2021, paid_leave_day:Y}, { sick_leave_day:13-12-2021, paid_leave_day:N}]|
+-------------+------+------------------------------------------------------------------------------------------------------------------------------------------------+


问:
Class to collect data from user
I am learning python from scratch and am stuck with classes what I am trying to achieve as follows:

Problem statement: "Collect the data of different students into an array and display."

I am trying to achieve this using classes.
Below is my code which I am trying out. Need help on how to get the values of different question into one single dimensional array.

i.e.

["brittos school", "Ahmedabad", "Francis", "34", " 36", "anthony's school", "Mumbai", "Sam", "45", " 55"]

Where 34 36 are the marks of the subject.

```<code>class Mack:
    def getmarks(self,numberofsubjects,numberofstudents,sub):
        marks=[]
        for i in range(numberofstudents):
            self.sname=input("Enter your School Name: ")
            a.append(marks)
            self.city=input("Enter the School City: ")
            a.append(marks)
            self.name=input("Enter your Name")
            a.append(marks)
            a=[]
            for j in range(numberofsubjects):
                a.append(int(input(f"Enter the Marks for {sub[j]} ")))
            marks.append(a)

    def show(self):
        print("My Name is: ",self.name)
        print("My City is: ",self.city)

sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))

for i in range(0, numberofsubjects):
        ele = input(f"enter the subject name :{i+1}")
        sub.append(ele)

ab=Mack()
for i in range(0,numberofstudents):
    ab.getmarks(numberofstudents,numberofsubjects,sub)
</code>```

答:
First of all, you are using the same loop outside the getmarks function and inside it so for example if I input number of students as 2. It will run 4 times which is incorrect. Loop over number of students once. Secondly a is not defined anywhere so if you want the list of all the input I'd suggest creating a as a member variable of this class.
I think this code below is what you need

```<code>class Mack:
    def getmarks(self,numberofsubjects,numberofstudents,sub):
        marks=[]
        a = []
        for i in range(numberofstudents):
            self.sname=input("Enter your School Name: ")
            a.append(self.sname)
            self.city=input("Enter the School City: ")
            a.append(self.city)
            self.name=input("Enter your Name")
            a.append(self.name)
            for j in range(numberofsubjects):
                a.append(int(input(f"Enter the Marks for {sub[j]} ")))
            marks.append(a)

        return a

    def show(self):
        print("My Name is: ",self.name)
        print("My City is: ",self.city)

sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))

for i in range(0, numberofsubjects):
    ele = input(f"enter the subject name :{i+1}")
    sub.append(ele)

ab=Mack()

result = ab.getmarks(numberofstudents,numberofsubjects,sub)
print(result)
</code>```

Although this is a very bad approach to do what you are trying to do. What I would suggest is to create a Student Class like.

```<code>class Student:
    def __init__(self, name, sname, cname, subjects, marks):
        self.name = name
        self.sname = sname
        self.cname = cname
        self.subjects = subjects
        self.marks = marks
</code>```

where subjects and marks would lists of subjects and marks. You can also create a dictionary if you want where subject would be key and marks would be value. After that, you can simple create a list of this class and take input for every element of that Student list.

Title: Class to collect data from user

Body:
I am learning python from scratch and am stuck with classes what I am trying to achieve as follows:

Problem statement: "Collect the data of different students into an array and display."

I am trying to achieve this using classes.
Below is my code which I am trying out. Need help on how to get the values of different question into one single dimensional array.

i.e.

["brittos school", "Ahmedabad", "Francis", "34", " 36", "anthony's school", "Mumbai", "Sam", "45", " 55"]

Where 34 36 are the marks of the subject.

class Mack:
    def getmarks(self,numberofsubjects,numberofstudents,sub):
        marks=[]
        for i in range(numberofstudents):
            self.sname=input("Enter your School Name: ")
            a.append(marks)
            self.city=input("Enter the School City: ")
            a.append(marks)
            self.name=input("Enter your Name")
            a.append(marks)
            a=[]
            for j in range(numberofsubjects):
                a.append(int(input(f"Enter the Marks for {sub[j]} ")))
            marks.append(a)

    def show(self):
        print("My Name is: ",self.name)
        print("My City is: ",self.city)

sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))

for i in range(0, numberofsubjects):
        ele = input(f"enter the subject name :{i+1}")
        sub.append(ele)

ab=Mack()
for i in range(0,numberofstudents):
    ab.getmarks(numberofstudents,numberofsubjects,sub)

Body:
First of all, you are using the same loop outside the getmarks function and inside it so for example if I input number of students as 2. It will run 4 times which is incorrect. Loop over number of students once. Secondly a is not defined anywhere so if you want the list of all the input I'd suggest creating a as a member variable of this class.
I think this code below is what you need

class Mack:
    def getmarks(self,numberofsubjects,numberofstudents,sub):
        marks=[]
        a = []
        for i in range(numberofstudents):
            self.sname=input("Enter your School Name: ")
            a.append(self.sname)
            self.city=input("Enter the School City: ")
            a.append(self.city)
            self.name=input("Enter your Name")
            a.append(self.name)
            for j in range(numberofsubjects):
                a.append(int(input(f"Enter the Marks for {sub[j]} ")))
            marks.append(a)

        return a

    def show(self):
        print("My Name is: ",self.name)
        print("My City is: ",self.city)

sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))

for i in range(0, numberofsubjects):
    ele = input(f"enter the subject name :{i+1}")
    sub.append(ele)

ab=Mack()

result = ab.getmarks(numberofstudents,numberofsubjects,sub)
print(result)

Although this is a very bad approach to do what you are trying to do. What I would suggest is to create a Student Class like.

class Student:
    def __init__(self, name, sname, cname, subjects, marks):
        self.name = name
        self.sname = sname
        self.cname = cname
        self.subjects = subjects
        self.marks = marks

where subjects and marks would lists of subjects and marks. You can also create a dictionary if you want where subject would be key and marks would be value. After that, you can simple create a list of this class and take input for every element of that Student list.


问:
Is it possible to use messaging, and kafka-messaging separately from helidon?
I created library using helidon-messaging, helidon-messaging-kafka. Also I created an example Java SE app using that library and all works fine. But when I try to use that library in Java EE (Weblogic) legacy application I have got an exception while that application starts:

```<code>org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Config with qualifiers @Default
  at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject io.helidon.messaging.connectors.kafka.KafkaConnector(Config)
  at io.helidon.messaging.connectors.kafka.KafkaConnector.<init>(KafkaConnector.java:0)
</code>```

Is it possible some how to switch off CDI stuff there?

答:
Did you try to exclude the connector package from bean scanning?

Something like this should help:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
       version="2.0"
       bean-discovery-mode="annotated">

     <scan>
        <exclude name="io.helidon.messaging.connectors.kafka.**" />
     </scan>
</beans>
```

More info can be found here

Body:
I created library using helidon-messaging, helidon-messaging-kafka. Also I created an example Java SE app using that library and all works fine. But when I try to use that library in Java EE (Weblogic) legacy application I have got an exception while that application starts:

org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Config with qualifiers @Default
  at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject io.helidon.messaging.connectors.kafka.KafkaConnector(Config)
  at io.helidon.messaging.connectors.kafka.KafkaConnector.<init>(KafkaConnector.java:0)

Is it possible some how to switch off CDI stuff there?

Body:
Did you try to exclude the connector package from bean scanning?

Something like this should help:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
       version="2.0"
       bean-discovery-mode="annotated">

     <scan>
        <exclude name="io.helidon.messaging.connectors.kafka.**" />
     </scan>
</beans>

More info can be found here


问:
Vue/Vite router has /#/ which doesn't work with Oauth flow callback URL
So I'm pretty sure this is easy but I'm brand new to Vite and I haven't hit upon the right combination yet. I have all of this working in Vue-Cli 3 but would like to get it working in Vite.

I'm using Vue Router 4.0.0 and Vue 3.2.25 and Vite and Okta as my Oauth provider. I have a sign-in redirect URI in Okta of http://localhost:8080/login/callback. When I initiate my login flow it redirects to http://localhost:8080/login/callback?code=PnrOH4v4_... which resolves to my Home route of "/" and not my LoginCallback route of "/login/callback". I'm pretty sure it's the hash. I've tried various combinations of things but haven't hit the right combination yet.

Here's my router.

```<code>import { createRouter, createWebHashHistory } from "vue-router";
import { LoginCallback, navigationGuard } from "@okta/okta-vue";

import Home from "../views/Home.vue";
import User from "../views/User.vue";
import Profile from "@/components/Profile.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/login/callback",
    component: LoginCallback,
  },
  {
    path: "/user",
    name: "User",
    component: User,
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: "/profile",
    component: Profile,
    meta: {
      requiresAuth: true,
    },
  },
];

console.log("base = " + import.meta.env.BASE_URL);
const router = createRouter({
  mode: "history",
  history: createWebHashHistory(import.meta.env.BASE_URL),
  hash: false,
  routes,
});

router.beforeEach(navigationGuard);

export default router;
</code>```

and here's my vite.config.js

```<code>import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  base: "http://localhost:8080/",
  server: {
    port: 3030,
  },
  preview: {
    port: 8080,
  },
  plugins: [vue()],
  resolve: {
    alias: [
      { find: "@", replacement: path.resolve(__dirname, "./src") },
      {
        // I got this from https://github.com/okta/okta-auth-js/issues/641
        find: "@okta/okta-auth-js",
        replacement: require.resolve(
          "@okta/okta-auth-js/dist/okta-auth-js.umd.js"
        ),
      },
      { find: "@config", replacement: path.resolve(__dirname, "./src/config") },
    ],
  },
});
</code>```

答:
I believe you don't need any more alias for replacing "@okta/okta-auth-js" with "@okta/okta-auth-js/dist/okta-auth-js.umd.js" since this issue was fixed in the newest version of Okta Vue SDK.

Since 5.x version you need to install @okta/okta-auth-js as dependency. Here you can find more information about migration.

Body:
So I'm pretty sure this is easy but I'm brand new to Vite and I haven't hit upon the right combination yet. I have all of this working in Vue-Cli 3 but would like to get it working in Vite.

I'm using Vue Router 4.0.0 and Vue 3.2.25 and Vite and Okta as my Oauth provider. I have a sign-in redirect URI in Okta of http://localhost:8080/login/callback. When I initiate my login flow it redirects to http://localhost:8080/login/callback?code=PnrOH4v4_... which resolves to my Home route of "/" and not my LoginCallback route of "/login/callback". I'm pretty sure it's the hash. I've tried various combinations of things but haven't hit the right combination yet.

Here's my router.

import { createRouter, createWebHashHistory } from "vue-router";
import { LoginCallback, navigationGuard } from "@okta/okta-vue";

import Home from "../views/Home.vue";
import User from "../views/User.vue";
import Profile from "@/components/Profile.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/login/callback",
    component: LoginCallback,
  },
  {
    path: "/user",
    name: "User",
    component: User,
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: "/profile",
    component: Profile,
    meta: {
      requiresAuth: true,
    },
  },
];

console.log("base = " + import.meta.env.BASE_URL);
const router = createRouter({
  mode: "history",
  history: createWebHashHistory(import.meta.env.BASE_URL),
  hash: false,
  routes,
});

router.beforeEach(navigationGuard);

export default router;

and here's my vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  base: "http://localhost:8080/",
  server: {
    port: 3030,
  },
  preview: {
    port: 8080,
  },
  plugins: [vue()],
  resolve: {
    alias: [
      { find: "@", replacement: path.resolve(__dirname, "./src") },
      {
        // I got this from https://github.com/okta/okta-auth-js/issues/641
        find: "@okta/okta-auth-js",
        replacement: require.resolve(
          "@okta/okta-auth-js/dist/okta-auth-js.umd.js"
        ),
      },
      { find: "@config", replacement: path.resolve(__dirname, "./src/config") },
    ],
  },
});


问:
Backup of svn repository to shared folder on NAS fails
I want to set up an automatic incremental backup of my SVN repositories.
Doing that to a local folder of the same PC seems to work, but if I try to write the files directly to a shared folder (I tried 2 different QNAP nas boxes) I get various errors, always a couple of hundred lines.

I tried

```<code>svnadmin hotcopy C:\SVNRepos\RalfStein \\Nas\home\svn\RalfStein
</code>```

After 202 lines it returned

svnadmin: E720059: Can't move
'\oldnas\home\svn\RalfStein\db\revprops\svn-1AA28066' to
'\oldnas\home\svn\RalfStein\db\revprops\203': Unerwarteter
Netzwerkfehler.

("Unerwarteter Netzwerkfehler" means "unexpected network error".)

On a different nas it returned after 799 lines:

svnadmin: E720059: Can't close file
'\nas\home\svn\RalfStein\db\revprops\svn-44790380': Unerwarteter
Netzwerkfehler.

I've shut down the svn service, so there's no danger of someone working on svn in the meantime. Still same problem.

In don't want to use "dump" as it's not incremental.
I can manually copy the entire repository and that seems to work. However, I'd like to understand where the problem is coming from.

System:

VisualSVN V4.3.6 on Windows10

svnadmin --version : 1.14.1

The NAS (a QNAP TS453d) provides the SMB-share

答:
What protocol does your NAS use?

Do you see errors when you run the Backup-SvnRepository PowerShell cmdlet?

What VisualSVN Server version and the version of SVN command-line tools are you using? I.e., what svnadmin --version says?

Note that you can consider the built-in Backup and Restore feature. It supports backup scheduling, encryption, incremental backups and backups to remote shares and Azure Files cloud. See KB106: Getting Started with Backup and Restore and KB137: Choosing backup destination.

I want to set up an automatic incremental backup of my SVN
repositories. Doing that to a local folder of the same PC seems to
work, but if I try to write the files directly to a shared folder (I
tried 2 different QNAP nas boxes) I get various errors, always a
couple of hundred lines.

From what I see, an unexpected network error indeed occurs when you hotcopy the repository onto your NAS. Please, double-check that you are using up-to-date Subversion command-line tools (what svnadmin --version says?).

I've shut down the svn service, so there's no danger of someone
working on svn in the meantime. Still same problem.

You don't need to stop the server's services when you run svnadmin  hotcopy:

[[[

This subcommand makes a “hot” backup of your repository, including all hooks, configuration files, and, of course, database files. You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository.

]]]

Body:
I want to set up an automatic incremental backup of my SVN repositories.
Doing that to a local folder of the same PC seems to work, but if I try to write the files directly to a shared folder (I tried 2 different QNAP nas boxes) I get various errors, always a couple of hundred lines.

I tried

svnadmin hotcopy C:\SVNRepos\RalfStein \\Nas\home\svn\RalfStein

After 202 lines it returned

svnadmin: E720059: Can't move
'\oldnas\home\svn\RalfStein\db\revprops\svn-1AA28066' to
'\oldnas\home\svn\RalfStein\db\revprops\203': Unerwarteter
Netzwerkfehler.

("Unerwarteter Netzwerkfehler" means "unexpected network error".)

On a different nas it returned after 799 lines:

svnadmin: E720059: Can't close file
'\nas\home\svn\RalfStein\db\revprops\svn-44790380': Unerwarteter
Netzwerkfehler.

I've shut down the svn service, so there's no danger of someone working on svn in the meantime. Still same problem.

In don't want to use "dump" as it's not incremental.
I can manually copy the entire repository and that seems to work. However, I'd like to understand where the problem is coming from.

System:

VisualSVN V4.3.6 on Windows10

svnadmin --version : 1.14.1

The NAS (a QNAP TS453d) provides the SMB-share


问:
AEM JCR SQL2 query to find all pages contains specific component
I wish to build a sql2 jcr query to find all pages under /content that contains this component, e.g /apps/platform/aem-core/components/content/form/form

I read https://wiki.magnolia-cms.com/display/WIKI/JCR+Query+Cheat+Sheet and tried something like below

My current attempt is something like SELECT * from [cq:Page] AS t WHERE t.contains('/apps/platform/aem-core/components/content/form/form')

But it won't work. Please suggest me a example to find all pages contains this component. Thanks

答: SELECT page.* FROM [cq:Page] AS page INNER JOIN [nt:base] AS component ON ISDESCENDANTNODE(component,page) WHERE ISDESCENDANTNODE(page, '/content') AND component.[sling:resourceType] = '/apps/platform/aem-core/components/content/form/form'</p>


问:
Count and Sort with Pandas
I have a dataframe for values form a file by which I have grouped by two columns, which return a count of the aggregation. Now I want to sort by the max count value, however I get the following error:

KeyError: 'count'

Looks the group by agg count column is some sort of index so not sure how to do this, I'm a beginner to Python and Panda.
Here's the actual code, please let me know if you need more detail:

```<code>def answer_five():
    df = census_df#.set_index(['STNAME'])
    df = df[df['SUMLEV'] == 50]
    df = df[['STNAME','CTYNAME']].groupby(['STNAME']).agg(['count']).sort(['count'])
    #df.set_index(['count'])
    print(df.index)
    # get sorted count max item
    return df.head(5)
</code>```

答:
For sort the rows by count of a colum, you can do this:

sorted_index = df['col'].value_counts().index
df.set_index('col').loc[sorted_index].reset_index()
```
<p>If you want to keep the old index, do this:</p>
<pre class="lang-py prettyprint-override"><code>sorted_index = df['col'].value_counts().index
df['index'] = df.index
df.set_index('col', drop=True).loc[sorted_index].reset_index().set_index('index', drop=True)
</code>```

Title: Count and Sort with Pandas

Body:
I have a dataframe for values form a file by which I have grouped by two columns, which return a count of the aggregation. Now I want to sort by the max count value, however I get the following error:

KeyError: 'count'

Looks the group by agg count column is some sort of index so not sure how to do this, I'm a beginner to Python and Panda.
Here's the actual code, please let me know if you need more detail:

def answer_five():
    df = census_df#.set_index(['STNAME'])
    df = df[df['SUMLEV'] == 50]
    df = df[['STNAME','CTYNAME']].groupby(['STNAME']).agg(['count']).sort(['count'])
    #df.set_index(['count'])
    print(df.index)
    # get sorted count max item
    return df.head(5)

Body:
For sort the rows by count of a colum, you can do this:

sorted_index = df['col'].value_counts().index
df.set_index('col').loc[sorted_index].reset_index()

If you want to keep the old index, do this:

sorted_index = df['col'].value_counts().index
df['index'] = df.index
df.set_index('col', drop=True).loc[sorted_index].reset_index().set_index('index', drop=True)