问:
Laravel Distinct query is not working in my project
In my laravel project, am joining more than 2 tables, but the problem is that in the table location_services,There is multiple entries with same location_id and services_id. I want to take only one row in such cases.Following is my Query.
What is the problem here.Kindly help me to resolve it

```<code>   $loc_services = Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
                        ->join('services', 'services.serviceID', '=', 'location_services.serviceID')
                        ->whereIn('services.serviceID',$services_id)
                        ->where('clinics.api_key','=',$apiKey)
                        ->get();
</code>```

Please help.

I want to retrive all data from clinics table which have various services in various locations. Eaach location may or may not have more than one services

答:
You may use groupBy() method to achieve the goal. Just add this method before the get() method's call.

```<code>groupBy('location_services.locationID', 'location_services.serviceID')
</code>```

Body:
In my laravel project, am joining more than 2 tables, but the problem is that in the table location_services,There is multiple entries with same location_id and services_id. I want to take only one row in such cases.Following is my Query.
What is the problem here.Kindly help me to resolve it

   $loc_services = Clinic::select('*')
                        ->join('locations', 'locations.clinicID', '=', 'clinics.clinicID')
                        ->join('location_services', 'location_services.locationID', '=', 'locations.locationID')
                        ->join('services', 'services.serviceID', '=', 'location_services.serviceID')
                        ->whereIn('services.serviceID',$services_id)
                        ->where('clinics.api_key','=',$apiKey)
                        ->get();

Please help.

I want to retrive all data from clinics table which have various services in various locations. Eaach location may or may not have more than one services

Body:
You may use groupBy() method to achieve the goal. Just add this method before the get() method's call.

groupBy('location_services.locationID', 'location_services.serviceID')


来源: stackexchange

问:
How to extend a Pydantic object and change some fields' type?
There are two similar pydantic object like that. The only difference is some fields are optionally.
How can I just define the fields in one object and extend into another one?</p>

```<code>class ProjectCreateObject(BaseModel):
    project_id: str
    project_name: str
    project_type: ProjectTypeEnum
    depot: str
    system: str
    ...

class ProjectPatchObject(ProjectCreateObject):
    project_id: str
    project_name: Optional[str]
    project_type: Optional[ProjectTypeEnum]
    depot: Optional[str]
    system: Optional[str]
    ...

</code>```

答:
I find a good and easy way by __init__subclass__.
The docs also can be generated successfully.

```<code>class ProjectCreateObject(BaseModel):
    project_id: str
    project_name: str
    project_type: ProjectTypeEnum
    depot: str
    system: str
    ...

    def __init_subclass__(cls, optional_fields=(), **kwargs):
        """
        allow some fields of subclass turn into optional
        """
        super().__init_subclass__(**kwargs)
        for field in optional_fields:
            cls.__fields__[field].outer_type_ = Optional
            cls.__fields__[field].required = False

_patch_fields = ProjectCreateObject.__fields__.keys() - {'project_id'}

class ProjectPatchObject(ProjectCreateObject, optional_fields=_patch_fields):
    pass
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are two similar pydantic object like that. The only difference is some fields are optionally.
How can I just define the fields in one object and extend into another one?

class ProjectCreateObject(BaseModel):
    project_id: str
    project_name: str
    project_type: ProjectTypeEnum
    depot: str
    system: str
    ...

class ProjectPatchObject(ProjectCreateObject):
    project_id: str
    project_name: Optional[str]
    project_type: Optional[ProjectTypeEnum]
    depot: Optional[str]
    system: Optional[str]
    ...

Body:
I find a good and easy way by __init__subclass__.
The docs also can be generated successfully.

class ProjectCreateObject(BaseModel):
    project_id: str
    project_name: str
    project_type: ProjectTypeEnum
    depot: str
    system: str
    ...

    def __init_subclass__(cls, optional_fields=(), **kwargs):
        """
        allow some fields of subclass turn into optional
        """
        super().__init_subclass__(**kwargs)
        for field in optional_fields:
            cls.__fields__[field].outer_type_ = Optional
            cls.__fields__[field].required = False

_patch_fields = ProjectCreateObject.__fields__.keys() - {'project_id'}

class ProjectPatchObject(ProjectCreateObject, optional_fields=_patch_fields):
    pass


问:
How to force  to be sticky in on side on the HTML page?
I'm trying to make  with google maps reference stick on the right side of my page I've tried this code still scrolls with the rest of the page

#map{
position: -webkit-sticky;
  position: sticky;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="map" id="map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d317715.71193692513!2d-0.38178583985785625!3d51.528735196048615!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47d8a00baf21de75%3A0x52963a5addd52a99!2sLondon%2C%20UK!5e0!3m2!1sen!2sae!4v1589590348452!5m2!1sen!2sae" width="600" height="700" frameborder="0" style="border:0; width: 100%;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe></code>```

答:
You are looking for position:fixed:

#map {
  position: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="map" id="map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d317715.71193692513!2d-0.38178583985785625!3d51.528735196048615!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47d8a00baf21de75%3A0x52963a5addd52a99!2sLondon%2C%20UK!5e0!3m2!1sen!2sae!4v1589590348452!5m2!1sen!2sae" width="600" height="700" frameborder="0" style="border:0; width: 100%;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe></code>```

Elements with position:fixed will stay in place when their parent element is scrolled.

Title: How to force < iframe> to be sticky in on side on the HTML page?

Body:
You are looking for position:fixed:

#map {
  position: fixed;
}

<iframe class="map" id="map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d317715.71193692513!2d-0.38178583985785625!3d51.528735196048615!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47d8a00baf21de75%3A0x52963a5addd52a99!2sLondon%2C%20UK!5e0!3m2!1sen!2sae!4v1589590348452!5m2!1sen!2sae" width="600" height="700" frameborder="0" style="border:0; width: 100%;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>

Elements with position:fixed will stay in place when their parent element is scrolled.


问:
Angular Routing Issue 'Cannot match any routes'
I just set up a new Angular project and added two Component Routes in my AppRouting Module.

I get the following error when I try to access a route:

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'cr-calculator'
Error: Cannot match any routes. URL Segment: 'cr-calculator'
    at ApplyRedirects.noMatchError (router.js:4396)
    at CatchSubscriber.selector (router.js:4360)
    at CatchSubscriber.error (catchError.js:29)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at ThrowIfEmptySubscriber._error (Subscriber.js:75)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41632)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)
</code>```

And also the router-outlet doesn't work for me for some reason, it just shows blank even if I have some content in my Route Components.

This is my app-routing.module.ts:

```<code>import { CrCalculatorPageComponent } from './../pages/cr-calculator-page/cr-calculator-page.component';
import { HomePageComponent } from './../pages/home-page/home-page.component';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

export const routes: Routes = [
  {
    path: '',
    data: {
      linkName: 'Home',
      showInMenu: true,
      animation: 'HomePage'
    },
    component: HomePageComponent
  },
  {
    path: 'cr-calculator',
    data: {
      linkName: 'CR Calculator',
      showInMenu: true,
      animation: 'CrCalculator'
    },
    component: CrCalculatorPageComponent
  }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

... and this is my app.module.ts:

```<code>import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { CrCalculatorPageComponent } from './pages/cr-calculator-page/cr-calculator-page.component';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavMenuComponent,
    HomePageComponent,
    CrCalculatorPageComponent
  ],
  imports: [
    BrowserModule,
    RouterModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

I have multi-checked my code and not found anything. I have also checked out some answered Questions here already but nothing helped me solving my issue.

Thanks in advance and please tell me if you need some more code to review the issue.

// EDIT

HTML-Code with routerLink Statements:

```<code><ul class="navbar-nav mr-auto">
  <ng-container *ngFor="let link of links">
    <li class="nav-item" *ngIf="link.data.showInMenu" [routerLinkActive]="['active']">
      <a class="nav-link" [routerLink]="link.path">{{link.data.linkName}}</a>
    </li>
  </ng-container>
</ul>
</code>```

'links' is basically the routes Object-Array from the app-routing.module.ts

答: The way you define the [routerLink], the URL ends up something like cr-calculator. That is a relative URL, because it doesn't start with /. Those don't work if you are not on a top level route. Add a / in front of the top level routes, whenever you are specifying the links in your nav.

Body:
I just set up a new Angular project and added two Component Routes in my AppRouting Module.

I get the following error when I try to access a route:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'cr-calculator'
Error: Cannot match any routes. URL Segment: 'cr-calculator'
    at ApplyRedirects.noMatchError (router.js:4396)
    at CatchSubscriber.selector (router.js:4360)
    at CatchSubscriber.error (catchError.js:29)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at ThrowIfEmptySubscriber._error (Subscriber.js:75)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41632)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)

And also the router-outlet doesn't work for me for some reason, it just shows blank even if I have some content in my Route Components.

This is my app-routing.module.ts:

import { CrCalculatorPageComponent } from './../pages/cr-calculator-page/cr-calculator-page.component';
import { HomePageComponent } from './../pages/home-page/home-page.component';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

export const routes: Routes = [
  {
    path: '',
    data: {
      linkName: 'Home',
      showInMenu: true,
      animation: 'HomePage'
    },
    component: HomePageComponent
  },
  {
    path: 'cr-calculator',
    data: {
      linkName: 'CR Calculator',
      showInMenu: true,
      animation: 'CrCalculator'
    },
    component: CrCalculatorPageComponent
  }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

... and this is my app.module.ts:

import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { CrCalculatorPageComponent } from './pages/cr-calculator-page/cr-calculator-page.component';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavMenuComponent,
    HomePageComponent,
    CrCalculatorPageComponent
  ],
  imports: [
    BrowserModule,
    RouterModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I have multi-checked my code and not found anything. I have also checked out some answered Questions here already but nothing helped me solving my issue.

Thanks in advance and please tell me if you need some more code to review the issue.

// EDIT

HTML-Code with routerLink Statements:

  <ng-container *ngFor="let link of links">

      {{link.data.linkName}}

  </ng-container>

'links' is basically the routes Object-Array from the app-routing.module.ts


问:
Pandas: extract data from df to a new df based on condition
I have the following df1:

```<code>Person  Day1  Day2  Day3
1       2     1     1
2       2     0     7
3       4     1     2
</code>```

And then another df2:

```<code>Person  Day1  Day2  Day3
1       a     b     b
2       a     c     a
3       c     b     c
</code>```

So these two dataframes have the same index and columns. How can I select elements of df1 that only have "c" in df2?

The result should be values from df1 when the condition is met, and 0 otherwise:

```<code>Person  Day1  Day2  Day3
1       0     0     0
2       0     0     0
3       4     0     2
</code>```

答:
With @jezrael's help, another solution using np.where:

```<code>import numpy as np
df = pd.DataFrame(np.where(df2.eq('c'), df1, 0), index=df1.index, columns=df1.columns).reset_index()
</code>```

Output:

```<code>   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2
</code>```

Body:
I have the following df1:

Person  Day1  Day2  Day3
1       2     1     1
2       2     0     7
3       4     1     2

And then another df2:

Person  Day1  Day2  Day3
1       a     b     b
2       a     c     a
3       c     b     c

So these two dataframes have the same index and columns. How can I select elements of df1 that only have "c" in df2?

The result should be values from df1 when the condition is met, and 0 otherwise:

Person  Day1  Day2  Day3
1       0     0     0
2       0     0     0
3       4     0     2

Body:
With @jezrael's help, another solution using np.where:

import numpy as np
df = pd.DataFrame(np.where(df2.eq('c'), df1, 0), index=df1.index, columns=df1.columns).reset_index()

Output:

   Person  Day1  Day2  Day3
0       1     0     0     0
1       2     0     0     0
2       3     4     0     2


答:
If you want individual vectors named in the global environment (i.e. object V1, V2, and etc.):

```<code>invisible(mapply(assign, names(as.data.frame(mu_t_0)),  as.data.frame(mu_t_0), MoreArgs=list(envir = globalenv())))
</code>```

Though I'm really interested in why the OP doesn't want to just work with a single matrix...

Title: How can I convert matrix to different matrices in R?

Body:
Here I have some codes generating a matrix like this:

N = 200
T = 10
mu_0 <- matrix(diag(1, T))
dim(mu_0) <- c(T,T)
mu_t_0 <- matrix(rep(t(mu_0), N), ncol = T, byrow = TRUE)

And generally the result looks like this

   V1   V2  V3  V4  V5  V6  V7  V8  V9 V10
1   1   0   0   0   0   0   0   0   0   0
2   0   1   0   0   0   0   0   0   0   0
3   0   0   1   0   0   0   0   0   0   0
4   0   0   0   1   0   0   0   0   0   0
5   0   0   0   0   1   0   0   0   0   0
6   0   0   0   0   0   1   0   0   0   0
7   0   0   0   0   0   0   1   0   0   0
8   0   0   0   0   0   0   0   1   0   0
9   0   0   0   0   0   0   0   0   1   0
10  0   0   0   0   0   0   0   0   0   1
11  1   0   0   0   0   0   0   0   0   0
12  0   1   0   0   0   0   0   0   0   0
13  0   0   1   0   0   0   0   0   0   0
14  0   0   0   1   0   0   0   0   0   0
15  0   0   0   0   1   0   0   0   0   0
16  0   0   0   0   0   1   0   0   0   0
17  0   0   0   0   0   0   1   0   0   0
18  0   0   0   0   0   0   0   1   0   0
19  0   0   0   0   0   0   0   0   1   0
20  0   0   0   0   0   0   0   0   0   1
...

Now for later calculation I want to split this large matrix into different small matrices like this:

Matrix One:

1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
...

Matrix Two:

0
1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
...

I tried the split function but I cannot get what I want. Are there any solutions?

Body:
If you want individual vectors named in the global environment (i.e. object V1, V2, and etc.):

invisible(mapply(assign, names(as.data.frame(mu_t_0)),  as.data.frame(mu_t_0), MoreArgs=list(envir = globalenv())))

Though I'm really interested in why the OP doesn't want to just work with a single matrix...


问:
Flutter : "Could not resolved the package" every install new packages
I have some problem about installing new package from pub.dev. I create my own package inside my root project with this command :

flutter create --template=package main_template

structure folder

I installing new package inside main_template not lib. every install new package in main_template i received this error :

```<code>
Compiler message:
Error: Could not resolve the package 'device_info' in 'package:device_info/device_info.dart'.
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:3:8: Error: Not found: 'package:device_info/device_info.dart'
import 'package:device_info/device_info.dart';
       ^
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:9:11: Error: 'DeviceInfoPlugin' isn't a type.
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
          ^^^^^^^^^^^^^^^^
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:9:47: Error: The method 'DeviceInfoPlugin' isn't defined for the class 'GetDeviceId'.
 - 'GetDeviceId' is from 'package:main_template/variable/get_device_id.dart' ('sinergi_flutter_template/main_template/lib/variable/get_device_id.dart').
Try correcting the name to the name of an existing method, or defining a method named 'DeviceInfoPlugin'.
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
                                              ^^^^^^^^^^^^^^^^
U
nhandled exception:
FileSystemException(uri=org-dartlang-u
ntranslatable-uri:package%3Adevice_info%2Fdevice_info.dart; message=StandardFileSystem only supports file:* and data:* URIs)
#0      StandardFileSystem.entityForUri  (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1      asFileUri ( (package:vm/kernel_front_end.dart:604:3)
7)
#2      writeDepfile  (package:vm/kernel_front_end.dart:799:21)
<asynchronous suspension>
#3      FrontendCompiler.compile  (package:frontend_server/frontend_server.dart:472:15)
<asynchronous suspension>
#4      _FlutterFrontendCompiler.compile (package:flut
ter_frontend_server/server.dart:38:22)
#5      starter  (package:flutter_frontend_server/server.dart:149:27)
#6      main  (file:///C:/b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30)
#7      _startIsolate.<anonymous closure>  (dart:isolate-patch/isolate_patch.dart:305:32)
#8      _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:174:12)
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 780

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* 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 20s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

</code>```

Until now i trying install 3 package [Cache Network Image,Device Info , SplashScreen]. And all packages give me that error.

How can i fixed it ?

答:
This command fixed my issue:

flutter pub get

Body:
I have some problem about installing new package from pub.dev. I create my own package inside my root project with this command :

flutter create --template=package main_template

structure folder

I installing new package inside main_template not lib. every install new package in main_template i received this error :

Compiler message:
Error: Could not resolve the package 'device_info' in 'package:device_info/device_info.dart'.
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:3:8: Error: Not found: 'package:device_info/device_info.dart'
import 'package:device_info/device_info.dart';
       ^
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:9:11: Error: 'DeviceInfoPlugin' isn't a type.
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
          ^^^^^^^^^^^^^^^^
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:9:47: Error: The method 'DeviceInfoPlugin' isn't defined for the class 'GetDeviceId'.
 - 'GetDeviceId' is from 'package:main_template/variable/get_device_id.dart' ('sinergi_flutter_template/main_template/lib/variable/get_device_id.dart').
Try correcting the name to the name of an existing method, or defining a method named 'DeviceInfoPlugin'.
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
                                              ^^^^^^^^^^^^^^^^
U
nhandled exception:
FileSystemException(uri=org-dartlang-u
ntranslatable-uri:package%3Adevice_info%2Fdevice_info.dart; message=StandardFileSystem only supports file:* and data:* URIs)
#0      StandardFileSystem.entityForUri  (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1      asFileUri ( (package:vm/kernel_front_end.dart:604:3)
7)
#2      writeDepfile  (package:vm/kernel_front_end.dart:799:21)
<asynchronous suspension>
#3      FrontendCompiler.compile  (package:frontend_server/frontend_server.dart:472:15)
<asynchronous suspension>
#4      _FlutterFrontendCompiler.compile (package:flut
ter_frontend_server/server.dart:38:22)
#5      starter  (package:flutter_frontend_server/server.dart:149:27)
#6      main  (file:///C:/b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30)
#7      _startIsolate.<anonymous closure>  (dart:isolate-patch/isolate_patch.dart:305:32)
#8      _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:174:12)
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 780

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* 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 20s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

Until now i trying install 3 package [Cache Network Image,Device Info , SplashScreen]. And all packages give me that error.

How can i fixed it ?


问:
How to add a colorbar to a kdeplot
I want to create a Kernel-Density-Estimation with seaborn.kdeplot with a colorbar on the side.

```<code>import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np; np.random.seed(10)
import seaborn as sns; sns.set(color_codes=True)

mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
sns.kdeplot(x, y ,shade=True)
plt.show()
</code>```

While the Kernel-Density-Estimation is created, I do not have a clue how to create the colorbar. I tried using plt.colorbar() without success.

答:
Now it's implemented! parameter cbar=True.

You can also use shade_lowest=False to not shade the first level.

```<code>import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

x, y = np.random.randn(2, 300)
sns.kdeplot(x=x, y=y, zorder=0, n_levels=6, shade=True,
    cbar=True, shade_lowest=False, cmap='viridis')
</code>```

Title: How to add a colorbar to a kdeplot

Body:
I want to create a Kernel-Density-Estimation with seaborn.kdeplot with a colorbar on the side.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np; np.random.seed(10)
import seaborn as sns; sns.set(color_codes=True)

mean, cov = [0, 2], [(1, .5), (.5, 1)]
x, y = np.random.multivariate_normal(mean, cov, size=50).T
sns.kdeplot(x, y ,shade=True)
plt.show()

While the Kernel-Density-Estimation is created, I do not have a clue how to create the colorbar. I tried using plt.colorbar() without success.

Body:
Now it's implemented! parameter cbar=True.

You can also use shade_lowest=False to not shade the first level.

import seaborn as sns
import numpy as np
import matplotlib.pylab as plt

x, y = np.random.randn(2, 300)
sns.kdeplot(x=x, y=y, zorder=0, n_levels=6, shade=True,
    cbar=True, shade_lowest=False, cmap='viridis')


问:
How can I select an option based on the value of an input?
I have similar inputs and a select in my page. If I enter an input value I want to automatically select the option by its value.

The problem is that it works for one input but I have many of those, one the same page and script change values for all of them. What i need achieve that i can enter value for one of them then for second one, but i can't change classes.

//select option from padalinys
(function($) {
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();

    $('.padalinys option').each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div></code>```

答:
You need to use class instead of id and then use $(this).parent().parent().find(".padalinys option") to traverse through only that select which needed to be changed.

Here is demo code :

//select option from padalinys
(function($) {
  //use .test2
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();
    //input->div->div->find select box
    var $selector = $(this).parent().parent().find(".padalinys option");
    $selector.each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="row">
  <div class="col-md-2">
    <label class="text-black" for="test2">Pad. kodas</label>
    <input type="text" id="test2" name="padkodas[]" class="form-control test2">
    <!--added class-->
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black" for="test2">Pad. kodas</label>
    <input type="text" id="test2" name="padkodas[]" class="form-control test2">
    <!--added class-->
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div></code>```

Body:
I have similar inputs and a select in my page. If I enter an input value I want to automatically select the option by its value.

The problem is that it works for one input but I have many of those, one the same page and script change values for all of them. What i need achieve that i can enter value for one of them then for second one, but i can't change classes.

//select option from padalinys
(function($) {
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();

    $('.padalinys option').each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

Body:
You need to use class instead of id and then use $(this).parent().parent().find(".padalinys option") to traverse through only that select which needed to be changed.

Here is demo code :

//select option from padalinys
(function($) {
  //use .test2
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();
    //input->div->div->find select box
    var $selector = $(this).parent().parent().find(".padalinys option");
    $selector.each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="row">
  <div class="col-md-2">
    <label class="text-black" for="test2">Pad. kodas</label>
    <input type="text" id="test2" name="padkodas[]" class="form-control test2">
    <!--added class-->
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black" for="test2">Pad. kodas</label>
    <input type="text" id="test2" name="padkodas[]" class="form-control test2">
    <!--added class-->
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>


问:
Firestore and express, .then chain not stopping when returned res.status(401).json()
So, I'm trying to implement .increment into my API. I need to update a like count more than once per second so that's why I'm trying to update my API to do this. This is the exact code I'm trying to implement:

```<code>const postRef = db
      .collection('posts')
      .doc(postId);
postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
</code>```

The code above works perfectly when there is no current like document associated to a user handle, but when there is, the

```<code>return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
</code>```

gets hit and returns the error message perfectly. But, the rest of the .then chains get hit, which they shouldn't be.

Here is the old code that works:

```<code>exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('posts')
        .doc(postId)
        .get()
        .then((doc) => {
            if(!doc.exists){
                return res.status(404).json({'Error': `post ID ${postId} not found`});
            }
            else{
                return db.collection('likes')
                    .where('postId', '==', postId)
                    .where('userHandle', '==', req.user.userHandle)
                    .get();
            }
        })
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(404).json({'Error': `${req.user.userHandle} already liked this post`});
            }
            else{
                return db
                    .collection('posts')
                    .doc(postId)
                    .get()
            }
        })
        .then((doc) => {
            const oldLikeCount = doc.data().likeCount;
            const newLikeCount = oldLikeCount + 1;
            return db
                .collection('posts')
                .doc(postId)
                .update({
                    likeCount: newLikeCount
                });
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };

            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            return res.status(500).json({error: err});
        });
}
</code>```

In this code, the res.status(404).json() gets hit AND the rest of the .then chains DON'T execute, which is perfect. But this code uses too many reads and writes as well as it's unable to update a document more than 1 time per second.

Here is the new code that has the bug:

```<code>exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('likes')
        .where('postId', '==', postId)
        .where('userHandle', '==', req.user.userHandle)
        .get()
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
            } // It should stop here but it is not.... the code returns the 401 status and the error message so it hits this code, but it doesn't stop the chain
            else{
                // Update count
                const postRef = db
                    .collection('posts')
                    .doc(postId);
                postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
            }
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };
            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            console.error(err);
            return res.status(500).json({error: err});
        });
}
</code>```

Any help is greatly appreciated!!!

答:
I don't think that stacking 3 or 4 then() in sequence of one another is a best practice. If you changed your code to include the then() inside one another, this kind of unexpected behaviour would be mitigated. Here is what your code could look like if you follow this approach(on your new code version):

```<code>exports.likepost = (req, res) => {
    const postId = req.body.postId;
    db.collection('likes')
      .where('postId', '==', postId)
      .where('userHandle', '==', req.user.userHandle)
      .get()
      .then((likeDoc) => {
          if(!likeDoc.empty){
              return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
          }
          else{
              const postRef = db.collection('posts').doc(postId);
              postRef.update({likeCount: admin.firestore.FieldValue.increment(1)}).then({
                  const like = {
                      userHandle: req.user.userHandle,
                      postId: postId,
                      likedAt: new Date().toISOString()
                  };
                  db.collection('likes').add(like).then({
                      return res.json({message: `Successfully liked ${postId}`});
                  });
              });
          }
      })
      .catch((err) => {
            console.error(err);
            return res.status(500).json({error: err});
      });
}
</code>```

Hope this helps.

Body:
So, I'm trying to implement .increment into my API. I need to update a like count more than once per second so that's why I'm trying to update my API to do this. This is the exact code I'm trying to implement:

const postRef = db
      .collection('posts')
      .doc(postId);
postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});

The code above works perfectly when there is no current like document associated to a user handle, but when there is, the

return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});

gets hit and returns the error message perfectly. But, the rest of the .then chains get hit, which they shouldn't be.

Here is the old code that works:

exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('posts')
        .doc(postId)
        .get()
        .then((doc) => {
            if(!doc.exists){
                return res.status(404).json({'Error': `post ID ${postId} not found`});
            }
            else{
                return db.collection('likes')
                    .where('postId', '==', postId)
                    .where('userHandle', '==', req.user.userHandle)
                    .get();
            }
        })
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(404).json({'Error': `${req.user.userHandle} already liked this post`});
            }
            else{
                return db
                    .collection('posts')
                    .doc(postId)
                    .get()
            }
        })
        .then((doc) => {
            const oldLikeCount = doc.data().likeCount;
            const newLikeCount = oldLikeCount + 1;
            return db
                .collection('posts')
                .doc(postId)
                .update({
                    likeCount: newLikeCount
                });
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };

            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            return res.status(500).json({error: err});
        });
}

In this code, the res.status(404).json() gets hit AND the rest of the .then chains DON'T execute, which is perfect. But this code uses too many reads and writes as well as it's unable to update a document more than 1 time per second.

Here is the new code that has the bug:

exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('likes')
        .where('postId', '==', postId)
        .where('userHandle', '==', req.user.userHandle)
        .get()
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
            } // It should stop here but it is not.... the code returns the 401 status and the error message so it hits this code, but it doesn't stop the chain
            else{
                // Update count
                const postRef = db
                    .collection('posts')
                    .doc(postId);
                postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
            }
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };
            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            console.error(err);
            return res.status(500).json({error: err});
        });
}

Any help is greatly appreciated!!!

Body:
I don't think that stacking 3 or 4 then() in sequence of one another is a best practice. If you changed your code to include the then() inside one another, this kind of unexpected behaviour would be mitigated. Here is what your code could look like if you follow this approach(on your new code version):

exports.likepost = (req, res) => {
    const postId = req.body.postId;
    db.collection('likes')
      .where('postId', '==', postId)
      .where('userHandle', '==', req.user.userHandle)
      .get()
      .then((likeDoc) => {
          if(!likeDoc.empty){
              return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
          }
          else{
              const postRef = db.collection('posts').doc(postId);
              postRef.update({likeCount: admin.firestore.FieldValue.increment(1)}).then({
                  const like = {
                      userHandle: req.user.userHandle,
                      postId: postId,
                      likedAt: new Date().toISOString()
                  };
                  db.collection('likes').add(like).then({
                      return res.json({message: `Successfully liked ${postId}`});
                  });
              });
          }
      })
      .catch((err) => {
            console.error(err);
            return res.status(500).json({error: err});
      });
}

Hope this helps.


问:
Why can't we pass arithmetic expression in range in for loop in python
I am getting an error as 'float' object cannot be interpreted as an integer</p>

```<code>num=5
for x in range(num/2):
     print("hello")
</code>```

答:
You should use integer division

num=5
for x in range(num//2):
     print("hello")
```

range does not support float input. If you want to use floating value, consider using numpy's arange.

Body:
I am getting an error as 'float' object cannot be interpreted as an integer

num=5
for x in range(num/2):
     print("hello")

Body:
You should use integer division

num=5
for x in range(num//2):
     print("hello")

range does not support float input. If you want to use floating value, consider using numpy's arange.


问:
Xamarin forms: Xamarin.Plugin.FilePicker is not working on ios
I am using Xamarin.Plugin.FilePicker to choose a file from the device.

Following is my code for picking a file from device:

```<code>var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
    filename_label.Text = file.FileName;
}
</code>```

But this is not working on ios platform (Working fine on android and windows). Getting the below exception when running on ios simulator:

System.NotImplementedException has been thrown.
  This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

What I am missing on the ios part? Is this package only for android and windows?

答:
System.NotImplementedException has been thrown. This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

The error probably caused by the version of Xamarin.Forms or Mono SDK could not match with the version of the plugin . In your case , the latest version of plugin is 2.1.41. Which is released  7 days ago . Maybe it is still a beta version when you install it . So you could uninstall it and install an older version like 2.1.34 .

Body:
I am using Xamarin.Plugin.FilePicker to choose a file from the device.

Following is my code for picking a file from device:

var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
    filename_label.Text = file.FileName;
}

But this is not working on ios platform (Working fine on android and windows). Getting the below exception when running on ios simulator:

System.NotImplementedException has been thrown.
  This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

What I am missing on the ios part? Is this package only for android and windows?


答:
add
top:0;
in #map. this will stick the page at the top. This way you can user css position.

Body:
I'm trying to make  with google maps reference stick on the right side of my page I've tried this code still scrolls with the rest of the page

#map{
position: -webkit-sticky;
  position: sticky;
}


问:
Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
I'm using Angular 8

My routing is defined like

app-routing.module.ts

```<code>const appRoutes: Routes = [
  {
    path: '',
    loadChildren: () => import('./@shared/layouts/dashboard-layout/dashboard-layout.module').then(m => m.DashboardLayoutModule)
  },
  {
    path: '',
    loadChildren: () => import('./@shared/layouts/auth-layout/auth-layout.module').then(m => m.AuthLayoutModule),
  },
  {path: '404', component: NotFoundComponent},
  {path: '**', redirectTo: '/404'}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

DashboardLayoutModule -> dashboard-layout.routing.ts

```<code>const routes: Routes = [
  {
    path: '', redirectTo: 'qr/create', pathMatch: 'full',
  },
  {
    path: 'qr', redirectTo: 'qr/create', pathMatch: 'full'
  },
  {
    path: '', component: DashboardLayoutComponent, children: [
      {
        path: 'settings', loadChildren: () => import('../../../views/settings/settings.module').then(m => m.SettingsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'qr/create', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr/create/:id/', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/designer/designer.module').then(m => m.DesignerModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/qr/qr.module').then(m => m.QrModule)
      },
      {
        path: 'analytics', loadChildren: () => import('../../../views/analytics/analytics.module').then(m => m.AnalyticsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'leads', loadChildren: () => import('../../../views/leads/leads.module').then(m => m.LeadsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'profile', loadChildren: () => import ('../../../views/profile/profile.module').then(m => m.ProfileModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'support', loadChildren: () => import ('../../../views/support/support.module').then(m => m.SupportModule)
      },
      {
        path: 'subscription', loadChildren: () => import ('../../../views/subscription/subscription.module').then(m => m.SubscriptionModule),
        canActivate: [AuthGuardService]
      }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ]
})
export class DashboardLayoutRouting {
}

</code>```

When production builds locally and even in development, everything is working fine. But on the production server, the navigation is not working and giving error

```<code>ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet
    at vn.activateWith (main-es2015.8496fab846e7208312ae.js:formatted:38396)
    at _e.activateRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36807)
    at main-es2015.8496fab846e7208312ae.js:formatted:36766
    at Array.forEach (<anonymous>)
    at _e.activateChildRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36765)
    at _e.activateRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36811)
    at main-es2015.8496fab846e7208312ae.js:formatted:36766
    at Array.forEach (<anonymous>)
    at _e.activateChildRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36765)
    at _e.activate (main-es2015.8496fab846e7208312ae.js:formatted:36711)
    at o.project (main-es2015.8496fab846e7208312ae.js:formatted:37865)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38949)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at l._next (main-es2015.8496fab846e7208312ae.js:formatted:42254)
    at l.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:31944)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at t._subscribe (main-es2015.8496fab846e7208312ae.js:formatted:39462)
    at t._trySubscribe (main-es2015.8496fab846e7208312ae.js:formatted:22325)
    at t.subscribe (main-es2015.8496fab846e7208312ae.js:formatted:22317)
    at s.call (main-es2015.8496fab846e7208312ae.js:formatted:38936)
    at t.subscribe (main-es2015.8496fab846e7208312ae.js:formatted:22317)
    at o (main-es2015.8496fab846e7208312ae.js:formatted:30375)
    at c._innerSub (main-es2015.8496fab846e7208312ae.js:formatted:31927)
    at c._next (main-es2015.8496fab846e7208312ae.js:formatted:31919)
    at c.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:31944)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at l._next (main-es2015.8496fab846e7208312ae.js:formatted:42254)
    at l.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:512)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at w._complete (main-es2015.8496fab846e7208312ae.js:formatted:35438)
    at w.complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at H._complete (main-es2015.8496fab846e7208312ae.js:formatted:739)
    at H.complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at c._complete (main-es2015.8496fab846e7208312ae.js:formatted:508)
    at complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at t._subscribe (main-es2015.8496fab846e7208312ae.js:formatted:39463)
    at v (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at v (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at polyfills-es2015.7cc86a7ad57851d5c4e3.js:1
    at a.invokeTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at Object.onInvokeTask (main-es2015.8496fab846e7208312ae.js:formatted:12546)
    at a.invokeTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at s.runTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at _ (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
</code>```

<router-outlet></router-outlet> is in two files

app.component.html

dashboard-layout.component.html

答:
Changes required :-

DashboardLayoutModule -> dashboard-layout.routing.ts

```<code>const routes: Routes = [
  {
    path: '', component: DashboardLayoutComponent, children: [
      {
         path: '', redirectTo: 'qr/create', pathMatch: 'full',
      },
      {
         path: 'qr', redirectTo: 'qr/create', pathMatch: 'full'
      }
      {
        path: 'settings', loadChildren: () => import('../../../views/settings/settings.module').then(m => m.SettingsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'qr/create', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr/create/:id/', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/designer/designer.module').then(m => m.DesignerModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/qr/qr.module').then(m => m.QrModule)
      },
      {
        path: 'analytics', loadChildren: () => import('../../../views/analytics/analytics.module').then(m => m.AnalyticsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'leads', loadChildren: () => import('../../../views/leads/leads.module').then(m => m.LeadsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'profile', loadChildren: () => import ('../../../views/profile/profile.module').then(m => m.ProfileModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'support', loadChildren: () => import ('../../../views/support/support.module').then(m => m.SupportModule)
      },
      {
        path: 'subscription', loadChildren: () => import ('../../../views/subscription/subscription.module').then(m => m.SubscriptionModule),
        canActivate: [AuthGuardService]
      }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ]
})
export class DashboardLayoutRouting {
}
</code>```

Body:
I'm using Angular 8

My routing is defined like

app-routing.module.ts

const appRoutes: Routes = [
  {
    path: '',
    loadChildren: () => import('./@shared/layouts/dashboard-layout/dashboard-layout.module').then(m => m.DashboardLayoutModule)
  },
  {
    path: '',
    loadChildren: () => import('./@shared/layouts/auth-layout/auth-layout.module').then(m => m.AuthLayoutModule),
  },
  {path: '404', component: NotFoundComponent},
  {path: '**', redirectTo: '/404'}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

DashboardLayoutModule -> dashboard-layout.routing.ts

const routes: Routes = [
  {
    path: '', redirectTo: 'qr/create', pathMatch: 'full',
  },
  {
    path: 'qr', redirectTo: 'qr/create', pathMatch: 'full'
  },
  {
    path: '', component: DashboardLayoutComponent, children: [
      {
        path: 'settings', loadChildren: () => import('../../../views/settings/settings.module').then(m => m.SettingsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'qr/create', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr/create/:id/', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/designer/designer.module').then(m => m.DesignerModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/qr/qr.module').then(m => m.QrModule)
      },
      {
        path: 'analytics', loadChildren: () => import('../../../views/analytics/analytics.module').then(m => m.AnalyticsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'leads', loadChildren: () => import('../../../views/leads/leads.module').then(m => m.LeadsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'profile', loadChildren: () => import ('../../../views/profile/profile.module').then(m => m.ProfileModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'support', loadChildren: () => import ('../../../views/support/support.module').then(m => m.SupportModule)
      },
      {
        path: 'subscription', loadChildren: () => import ('../../../views/subscription/subscription.module').then(m => m.SubscriptionModule),
        canActivate: [AuthGuardService]
      }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ]
})
export class DashboardLayoutRouting {
}

When production builds locally and even in development, everything is working fine. But on the production server, the navigation is not working and giving error

ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet
    at vn.activateWith (main-es2015.8496fab846e7208312ae.js:formatted:38396)
    at _e.activateRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36807)
    at main-es2015.8496fab846e7208312ae.js:formatted:36766
    at Array.forEach (<anonymous>)
    at _e.activateChildRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36765)
    at _e.activateRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36811)
    at main-es2015.8496fab846e7208312ae.js:formatted:36766
    at Array.forEach (<anonymous>)
    at _e.activateChildRoutes (main-es2015.8496fab846e7208312ae.js:formatted:36765)
    at _e.activate (main-es2015.8496fab846e7208312ae.js:formatted:36711)
    at o.project (main-es2015.8496fab846e7208312ae.js:formatted:37865)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38949)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at l._next (main-es2015.8496fab846e7208312ae.js:formatted:42254)
    at l.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:31944)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at t._subscribe (main-es2015.8496fab846e7208312ae.js:formatted:39462)
    at t._trySubscribe (main-es2015.8496fab846e7208312ae.js:formatted:22325)
    at t.subscribe (main-es2015.8496fab846e7208312ae.js:formatted:22317)
    at s.call (main-es2015.8496fab846e7208312ae.js:formatted:38936)
    at t.subscribe (main-es2015.8496fab846e7208312ae.js:formatted:22317)
    at o (main-es2015.8496fab846e7208312ae.js:formatted:30375)
    at c._innerSub (main-es2015.8496fab846e7208312ae.js:formatted:31927)
    at c._next (main-es2015.8496fab846e7208312ae.js:formatted:31919)
    at c.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:31944)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at l._next (main-es2015.8496fab846e7208312ae.js:formatted:42254)
    at l.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at c.notifyNext (main-es2015.8496fab846e7208312ae.js:formatted:512)
    at i._next (main-es2015.8496fab846e7208312ae.js:formatted:538)
    at i.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at o._next (main-es2015.8496fab846e7208312ae.js:formatted:38953)
    at o.next (main-es2015.8496fab846e7208312ae.js:formatted:717)
    at w._complete (main-es2015.8496fab846e7208312ae.js:formatted:35438)
    at w.complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at H._complete (main-es2015.8496fab846e7208312ae.js:formatted:739)
    at H.complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at c._complete (main-es2015.8496fab846e7208312ae.js:formatted:508)
    at complete (main-es2015.8496fab846e7208312ae.js:formatted:725)
    at t._subscribe (main-es2015.8496fab846e7208312ae.js:formatted:39463)
    at v (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at v (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at polyfills-es2015.7cc86a7ad57851d5c4e3.js:1
    at a.invokeTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at Object.onInvokeTask (main-es2015.8496fab846e7208312ae.js:formatted:12546)
    at a.invokeTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at s.runTask (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)
    at _ (polyfills-es2015.7cc86a7ad57851d5c4e3.js:1)

<router-outlet></router-outlet> is in two files

app.component.html

dashboard-layout.component.html

Body:
Changes required :-

DashboardLayoutModule -> dashboard-layout.routing.ts

const routes: Routes = [
  {
    path: '', component: DashboardLayoutComponent, children: [
      {
         path: '', redirectTo: 'qr/create', pathMatch: 'full',
      },
      {
         path: 'qr', redirectTo: 'qr/create', pathMatch: 'full'
      }
      {
        path: 'settings', loadChildren: () => import('../../../views/settings/settings.module').then(m => m.SettingsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'qr/create', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr/create/:id/', loadChildren: () => import('../../../views/create-qr/create-qr.module').then(m => m.CreateQrModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/designer/designer.module').then(m => m.DesignerModule)
      },
      {
        path: 'qr', loadChildren: () => import('../../../views/qr/qr.module').then(m => m.QrModule)
      },
      {
        path: 'analytics', loadChildren: () => import('../../../views/analytics/analytics.module').then(m => m.AnalyticsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'leads', loadChildren: () => import('../../../views/leads/leads.module').then(m => m.LeadsModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'profile', loadChildren: () => import ('../../../views/profile/profile.module').then(m => m.ProfileModule),
        canActivate: [AuthGuardService]
      },
      {
        path: 'support', loadChildren: () => import ('../../../views/support/support.module').then(m => m.SupportModule)
      },
      {
        path: 'subscription', loadChildren: () => import ('../../../views/subscription/subscription.module').then(m => m.SubscriptionModule),
        canActivate: [AuthGuardService]
      }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ]
})
export class DashboardLayoutRouting {
}


问:
TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'
Hey Guys I have an Error in Python Tkinter.

I wanted to make an simple Calculator:

```<code>from tkinter import *
from tkinter import ttk

intery=ttk.Entry(root, width=8)
intery.pack()
intery2=ttk.Entry(root, width=8)
intery2.pack()

def su():
    intery.config(intery + intery2)
    print(su)

btn=ttk.Button(root, text="+", command=su)
btn.pack()
</code>```

But I encounter an Error:

```<code>TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'
</code>```

答:
try with</p>

```<code>intery.config(int(intery) + int(intery2))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey Guys I have an Error in Python Tkinter.

I wanted to make an simple Calculator:

from tkinter import *
from tkinter import ttk

intery=ttk.Entry(root, width=8)
intery.pack()
intery2=ttk.Entry(root, width=8)
intery2.pack()

def su():
    intery.config(intery + intery2)
    print(su)

btn=ttk.Button(root, text="+", command=su)
btn.pack()

But I encounter an Error:

TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'

Body:
try with

intery.config(int(intery) + int(intery2))


问:
BeautifulSoup children of div
I am trying to find the children div for a specific div on a website using beautifulSoup.

I have inspired myself from this answer : Beautiful Soup find children for particular div

However, when I want to retrieve all the content of the divs with class='row' which has a parent div with class="container search-results-wrapper endless_page_template" as seen below: My problem is that it only retrieves the content of the first div class='row'.

I am using the following code :

```<code>    boatContainer= page_soup.find_all('div', class_='container search-results-wrapper endless_page_template')
    for row in boatContainer:
        all_boats = row.find_all('div', class_='row')
        for boat in all_boats:
           print(boat.text)
</code>```

I apply this on this website.
What can I do so that my solution retrieves the data of the divs from class='row' which belong in the div class='container search-results-wrapper endless_page_template' ?

答:
Use response.content instead of response.text.

you're also not requesting the correct url in your code. https://www.sailogy.com/en/search/?search_where=ibiza&trip_date=2020-06-06&weeks_count=1&skipper=False&search_src=home only displays a single boat hence you're code is only returning one row.

Use https://www.sailogy.com/en/search/?search_where=ibiza&trip_date=2020-06-06&weeks_count=1&guests_count=&order_by=-rank&is_roundtrip=&coupon_code=&skipper=None instead in this case

You'll probally find use in adjusting the url parameters to filter boats at some point !

Title: BeautifulSoup children of div

Body:
I am trying to find the children div for a specific div on a website using beautifulSoup.

I have inspired myself from this answer : Beautiful Soup find children for particular div

However, when I want to retrieve all the content of the divs with class='row' which has a parent div with class="container search-results-wrapper endless_page_template" as seen below: My problem is that it only retrieves the content of the first div class='row'.

I am using the following code :

    boatContainer= page_soup.find_all('div', class_='container search-results-wrapper endless_page_template')
    for row in boatContainer:
        all_boats = row.find_all('div', class_='row')
        for boat in all_boats:
           print(boat.text)

I apply this on this website.
What can I do so that my solution retrieves the data of the divs from class='row' which belong in the div class='container search-results-wrapper endless_page_template' ?


问:
Change \itemize bullet point after certain slide in nestled \itemize environment
I want to change the bullet point symbol of certain items in my list after a certain slide.

A solution to a similar problem, but without nestled \itemize environments, was posted here: https://tex.stackexchange.com/questions/424011/change-beamer-itemize-symbol-and-overlay

The list looks like this:

```<code>\documentclass[9pt,aspectratio=169]{beamer}

\newenvironment{redenv}{\only{\setbeamercolor{local structure}{fg=red}}}{}

\begin{itemize}
    \item<1-|red@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|red@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{document}
</code>```

I want to change the symbol for Item 1 and Item 3 after a certain pause. This solution works only for Item 1, but not Item 3.

Edit:

Turns out I copied the example wrongly here, but not in my actual document. Instead I found the real culprit: My document uses a beamercolor.sty sheet that defines the color of the bullet points:

```<code>\setbeamercolor{item}{parent=local structure}
\setbeamercolor{subitem}{parent=item, fg=gray}
\setbeamercolor{subsubitem}{parent=subitem}
</code>```

So, when I delete the fg=gray, it works as indended. But I want the gray color as default and only change the color in places I choose. How can reconcile both coloring methods?

答:
You are missing the fg= in your colour definition:

```<code>\documentclass[9pt,aspectratio=169]{beamer}

\newenvironment{redenv}{\only{\setbeamercolor{local structure}{fg=red}}}{}

\begin{document}
\begin{frame}

\begin{itemize}
    \item<1-|red@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|red@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{frame}
\end{document}
</code>```

Or if you don't mind that the text also changes colour, you could use alert:

```<code>\documentclass[9pt,aspectratio=169]{beamer}

\begin{document}
\begin{frame}

\begin{itemize}
    \item<1-|alert@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|alert@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{frame}
\end{document}
</code>```

Body:
I want to change the bullet point symbol of certain items in my list after a certain slide.

A solution to a similar problem, but without nestled \itemize environments, was posted here: https://tex.stackexchange.com/questions/424011/change-beamer-itemize-symbol-and-overlay

The list looks like this:

\documentclass[9pt,aspectratio=169]{beamer}

\newenvironment{redenv}{\only{\setbeamercolor{local structure}{fg=red}}}{}

\begin{itemize}
    \item<1-|red@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|red@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{document}

I want to change the symbol for Item 1 and Item 3 after a certain pause. This solution works only for Item 1, but not Item 3.

Edit:

Turns out I copied the example wrongly here, but not in my actual document. Instead I found the real culprit: My document uses a beamercolor.sty sheet that defines the color of the bullet points:

\setbeamercolor{item}{parent=local structure}
\setbeamercolor{subitem}{parent=item, fg=gray}
\setbeamercolor{subsubitem}{parent=subitem}

So, when I delete the fg=gray, it works as indended. But I want the gray color as default and only change the color in places I choose. How can reconcile both coloring methods?

Body:
You are missing the fg= in your colour definition:

\documentclass[9pt,aspectratio=169]{beamer}

\newenvironment{redenv}{\only{\setbeamercolor{local structure}{fg=red}}}{}

\begin{document}
\begin{frame}

\begin{itemize}
    \item<1-|red@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|red@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{frame}
\end{document}

Or if you don't mind that the text also changes colour, you could use alert:

\documentclass[9pt,aspectratio=169]{beamer}

\begin{document}
\begin{frame}

\begin{itemize}
    \item<1-|alert@3-> Item 1
    \item Item 2
    \begin{itemize}
        \item<2-|alert@3-> Item 3
    \end{itemize}
    \item Item 4
\end{itemize}

\end{frame}
\end{document}


问:
Techniques for dealing with anemic domain model
I've read some of the questions regarding anemic domain models and separation of concerns.  What are the best techniques for performing/attaching domain logic on anemic domain objects?  At my job, we have a pretty anemic model, and we're currently using "helper" classes to perform the database/business logic on the domain objects.  For example:

```<code>public class Customer
{
    public string Name {get;set;}
    public string Address {get;set;}
}

public class Product
{
    public string Name {get;set;}
    public decimal Price {get;set;}
}

public class StoreHelper
{
    public void PurchaseProduct(Customer c, Product p)
    {
         // Lookup Customer and Product in db
         // Create records for purchase
         // etc.
    }
}
</code>```

When the app needs to do a purchase, it would create the StoreHelper, and call the method on the domain objects.  To me, it would make sense for the Customer/Product to know how to save itself to a repository, but you probably wouldn't want Save() methods on the domain objects.  It would also make sense for a method like Customer.Purchase(Product), but that is putting domain logic on the entity.

Here are some techniques I've come across, not sure which are good/bad:

Customer and Product inherit from an "Entity" class, which provides the basic CRUD operations in a generic fashion (using an ORM maybe).

Pros: Each data object would automatically get the CRUD operations, but are then tied to the database/ORM

Cons: This does not solve the problem of business operations on the objects, and also ties all domain objects to a base Entity that might not be appropriate

Use helper classes to handle the CRUD operations and business logic

Does it make sense to have DAOs for the "pure database" operations, and separate business helpers for the more business-specific operations?

Is it better to use non-static or static helper classes for this?

Pros: domain objects are not tied to any database/business logic (completely anemic)

Cons: not very OO, not very natural to use helpers in application code (looks like C code)

Use the Double Dispatch technique where the entity has methods to save to an arbitrary repository

Pros: better separation of concerns

Cons: entities have some extra logic attached (although it's decoupled)

In C# 3.0, you could use extension methods to attach the CRUD/business methods to a domain object without touching it

Is this a valid approach?  What are pros/cons?

Other techniques?

What are the best techniques for handling this?  I'm pretty new to DDD (I'm reading the Evans book - so maybe that will open my eyes)

答:
Martin Fowler has written a lot about domain models, including anemic domain models. He also has brief descriptions (and UML class diagrams) of many design patterns for domain models and databases that might be helpful: Catalog of "Patterns of Enterprise Application Architecture".

I would suggest looking at the Active Record and Data Mapper patterns. From the description of your problem, it sounds like your helper classes contain both domain/business rules and database implementation details.

The Active Record would move the helper's domain logic and database code into the other domain objects (like your Entity base class). The Data Mapper would move the helper's domain logic into the domain objects and the database code into a separate map object. Either approach would be more object-oriented than procedural-style helper classes.

Eric Evans' "Domain Driven Design" book is excellent. It gets a bit dry, but is definitely worth it. InfoQ has a "Domain Driven Design Quickly" mini-book that is a good introduction to Evans' book. Plus "Domain Driven Design Quickly" is available as a free PDF.

OwnerDisplayName: Andy White

ContentLicense: CC BY-SA 2.5

Body:
I've read some of the questions regarding anemic domain models and separation of concerns.  What are the best techniques for performing/attaching domain logic on anemic domain objects?  At my job, we have a pretty anemic model, and we're currently using "helper" classes to perform the database/business logic on the domain objects.  For example:

public class Customer
{
    public string Name {get;set;}
    public string Address {get;set;}
}

public class Product
{
    public string Name {get;set;}
    public decimal Price {get;set;}
}

public class StoreHelper
{
    public void PurchaseProduct(Customer c, Product p)
    {
         // Lookup Customer and Product in db
         // Create records for purchase
         // etc.
    }
}

When the app needs to do a purchase, it would create the StoreHelper, and call the method on the domain objects.  To me, it would make sense for the Customer/Product to know how to save itself to a repository, but you probably wouldn't want Save() methods on the domain objects.  It would also make sense for a method like Customer.Purchase(Product), but that is putting domain logic on the entity.

Here are some techniques I've come across, not sure which are good/bad:

Customer and Product inherit from an "Entity" class, which provides the basic CRUD operations in a generic fashion (using an ORM maybe).

Pros: Each data object would automatically get the CRUD operations, but are then tied to the database/ORM

Cons: This does not solve the problem of business operations on the objects, and also ties all domain objects to a base Entity that might not be appropriate

Use helper classes to handle the CRUD operations and business logic

Does it make sense to have DAOs for the "pure database" operations, and separate business helpers for the more business-specific operations?

Is it better to use non-static or static helper classes for this?

Pros: domain objects are not tied to any database/business logic (completely anemic)

Cons: not very OO, not very natural to use helpers in application code (looks like C code)

Use the Double Dispatch technique where the entity has methods to save to an arbitrary repository

Pros: better separation of concerns

Cons: entities have some extra logic attached (although it's decoupled)

In C# 3.0, you could use extension methods to attach the CRUD/business methods to a domain object without touching it

Is this a valid approach?  What are pros/cons?

Other techniques?

What are the best techniques for handling this?  I'm pretty new to DDD (I'm reading the Evans book - so maybe that will open my eyes)

OwnerDisplayName: cpeterso


问:
jQuery hover effect
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

```<code>.bgHvr {
  background-color: #FFFACD;
}
</code>```

The only way I know how to add the hover effect I desire is:

```<code>jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});
</code>```

UPDATE:

After some more help I found out a simpler way of a hover effect:

```<code>$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});
</code>```

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

答:
Best way I know how and fully compatible with all browsers.

On an unordered list -

JS

```<code>$('ul').delegate('li', 'mouseenter mouseleave', function() {
  $(this).toggleClass('hover');
});
</code>```

CSS

```<code>li.hover {
  background-color: #CCC;
}
</code>```

Title: jQuery hover effect

Body:
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

.bgHvr {
  background-color: #FFFACD;
}

The only way I know how to add the hover effect I desire is:

jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});

UPDATE:

After some more help I found out a simpler way of a hover effect:

$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

Body:
Best way I know how and fully compatible with all browsers.

On an unordered list -

JS

$('ul').delegate('li', 'mouseenter mouseleave', function() {
  $(this).toggleClass('hover');
});

CSS

li.hover {
  background-color: #CCC;
}


问:
Textbox caret isn't moving WPF C#
I am trying to move the textbox's caret to the start of the textbox when clicking on it with no success.
I tried multiple approaches and was always getting the same result of the caret position not changing, is there anything in my code that could prevent the caret moving? is there a certain event I need to use?

This is my XAML:

```<code><TextBox Name="roomNameBox"
         Text ="Room Name"
         Margin="23,0,0,0"
         GotFocus="TextBox_GotFocus"
         LostFocus="TextBox_LostFocus"
         TextChanged="TextBox_TextChanged">
</code>```

And this is my code:

```<code>    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            box.CaretIndex = 0;
        }
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Opacity == 0.5)
            {
                box.Opacity = 1;
                box.CaretBrush = Brushes.White;
            }
        }
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Text == "")
            {
                if (box.Name == roomNameBox.Name)
                {
                    box.Text = Constants.ROOM_NAME_HINT;
                }
                else if (box.Name == timePerQuestionBox.Name)
                {
                    box.Text = Constants.TIME_PER_QUESTION_HINT;
                }
                else if (box.Name == maxPlayersBox.Name)
                {
                    box.Text = Constants.MAX_PLAYERS_HINT;
                }

                box.Opacity = 0.5;
                box.CaretBrush = new SolidColorBrush(Color.FromRgb(150, 169, 198));
            }
        }
    }
</code>```

Thanks in advance for any help

Edit: The code works only when I set a breakpoint and step the code

答:
Set box.CaretIndex = 0; in the GotFocus events for Keyboard and Mouse. See the CaretIndex property here.

Setting the index to 0 is translated to placing the caret before the first character (at index 0) of the text string content.

An event is firing after the GotFocus that is placing the caret at the end. The solution is to implement these two events:

<TextBox
Keyboard.GotKeyboardFocus="TextBox_GotKeyboardFocus" Mouse.GotMouseCapture="TextBox_GotMouseCapture"
Text="test"></TextBox>
```
```private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}

private void TextBox_GotMouseCapture(object sender, MouseEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}
```

Title: Textbox caret isn't moving WPF C#

Body:
I am trying to move the textbox's caret to the start of the textbox when clicking on it with no success.
I tried multiple approaches and was always getting the same result of the caret position not changing, is there anything in my code that could prevent the caret moving? is there a certain event I need to use?

This is my XAML:

<TextBox Name="roomNameBox"
         Text ="Room Name"
         Margin="23,0,0,0"
         GotFocus="TextBox_GotFocus"
         LostFocus="TextBox_LostFocus"
         TextChanged="TextBox_TextChanged">

And this is my code:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            box.CaretIndex = 0;
        }
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Opacity == 0.5)
            {
                box.Opacity = 1;
                box.CaretBrush = Brushes.White;
            }
        }
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Text == "")
            {
                if (box.Name == roomNameBox.Name)
                {
                    box.Text = Constants.ROOM_NAME_HINT;
                }
                else if (box.Name == timePerQuestionBox.Name)
                {
                    box.Text = Constants.TIME_PER_QUESTION_HINT;
                }
                else if (box.Name == maxPlayersBox.Name)
                {
                    box.Text = Constants.MAX_PLAYERS_HINT;
                }

                box.Opacity = 0.5;
                box.CaretBrush = new SolidColorBrush(Color.FromRgb(150, 169, 198));
            }
        }
    }

Thanks in advance for any help

Edit: The code works only when I set a breakpoint and step the code

Body:
Set box.CaretIndex = 0; in the GotFocus events for Keyboard and Mouse. See the CaretIndex property here.

Setting the index to 0 is translated to placing the caret before the first character (at index 0) of the text string content.

An event is firing after the GotFocus that is placing the caret at the end. The solution is to implement these two events:

<TextBox
Keyboard.GotKeyboardFocus="TextBox_GotKeyboardFocus" Mouse.GotMouseCapture="TextBox_GotMouseCapture"
Text="test"></TextBox>

private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}

private void TextBox_GotMouseCapture(object sender, MouseEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}


问:
Send AJAX data to Node.js
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

```<code><script type="text/javascript">
    $(document).ready(function(){
    var selectElement = document.getElementById('selectDetails');
    var selectValue='';
        $.ajax({
                 url: "http://localhost:8070/api/route1",
                 type: 'POST',
                 dataType:'json',

                 success: function(res) {
                     console.log(res);
                     console.log(res.content);
                     $.each(res.content, function(key,value) {
                        console.log(value);
                        selectElement.options[selectElement.options.length] = new Option(value.hostname+":"+value.port);
                    });
                    $("#myButton").click(function(){
                        var selectValue = document.getElementById("selectDetails").value;
                        console.log(selectValue);
                    });
                },
                data: { selectValue: selectValue}
            });
        });
</script>
</code>```

app.js

```<code>router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});
</code>```

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.

答:
note that your url is: "http://localhost:8070/api/monitor"
and in your app.js file you're trying to post to /route1</p>

Title: Send AJAX data to Node.js

Body:
Unable to send data to Node.js from my HTML/AJAX, I have variable selectValue which I want to send to my Node server. While making use of data: { selectValue: selectValue} does not help.

index.html

app.js

router.post('/route1', function(req, res){
    var selValue= req.body.selectValue;
    console.log("Select Value"+selValue);
});

console.log("Select Value"+selValue); give an undefined value. How do I send the value of selectValue to my node server.