问:
GraphQLServer union types "Abstract type N must resolve to an Object type at runtime" error
Given a GraphQL union return type:

```<code>union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest
</code>```

meant to be returned by a given resolver:

```<code>type Query {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}
</code>```

I'm getting these warnings or errors regarding a __resolveType or __isTypeOf function:

```<code>Abstract type N must resolve to an Object type at runtime for field Query.getBankAccounts with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the N type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'
</code>```

I've searched for days in github issues and SO questions looking to resolve this error.

Implementing __resolveType or __isTypeOf in my resolvers is not working:

```<code>export const Query = {
  getBankAccounts: (parent, args, context: IContext, info) => {
    return {
      __isTypeOf(obj) { // OR __resolveType, none of them work
        return `GetAccountsResponse`;
      },
      accounts: []
    };
  },
};
</code>```

答:
Your resolver map is not set up correctly.

The resolver map passed to ApolloServer (or makeExecutableSchema) should should be an object whose keys are type names in your schema, with each key mapping to another object whose keys are field names on that type. Each field name then maps to a resolver function.

```<code>const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
}
</code>```

You use the same resolver map to pass in the resolveType function for a union or interface. The pattern is the same, but the name of the type is the name of the union or interface and instead of a field name, the key is __resolveType:

```<code>const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
  SomeUnion: {
    __resolveType: (parent) => { ... },
  }
}
</code>```

The resolveType function should always return a string that matches the name of an existing object type in your schema.

If you use __isTypeOf instead of __resolveType, then this will look a bit different because the isTypeOf function is associated with a particular object type, not the interface or union. This is all shown in the docs. So the resolver map looks like this:

```<code>const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
    __isTypeOf: (parent) => { ... },
  },
}
</code>```

__isTypeOf should always return either true or false, depending on whether the passed in object is in fact that type.

You only need to use either __resolveType or __isTypeOf. If you use __isTypeOf, you have to add it to every possible object type in the union or interface.

Body:
Given a GraphQL union return type:

union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest

meant to be returned by a given resolver:

type Query {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}

I'm getting these warnings or errors regarding a __resolveType or __isTypeOf function:

Abstract type N must resolve to an Object type at runtime for field Query.getBankAccounts with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the N type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'

I've searched for days in github issues and SO questions looking to resolve this error.

Implementing __resolveType or __isTypeOf in my resolvers is not working:

export const Query = {
  getBankAccounts: (parent, args, context: IContext, info) => {
    return {
      __isTypeOf(obj) { // OR __resolveType, none of them work
        return `GetAccountsResponse`;
      },
      accounts: []
    };
  },
};

Body:
Your resolver map is not set up correctly.

The resolver map passed to ApolloServer (or makeExecutableSchema) should should be an object whose keys are type names in your schema, with each key mapping to another object whose keys are field names on that type. Each field name then maps to a resolver function.

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
}

You use the same resolver map to pass in the resolveType function for a union or interface. The pattern is the same, but the name of the type is the name of the union or interface and instead of a field name, the key is __resolveType:

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
  },
  SomeUnion: {
    __resolveType: (parent) => { ... },
  }
}

The resolveType function should always return a string that matches the name of an existing object type in your schema.

If you use __isTypeOf instead of __resolveType, then this will look a bit different because the isTypeOf function is associated with a particular object type, not the interface or union. This is all shown in the docs. So the resolver map looks like this:

const resolvers = {
  SomeType: {
    someField: (parent, args, context, info) => { ... },
    __isTypeOf: (parent) => { ... },
  },
}

__isTypeOf should always return either true or false, depending on whether the passed in object is in fact that type.

You only need to use either __resolveType or __isTypeOf. If you use __isTypeOf, you have to add it to every possible object type in the union or interface.


来源: stackexchange

问:
Grafana: Integrating groups with LDAP
I need some help integrating Grafana and LDAP. Say I have a group in LDAP that needs to be mapped to Grafana organization, 'MyGroup'.
Does the below ldap.conf have the right configuration so that if user 'Rag Cho' is member of MyGroup, the user will become admin of MyGroup org in Grafana? I have tried the below config and the user is visible in Grafana but the user does not appear to be part of 'MyGroup' org in Grafana.

```<code>ldap entry:
dn: cn=MyGroup,ou=root
cn: MyGroup
objectClass: groupOfNames
member: cn=Rag Cho,ou=root
</code>```

Part of Grafana ldap.conf:

```<code>...
search_base_dns = ["ou=root"]
group_search_filter = "(&(objectClass=groupOfNames)(member=%s))"
group_search_base_dns = ["ou=root"]

[servers.attributes]
name = "givenName"
surname = "sn"
username = "uid"
member_of = "cn" # is cn value correct or should it be member?
email =  "mail"

[[servers.group_mappings]]
group_dn = "cn=MyGroup,ou=root"
org_role = "Admin"
...
</code>```

答:
The member_of attribute must be set to memberOf. Everything else looks valid.

Regarding your request

if user 'Rag Cho' is member of MyGroup, the user will become admin of MyGroup org in Grafana

you have to set org_id to the integer of MyGroup in Grafana to map Users of MyGroup (LDAP) to the admin role of MyGroup (Grafana)

```<code>[[servers.group_mappings]]
group_dn = "cn=MyGroup,ou=root"
org_role = "Admin"
org_id   = 23
</code>```

The Grafana documentation is quite good. Maybe you should have a look at the examples there.

ContentLicense: CC BY-SA 3.0

Title: Grafana: Integrating groups with LDAP

Body:
I need some help integrating Grafana and LDAP. Say I have a group in LDAP that needs to be mapped to Grafana organization, 'MyGroup'.
Does the below ldap.conf have the right configuration so that if user 'Rag Cho' is member of MyGroup, the user will become admin of MyGroup org in Grafana? I have tried the below config and the user is visible in Grafana but the user does not appear to be part of 'MyGroup' org in Grafana.

ldap entry:
dn: cn=MyGroup,ou=root
cn: MyGroup
objectClass: groupOfNames
member: cn=Rag Cho,ou=root

Part of Grafana ldap.conf:

...
search_base_dns = ["ou=root"]
group_search_filter = "(&(objectClass=groupOfNames)(member=%s))"
group_search_base_dns = ["ou=root"]

[servers.attributes]
name = "givenName"
surname = "sn"
username = "uid"
member_of = "cn" # is cn value correct or should it be member?
email =  "mail"

[[servers.group_mappings]]
group_dn = "cn=MyGroup,ou=root"
org_role = "Admin"
...

Body:
The member_of attribute must be set to memberOf. Everything else looks valid.

Regarding your request

if user 'Rag Cho' is member of MyGroup, the user will become admin of MyGroup org in Grafana

you have to set org_id to the integer of MyGroup in Grafana to map Users of MyGroup (LDAP) to the admin role of MyGroup (Grafana)

[[servers.group_mappings]]
group_dn = "cn=MyGroup,ou=root"
org_role = "Admin"
org_id   = 23

The Grafana documentation is quite good. Maybe you should have a look at the examples there.

ContentLicense: CC BY-SA 4.0


问:
How to parse dates in JSON request with NestJs @Body
I have a DTO that looks like this:

class PersonDto {
   readonly name: string;
   readonly birthDate: Date;
}
```

<p>My NestJs controller method looks like this:</p>

<pre class="lang-js prettyprint-override"><code>@Post
create(@Body() person: PersonDto) {
    console.log("New person with the following data:", person);
    // more logic here
}
</code>```

The JSON data that gets posted has birthDate as a string: "2020-01-15". How can I convert this string to a JavaScript Date object? I'd like to add the @IsDate class-validation to PersonDto but currently that would fail.

答:
I figured out how to use the global ValidationPipe with a Date property and the @IsDate() annotation:

The first step is to allow transformations like this (my bootstrap file as an example):

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({transform: true}));
  await app.listen(3000);
}
bootstrap();
```

<p>Then you need to annotate the DTO with the <code>@Type()</code> annotation:</p>

<pre class="lang-js prettyprint-override"><code>import { IsDate } from 'class-validator';
import { Type } from 'class-transformer';

class PersonDto {
   readonly name: string;
   @Type(() => Date)
   @IsDate()
   readonly birthDate: Date;
}
</code>```

Body:
I have a DTO that looks like this:

class PersonDto {
   readonly name: string;
   readonly birthDate: Date;
}

My NestJs controller method looks like this:

@Post
create(@Body() person: PersonDto) {
    console.log("New person with the following data:", person);
    // more logic here
}

The JSON data that gets posted has birthDate as a string: "2020-01-15". How can I convert this string to a JavaScript Date object? I'd like to add the @IsDate class-validation to PersonDto but currently that would fail.

Body:
I figured out how to use the global ValidationPipe with a Date property and the @IsDate() annotation:

The first step is to allow transformations like this (my bootstrap file as an example):

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({transform: true}));
  await app.listen(3000);
}
bootstrap();

Then you need to annotate the DTO with the @Type() annotation:

import { IsDate } from 'class-validator';
import { Type } from 'class-transformer';

class PersonDto {
   readonly name: string;
   @Type(() => Date)
   @IsDate()
   readonly birthDate: Date;
}


问:
How to perform update for this select query?
```<code>select * from xxhys_bill_site_m master, xxhys_bill_site_m_wk wk`
where master.bill_site_cd = wk.name`
and master.co_cd = wk.co_cd`
and SYSDATE between master.CUST_SITE_VALID_START_DT and NVL(master.CUST_SITE_VALID_END_DT,'3999/12/31')`
and master.co_cd NOT IN ('1012','3002','3004','3008','3009','3010','3011','3012','3015','3014','3016','3017,'3018','3019')`
and wk.ifid <> 'SPIJ0679X31';
</code>```

The select query above is quite difficult for me to convert into update statement, I performed such various of update query but not getting the same result from select statement.
I want to update those data being queried by the select statement above.

答:
Here is how you would update columns in table xxhys_bill_site_m.
For more info you will need to tell us which columns you wish to update.</p>

```<code>update xxhys_bill_site_m
set bill_site_cd = 'update value'
-- here you will put all the columns you want to update from table xxhys_bill_site_m
-- you will do it in the way I have shown in the code line above
where SYSDATE between xxhys_bill_site_m.CUST_SITE_VALID_START_DT and NVL(xxhys_bill_site_m.CUST_SITE_VALID_END_DT,'3999/12/31')
and xxhys_bill_site_m.co_cd NOT IN ('1012','3002','3004','3008','3009','3010','3011','3012','3015','3014','3016','3017','3018','3019')
and exists (select '1'
            from xxhys_bill_site_m_wk
            where xxhys_bill_site_m_wk.ifid <> 'SPIJ0679X31'
            and xxhys_bill_site_m_wk.name = xxhys_bill_site_m.bill_site_cd
            and xxhys_bill_site_m_wk.co_cd = xxhys_bill_site_m.co_cd)
</code>```

Body:
select * from xxhys_bill_site_m master, xxhys_bill_site_m_wk wk`
where master.bill_site_cd = wk.name`
and master.co_cd = wk.co_cd`
and SYSDATE between master.CUST_SITE_VALID_START_DT and NVL(master.CUST_SITE_VALID_END_DT,'3999/12/31')`
and master.co_cd NOT IN ('1012','3002','3004','3008','3009','3010','3011','3012','3015','3014','3016','3017,'3018','3019')`
and wk.ifid <> 'SPIJ0679X31';

The select query above is quite difficult for me to convert into update statement, I performed such various of update query but not getting the same result from select statement.
I want to update those data being queried by the select statement above.

Body:
Here is how you would update columns in table xxhys_bill_site_m.
For more info you will need to tell us which columns you wish to update.

update xxhys_bill_site_m
set bill_site_cd = 'update value'
-- here you will put all the columns you want to update from table xxhys_bill_site_m
-- you will do it in the way I have shown in the code line above
where SYSDATE between xxhys_bill_site_m.CUST_SITE_VALID_START_DT and NVL(xxhys_bill_site_m.CUST_SITE_VALID_END_DT,'3999/12/31')
and xxhys_bill_site_m.co_cd NOT IN ('1012','3002','3004','3008','3009','3010','3011','3012','3015','3014','3016','3017','3018','3019')
and exists (select '1'
            from xxhys_bill_site_m_wk
            where xxhys_bill_site_m_wk.ifid <> 'SPIJ0679X31'
            and xxhys_bill_site_m_wk.name = xxhys_bill_site_m.bill_site_cd
            and xxhys_bill_site_m_wk.co_cd = xxhys_bill_site_m.co_cd)


问:
Pretty-Print JSON in Java
I'm using json-simple and I need to pretty-print JSON data (make it more human readable).

I haven't been able to find this functionality within that library.
How is this commonly achieved?

答:
You can use small json library </p>

```<code>String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString("  ");
</code>```

Title: Pretty-Print JSON in Java

Body:
You can use small json library

String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString("  ");


问:
Flutter, the second animation controller is not animating, why?
I have two animation controllers using TickerProviderStateMixin the first animation is working smoothly while the second does not animate when I trigger it's forward method : Here are their declarations :

```<code>class HomeAnimator extends StatefulWidget {
  @override
  _HomeAnimatorState createState() => _HomeAnimatorState();
}

class _HomeAnimatorState extends State<HomeAnimator>
    with TickerProviderStateMixin {
  AnimationController _controller;
  AnimationController _signupctrl;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(duration: Duration(milliseconds: 900), vsync: this);
    _signupctrl =
        AnimationController(duration: Duration(milliseconds: 900), vsync: this);
    // _controller.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _signupctrl.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dahome(controllers: [_controller,_signupctrl]);
  }
}
</code>```

I have two files for the different set of animations :

-- Mahome_EnterAnimation: when clicked on sign-in button
here's a relevant piece :

```<code>class EntAnime {
  EntAnime(this.controller)
      : opanime = Tween<double>(begin: 1, end: 0).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        r_opanime = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        hfact = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),
</code>```

-- Mahome_SignupAnime: for when I press sign-up button

```<code>class SignupAnime {
  SignupAnime(this.controller):
  qopanime = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0.0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        qhfact = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0.5, 0.9, curve: Curves.fastOutSlowIn),
        ));

  final AnimationController controller;
  final Animation<double> qopanime;
  final Animation<double> qhfact;
}
</code>```

This is how I declared it :

```<code>class Dahome extends StatefulWidget {
  Dahome({Key key, this.title, @required List<AnimationController> controllers})
      : daanime = EntAnime(controllers[0]),
        signanime = SignupAnime(controllers[1]),
        super(key: key);
  final EntAnime daanime;
  final SignupAnime signanime;
  final String title;
  Dastate createState() => Dastate(daanime, signanime);
  // @override
}

class Dastate extends State<Dahome> {
  Dastate(this.maanime, this.loganime);
  final EntAnime maanime;
  final SignupAnime loganime;
...
</code>```

I called the forward methods in two different buttons:

The first one here and the second the same way:

```<code>RaisedButton(
    onPressed: () => {
       maanime.controller.forward()
       },
</code>```

答: Silly me, the problem was the animatedbuilder widget I had to change the animation parameter with the second controller

Body:
I have two animation controllers using TickerProviderStateMixin the first animation is working smoothly while the second does not animate when I trigger it's forward method : Here are their declarations :

class HomeAnimator extends StatefulWidget {
  @override
  _HomeAnimatorState createState() => _HomeAnimatorState();
}

class _HomeAnimatorState extends State<HomeAnimator>
    with TickerProviderStateMixin {
  AnimationController _controller;
  AnimationController _signupctrl;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(duration: Duration(milliseconds: 900), vsync: this);
    _signupctrl =
        AnimationController(duration: Duration(milliseconds: 900), vsync: this);
    // _controller.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _signupctrl.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dahome(controllers: [_controller,_signupctrl]);
  }
}

I have two files for the different set of animations :

-- Mahome_EnterAnimation: when clicked on sign-in button
here's a relevant piece :

class EntAnime {
  EntAnime(this.controller)
      : opanime = Tween<double>(begin: 1, end: 0).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        r_opanime = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        hfact = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn),
        )),

-- Mahome_SignupAnime: for when I press sign-up button

class SignupAnime {
  SignupAnime(this.controller):
  qopanime = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0.0, 0.5, curve: Curves.fastOutSlowIn),
        )),
        qhfact = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
          parent: controller,
          curve: Interval(0.5, 0.9, curve: Curves.fastOutSlowIn),
        ));

  final AnimationController controller;
  final Animation<double> qopanime;
  final Animation<double> qhfact;
}

This is how I declared it :

class Dahome extends StatefulWidget {
  Dahome({Key key, this.title, @required List<AnimationController> controllers})
      : daanime = EntAnime(controllers[0]),
        signanime = SignupAnime(controllers[1]),
        super(key: key);
  final EntAnime daanime;
  final SignupAnime signanime;
  final String title;
  Dastate createState() => Dastate(daanime, signanime);
  // @override
}

class Dastate extends State<Dahome> {
  Dastate(this.maanime, this.loganime);
  final EntAnime maanime;
  final SignupAnime loganime;
...

I called the forward methods in two different buttons:

The first one here and the second the same way:

RaisedButton(
    onPressed: () => {
       maanime.controller.forward()
       },


问:
Is it possible to create an object on a background thread with no reference on the main thread?
Equities trading application uses a class library for getting callbacks on stock quote updates, another class library for getting callbacks on order executions or cancelations. I currently have the callbacks execute in the thread pool. I start one background thread for each callback. The threads are very short lived and the work involved includes fetching the data and notifying the observers. Once observers are notified the background thread dies. When I have strategies subscribing to over 1000 actively traded symbols I get OutOfMemory exceptions.

How can I improve this design? I was thinking of starting two threads at the start, one for quotes, the other for executions, and creating each object on its respective threads. Then just have a shared object which allows adding and removing observers to the threads. But 1) how would you keep the thread alive to receive the callbacks? 2) How can you even have a callback object which is initialized on a thread with no reference on the main thread? Is this even possible?

Any help would be appreciated.

答:
What you've described is a general picture of your application.  In order to redesign your application we concrete requirements and at least a simplified model of how the participants interact with each other.  Your informal description is not precise enough to suggest a specific data structure and algorithm because without knowing all enough details we might omit something crucial and not meet your needs.

You are saying all the right words and you have a specific problem, out of memory, and you need to fix something.  Go back to prototyping.  Write a very small but brutally exercised program to demonstrate what you want to do.  Then scale it back up to your application.  It's much easier to design in the prototype size.

Edit:

Because you are running out of memory, the most likely reasons are that you have a memory leak or you simply have a near-real-time system with insufficient capacity to process the load you are experiencing.  A leak might be due to the usual suspects, e.g. not detaching event handlers which you can diagnose with memory profilers, but we'll rule that out for now.

If you must keep up with quotes as they are updated, they have to go somewhere such as a queue or be dispatched to a thread, and unless you can keep up, this can grow unbounded.

The only way to solve this problem is to:

throw some quotes on the floor

get beefier hardware

process quotes more efficiently

I think you are hoping that there is a clear alternative to process quotes more efficiently with a new data structure or algorithm that could make a big difference.  But even if you do make it more efficient, the problem could still come back and you may be forced to consider gracefully degrading under overload conditions rather than failing with out of memory.

But in general terms, for high performance simpler is often better and fewer threads swaps is better.  For example, if the work done in update is small, making it synchronous could be a big win, even though it seems counter intuitive.  You have to know what the update handler does and most of all for a near-real-time system you have to measure, measure, measure to empirically know which is fastest.


问:
Parsing data from function in POSIX
I'm using POSIX. I have a function called get_data which returns:

```<code>4;Fix README;feature4;develop;URL5
2;Fix file3;feature2;develop;URL2
5;Fix README;feature2;develop;URL3
1;Fix file2;feature1;develop;URL1
</code>```

I want to get to the URL (last part) of latest feature2 (based on the first index). In the above example, it will return URL3 because it has feature2 in the third field and 5 > 2 in the first field.

The first thing I tried is:

```<code>url=$(get_data | grep feature2)
</code>```

But I don't like this solution because the other lines also can contain feature2 on other fields. If it was Bash I would use BASH_REMATCH with regex, but here I'm not sure what is the best most elegant way to get that URL.

Is it possible to get some suggestion on how to do it?

答:
Using sort and awk, we can do </p>

```<code>url=$(get_data | sort -t ";" -k 1nr,1nr file | awk -F";" '$3 == "feature2"{print $5;exit}')
</code>```

Title: Parsing data from function in POSIX

Body:
I'm using POSIX. I have a function called get_data which returns:

4;Fix README;feature4;develop;URL5
2;Fix file3;feature2;develop;URL2
5;Fix README;feature2;develop;URL3
1;Fix file2;feature1;develop;URL1

I want to get to the URL (last part) of latest feature2 (based on the first index). In the above example, it will return URL3 because it has feature2 in the third field and 5 > 2 in the first field.

The first thing I tried is:

url=$(get_data | grep feature2)

But I don't like this solution because the other lines also can contain feature2 on other fields. If it was Bash I would use BASH_REMATCH with regex, but here I'm not sure what is the best most elegant way to get that URL.

Is it possible to get some suggestion on how to do it?

Body:
Using sort and awk, we can do

url=$(get_data | sort -t ";" -k 1nr,1nr file | awk -F";" '$3 == "feature2"{print $5;exit}')


问:
SwiftUI Toggle in a VStack is misaligned
I have a simple List where each row is a Toggle with its Text and Text as a subtitle all in a VStack. All works fine until I start showing or hiding some rows. Somehow the switch of the Toggle view is misaligned and is placed over its title. This happens only on the device and not when running on the simulator.

It happens with both XCode 13.3 and 13.4 beta on a device running iOS 13.3.1

The complete example is

```<code>import SwiftUI

struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        NavigationView {
            Form {
                ToggleSubtitleRow(title: "Show Advanced",
                                     text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                     isOn: $showDetails)

                if showDetails {
                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $firstToggle)

                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $secondToggle)
                }

            }
            .listStyle(GroupedListStyle())
            .navigationBarTitle("Settings", displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public init(title: String, text: String,
                isOn: Binding<Bool>) {
        self.text = text
        self.title = title
        self._isOn = isOn

    }

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}
</code>```

答:
this should work

```<code>import SwiftUI

struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        NavigationView {
            Form {
                ToggleSubtitleRow(title: "Show Advanced",
                                     text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                     isOn: $showDetails)

                if showDetails {
                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                        isOn: $firstToggle).id(UUID())

                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $secondToggle)
                }

            }
            .listStyle(GroupedListStyle())
            .navigationBarTitle("Settings", displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}
</code>```

I put it here to show, that the whole conditional part is recreated if at least one of its element need to be recreated.

For explanation, change the code a little bit (without any .id modifier)

```<code>if showDetails {
    Text("\(showDetails.description)")
    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $firstToggle)

     ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $secondToggle)
 }
</code>```

It works, "as expected", because in the conditional part SwiftUI recognized "something" was changed.

```<code>Text("\(showDetails.description)")
</code>```

has the same effect.

What about .id modifier? Why it works?

```<code>@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension View {

    /// Returns a view whose identity is explicitly bound to the proxy
    /// value `id`. When `id` changes the identity of the view (for
    /// example, its state) is reset.
    @inlinable public func id<ID>(_ id: ID) -> some View where ID : Hashable

}
</code>```

Based on written

```<code>ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                    isOn: $firstToggle).id(showDetails)
</code>```

works as well!

Lets rearrange the code this way

```<code>struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        let g = Group {
            if showDetails {
                ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $firstToggle).id(UUID())

                ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $secondToggle)
            }
        }
        let f = Form {
            ToggleSubtitleRow(title: "Show Advanced",
                                 text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                 isOn: $showDetails)
            g

        }
        .listStyle(GroupedListStyle())
        .navigationBarTitle("Settings", displayMode: .inline)
        let v = NavigationView {
            f
        }
        return v
    }
}
</code>```

and check the type of g

```<code>let g: Group<TupleView<(some View, ToggleSubtitleRow)>?>
</code>```

we can see how SwiftUI deal with our "conditional". It is in fact

```<code>TupleView<(some View, ToggleSubtitleRow)>?
</code>```

UPDATE based on discussion, applying .id modifier on more than one ToggleSubtitleRow simply doesn't work

The best option, how to solve this bug is redefine

```<code>public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }.id(UUID())
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}
</code>```

by not modifying anything in you ContentView but directly Toggle self in ToggleSubtitleRow

Body:
I have a simple List where each row is a Toggle with its Text and Text as a subtitle all in a VStack. All works fine until I start showing or hiding some rows. Somehow the switch of the Toggle view is misaligned and is placed over its title. This happens only on the device and not when running on the simulator.

It happens with both XCode 13.3 and 13.4 beta on a device running iOS 13.3.1

The complete example is

import SwiftUI

struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        NavigationView {
            Form {
                ToggleSubtitleRow(title: "Show Advanced",
                                     text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                     isOn: $showDetails)

                if showDetails {
                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $firstToggle)

                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $secondToggle)
                }

            }
            .listStyle(GroupedListStyle())
            .navigationBarTitle("Settings", displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public init(title: String, text: String,
                isOn: Binding<Bool>) {
        self.text = text
        self.title = title
        self._isOn = isOn

    }

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}

Body:
this should work

import SwiftUI

struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        NavigationView {
            Form {
                ToggleSubtitleRow(title: "Show Advanced",
                                     text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                     isOn: $showDetails)

                if showDetails {
                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                        isOn: $firstToggle).id(UUID())

                    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                         text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                         isOn: $secondToggle)
                }

            }
            .listStyle(GroupedListStyle())
            .navigationBarTitle("Settings", displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}

I put it here to show, that the whole conditional part is recreated if at least one of its element need to be recreated.

For explanation, change the code a little bit (without any .id modifier)

if showDetails {
    Text("\(showDetails.description)")
    ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $firstToggle)

     ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $secondToggle)
 }

It works, "as expected", because in the conditional part SwiftUI recognized "something" was changed.

Text("\(showDetails.description)")

has the same effect.

What about .id modifier? Why it works?

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension View {

    /// Returns a view whose identity is explicitly bound to the proxy
    /// value `id`. When `id` changes the identity of the view (for
    /// example, its state) is reset.
    @inlinable public func id<ID>(_ id: ID) -> some View where ID : Hashable

}

Based on written

ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                    isOn: $firstToggle).id(showDetails)

works as well!

Lets rearrange the code this way

struct ContentView: View {

    @State var showDetails = false
    @State var firstToggle = false
    @State var secondToggle = false
    var body: some View {
        let g = Group {
            if showDetails {
                ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $firstToggle).id(UUID())

                ToggleSubtitleRow(title: "Lorem ipsum dolor sit amet",
                                  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
                                  isOn: $secondToggle)
            }
        }
        let f = Form {
            ToggleSubtitleRow(title: "Show Advanced",
                                 text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, se",
                                 isOn: $showDetails)
            g

        }
        .listStyle(GroupedListStyle())
        .navigationBarTitle("Settings", displayMode: .inline)
        let v = NavigationView {
            f
        }
        return v
    }
}

and check the type of g

let g: Group<TupleView<(some View, ToggleSubtitleRow)>?>

we can see how SwiftUI deal with our "conditional". It is in fact

TupleView<(some View, ToggleSubtitleRow)>?

UPDATE based on discussion, applying .id modifier on more than one ToggleSubtitleRow simply doesn't work

The best option, how to solve this bug is redefine

public struct ToggleSubtitleRow: View {
    let title: String
    let text: String
    @Binding var isOn: Bool

    public var body: some View {
        VStack(alignment: .leading) {
            Toggle(isOn: $isOn) {
                Text(title)
            }.id(UUID())
            Text(text)
                .fixedSize(horizontal: false, vertical: true)
                .foregroundColor(Color(.secondaryLabel))
                .frame(alignment: .leading)
        }
        .foregroundColor(Color(.label))
    }
}

by not modifying anything in you ContentView but directly Toggle self in ToggleSubtitleRow


问:
Symfony cmd error "The target-entity..cannot be found in.."
I'm starting with Symfony Framework and I am trying to make ManyToMany relationship.
But when I try this commandline

```<code>php bin/console doctrine:schema:update
</code>```

I am getting this error:

```<code>The target-entity C:\xampp\htdocs\symfony-tp\src\Entity\Competetence cannot be found in 'App\Entity\Stagiaire#competencies'.
</code>```

Stagiaire.php

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\StagiaireRepository")
 */
class Stagiaire
{
    /**
     * @ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
     */
    private $competencies;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $name;

    /**
     * @ORM\Column(type="integer")
     */
    private $phone;

    /**
     * @ORM\Column(type="datetime")
     */
    private $birthday;
    /**
     * @var \Datetime
     */
    private $date;

    public function __construct()
    {
        $this->date = new \Datetime();
        $this->competencies = new ArrayCollection();
    }

    public function addCompetence(Competence $competence)
    {
        $this->$competence[] = $competence;

        return $this;
    }

    public function removeCompetence(Competence $competence)
    {
        $this->competencies->removeElement($competence);
    }

    public function getCompetencies()
    {
        return $this->competencies;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getBirthday(): ?\DateTimeInterface
    {
        return $this->birthday;
    }

    public function setBirthday(\DateTimeInterface $birthday): self
    {
        $this->birthday = $birthday;

        return $this;
    }
}
</code>```

Competence.php

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompetenceRepository")
 */
class Competence
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $name;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}
</code>```

Thanks for your help !

答:
In Stagiaire::$competencies annotation you need to provide Competence's Fully-Qualified Class Name instead of file path on your computer, and that would be App\Entity\Competence

So this:

```<code>    /**
     * @ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
     */
    private $competencies;
</code>```

Becomes:

```<code>    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Competence",cascade={"persist"})
     */
    private $competencies;
</code>```

Body:
I'm starting with Symfony Framework and I am trying to make ManyToMany relationship.
But when I try this commandline

php bin/console doctrine:schema:update

I am getting this error:

The target-entity C:\xampp\htdocs\symfony-tp\src\Entity\Competetence cannot be found in 'App\Entity\Stagiaire#competencies'.

Stagiaire.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\StagiaireRepository")
 */
class Stagiaire
{
    /**
     * @ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
     */
    private $competencies;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $name;

    /**
     * @ORM\Column(type="integer")
     */
    private $phone;

    /**
     * @ORM\Column(type="datetime")
     */
    private $birthday;
    /**
     * @var \Datetime
     */
    private $date;

    public function __construct()
    {
        $this->date = new \Datetime();
        $this->competencies = new ArrayCollection();
    }

    public function addCompetence(Competence $competence)
    {
        $this->$competence[] = $competence;

        return $this;
    }

    public function removeCompetence(Competence $competence)
    {
        $this->competencies->removeElement($competence);
    }

    public function getCompetencies()
    {
        return $this->competencies;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getBirthday(): ?\DateTimeInterface
    {
        return $this->birthday;
    }

    public function setBirthday(\DateTimeInterface $birthday): self
    {
        $this->birthday = $birthday;

        return $this;
    }
}

Competence.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompetenceRepository")
 */
class Competence
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $name;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}

Thanks for your help !

Body:
In Stagiaire::$competencies annotation you need to provide Competence's Fully-Qualified Class Name instead of file path on your computer, and that would be App\Entity\Competence

So this:

    /**
     * @ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
     */
    private $competencies;

Becomes:

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Competence",cascade={"persist"})
     */
    private $competencies;


问:
Soup.select method in python - how to choose only one score?
I want to display only first score of soup.select method, now i have this code:

```<code>score = soup.select('my_name a')
print(score)

urls = [tag['href'] for tag in score if 'href' in tag.attrs and "name" in tag['href']]
print(urls)
</code>```

When bs finds only one score, it works very good. But how to choose only first score when i get more scores?

Now output is:

```<code>> [<a href="/name/adrian1021 "> Adrian </a>, <a href="/name/john.james"> John James </a>, <a href="/name/carol22 "> Carol Coat </a>]
>
> ['/name/adrian1021 ', '/name/john.james ', '/name/carol22 ']
</code>```

I want to extract only one score, for example output should be:

```<code>[/name/adrian1021 ']
</code>```

Is that possible? I tried to work on this like on list but it does not work.

答:
You are looking to use soup.select_one() which finds only the first element that matches a selector.

So your score variable should be:

```<code>score = soup.select_one('my_name a')
</code>```

Body:
I want to display only first score of soup.select method, now i have this code:

score = soup.select('my_name a')
print(score)

urls = [tag['href'] for tag in score if 'href' in tag.attrs and "name" in tag['href']]
print(urls)

When bs finds only one score, it works very good. But how to choose only first score when i get more scores?

Now output is:

> [ Adrian ,  John James ,  Carol Coat ]
>
> ['/name/adrian1021 ', '/name/john.james ', '/name/carol22 ']

I want to extract only one score, for example output should be:

[/name/adrian1021 ']

Is that possible? I tried to work on this like on list but it does not work.

Body:
You are looking to use soup.select_one() which finds only the first element that matches a selector.

So your score variable should be:

score = soup.select_one('my_name a')


问:
Accessing type of a property from an extended generic
Consider the following setup:

genericModel.ts

```<code>export default class GenericModel<TModelId> {
    id!: TModelId;

    constructor(defaultId: any){
        this.id = defaultId;
    }
}
</code>```

genericStore.ts

```<code>class GenericStore<TModel extends GenericModel<any>> {

    @observable loadedModels = observable.map<typeof(TModel.id), TModel>();

    constructor(service: TService){
        this.service = service;
    }

}

export default GenericStore;
</code>```

I know that you cannot call typeof on a generic and why -- this is only to illustrate intent. The observable decorator is from mobx, but it is just a unique structure that requires the type of the model id to use as an identifier, and the model type itself. Now I know I can make it work like this:

```<code>class GenericStore<TModelId, TModel extends GenericModel<TModelId, any>, TService> {
    @observable loadedModels = observable.map<TModelId, TModel>();

    constructor(service: TService){
        this.service = service;
    }

}

export default GenericStore;
</code>```

But when I am extending the generic store, the type of the model is already declared, so I am thinking there should be a way to infer it without having to declare the TModelId explicitly. I'm new to generics so this may just not be possible but if that's the case I just want confirmation.

答:
I think TModel["id"] is what you're looking for. Complete example:

```<code>class GenericModel<ID> {
    constructor(public id: ID) { }
}

class GenericStore<TModel extends GenericModel<any>> {
    public aaa!: TModel["id"];
}

const store1 = new GenericStore<GenericModel<number>>();

store1.aaa; // number
</code>```

Body:
Consider the following setup:

genericModel.ts

export default class GenericModel<TModelId> {
    id!: TModelId;

    constructor(defaultId: any){
        this.id = defaultId;
    }
}

genericStore.ts

class GenericStore<TModel extends GenericModel<any>> {

    @observable loadedModels = observable.map<typeof(TModel.id), TModel>();

    constructor(service: TService){
        this.service = service;
    }

}

export default GenericStore;

I know that you cannot call typeof on a generic and why -- this is only to illustrate intent. The observable decorator is from mobx, but it is just a unique structure that requires the type of the model id to use as an identifier, and the model type itself. Now I know I can make it work like this:

class GenericStore<TModelId, TModel extends GenericModel<TModelId, any>, TService> {
    @observable loadedModels = observable.map<TModelId, TModel>();

    constructor(service: TService){
        this.service = service;
    }

}

export default GenericStore;

But when I am extending the generic store, the type of the model is already declared, so I am thinking there should be a way to infer it without having to declare the TModelId explicitly. I'm new to generics so this may just not be possible but if that's the case I just want confirmation.

Body:
I think TModel["id"] is what you're looking for. Complete example:

class GenericModel<ID> {
    constructor(public id: ID) { }
}

class GenericStore<TModel extends GenericModel<any>> {
    public aaa!: TModel["id"];
}

const store1 = new GenericStore<GenericModel<number>>();

store1.aaa; // number


问:
How do I animate a polygon to spin in place with SVG?
I have an 8 sided polygon that I want to spin clockwise at its center axis with text. Looking at MDN web docs shows a simple triangle spinning in place, but when I apply it to a polygon it doesn't quite work.

<svg width="500" height="300">
  <polygon
      points="25,5   75,5  100,30  100,80 75,105
      25,105  0,80  0, 30"
      style="stroke:gray; fill:#cc3333; stroke-width: 3;">
        <animateTransform attributeName="transform"
                          attributeType="XML"
                          type="rotate"
                          from="0 60 70"
                          to="360 60 70"
                          dur="10s"
                          repeatCount="indefinite"/>
      </polygon>
</svg>```

答:
The centre of the polygon is at 50, 52.5 so you need to rotate round that.

console.log(document.getElementsByTagName("polygon")[0].getBBox());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="500" height="300">
  <polygon
      points="25,5   75,5  100,30  100,80 75,105
      25,105  0,80  0, 30"
      style="stroke:gray; fill:#cc3333; stroke-width: 3;">
        <animateTransform attributeName="transform"
                          attributeType="XML"
                          type="rotate"
                          from="0 50 52.5"
                          to="360 50 52.5"
                          dur="10s"
                          repeatCount="indefinite">
</svg></code>```

Body:
The centre of the polygon is at 50, 52.5 so you need to rotate round that.

console.log(document.getElementsByTagName("polygon")[0].getBBox());

<svg width="500" height="300">
  <polygon
      points="25,5   75,5  100,30  100,80 75,105
      25,105  0,80  0, 30"
      style="stroke:gray; fill:#cc3333; stroke-width: 3;">
        <animateTransform attributeName="transform"
                          attributeType="XML"
                          type="rotate"
                          from="0 50 52.5"
                          to="360 50 52.5"
                          dur="10s"
                          repeatCount="indefinite">
</svg>


问:
How to get background color of div?
I have a div I want when user clicks on this div the background color of div should be display in alert box using jquery only ?

答:
You can get the color like this:

```<code>$('div#test').css('background-color'); // returns RGB
</code>```

and display it after click like that:

```<code>$('div#test').click(function(){
    alert($(this).css('background-color'));
});
</code>```

See fiddle: http://jsfiddle.net/xWkDW/1/

Title: How to get background color of div?

Body:
You can get the color like this:

$('div#test').css('background-color'); // returns RGB

and display it after click like that:

$('div#test').click(function(){
    alert($(this).css('background-color'));
});

See fiddle: http://jsfiddle.net/xWkDW/1/


问:
ValueError when I compare a concrete value within an array with an integer value
I get the error mentioned in the title in the following code:

import numpy

def solve(index):
    if (index >80):
        return sudoku

    rowIndex = int(index/9)
    columnIndex = index % 9

    if sudoku[rowIndex][columnIndex]!= 0:
        return solve(index+1)

    for input in range (1,10):
        if checking(rowIndex, columnIndex, input):
            sudoku[rowIndex][columnIndex] = input
            if solve(index + 1):

                return sudoku
            sudoku[rowIndex][columnIndex]=0

    return False

solve(start)

```

I have already looked at a few contributions to this error, and  my understanding of the error is that your get it if you compare two arrays with each other or you compare the entire array with a scalar value.
But the only if-statements where I use the array are concrete values within the array for example array[i][j] =! 0
And also it surprises me that the code works completely fine until the last recursion call.

答:
Its because you return either the np array or a boolean value from solve().

Try returning None instead of False.

def solve(index):
    if (index >80):
        return sudoku

    rowIndex = int(index/9)
    columnIndex = index % 9

    if sudoku[rowIndex][columnIndex]!= 0:
        return solve(index+1)

    for input in range (1,10):
        if checking(rowIndex, columnIndex, input):
            sudoku[rowIndex][columnIndex] = input
            if not solve(index + 1) is None:
                return sudoku
            sudoku[rowIndex][columnIndex]=0

    return None
```

<p>And change the if conditions to accomodate:</p>

<pre class="lang-py prettyprint-override"><code>if not solve(index + 1) is None:
</code>```

Body:
I get the error mentioned in the title in the following code:

import numpy

def solve(index):
    if (index >80):
        return sudoku

    rowIndex = int(index/9)
    columnIndex = index % 9

    if sudoku[rowIndex][columnIndex]!= 0:
        return solve(index+1)

    for input in range (1,10):
        if checking(rowIndex, columnIndex, input):
            sudoku[rowIndex][columnIndex] = input
            if solve(index + 1):

                return sudoku
            sudoku[rowIndex][columnIndex]=0

    return False

solve(start)

I have already looked at a few contributions to this error, and  my understanding of the error is that your get it if you compare two arrays with each other or you compare the entire array with a scalar value.
But the only if-statements where I use the array are concrete values within the array for example array[i][j] =! 0
And also it surprises me that the code works completely fine until the last recursion call.

Body:
Its because you return either the np array or a boolean value from solve().

Try returning None instead of False.

def solve(index):
    if (index >80):
        return sudoku

    rowIndex = int(index/9)
    columnIndex = index % 9

    if sudoku[rowIndex][columnIndex]!= 0:
        return solve(index+1)

    for input in range (1,10):
        if checking(rowIndex, columnIndex, input):
            sudoku[rowIndex][columnIndex] = input
            if not solve(index + 1) is None:
                return sudoku
            sudoku[rowIndex][columnIndex]=0

    return None

And change the if conditions to accomodate:

if not solve(index + 1) is None:


问:
Prevent duplicates when insert by SQLXMLBULKLOADLib
I am wondering if is there a way to prevent insert of duplicate rows while we use SQLXMLBULKLOADLib? I've tried to add UNIQUE NONCLUSTERED INDEX to the SQL table, however insert by SQLXMLBulkLoad4Class fails.

So my code looks likes this

```<code>SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class();
objBL.ConnectionString = "Provider=sqloledb;server=server;database=databaseName;integrated security=SSPI";
objBL.ErrorLogFile = "error.xml";
objBL.KeepIdentity = false;
objBL.Execute ("schema.xml","data.xml");
</code>```

My xml looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <BICYCLE_NUM>624</BICYCLE_NUM>
      <BICYCLE_ORDER>1</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>623</BICYCLE_NUM>
      <BICYCLE_ORDER>2</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>681</BICYCLE_NUM>
      <BICYCLE_ORDER>3</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>625</BICYCLE_NUM>
      <BICYCLE_ORDER>4</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>680</BICYCLE_NUM>
      <BICYCLE_ORDER>5</BICYCLE_ORDER>
   </row>
</foo>
</code>```

And  XSD looks like this:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="row" sql:relation="BICYCLE"
                        sql:key-fields="BICYCLE_NUM">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="BICYCLE_NUM"   type="xsd:integer" />
            <xsd:element name="BICYCLE_ORDER"   type="xsd:integer" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</code>```

SQL table looks like this:

```<code>CREATE TABLE BICYCLE (
         BICYCLE_NUM   INT ,
         BICYCLE_ORDER INT
GO

CREATE UNIQUE NONCLUSTERED INDEX IX_BICYCLE_NUM__BICYCLE_ORDER
   ON Wagon (BICYCLE_NUM, BICYCLE_ORDER);
</code>```

I've tried to set CheckConstraints = true, nevertheless the result is the same

```<code>SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
            {
                ConnectionString = connectionString,
                ErrorLogFile = "error.xml",
                KeepIdentity = true,
                CheckConstraints = true
            };
</code>```

My question is how can I prevent insert of duplicates using SQLXMLBULKLOADLib?

答:
After exploring SQLXMLBulkLoad4Class, IgnoreDuplicateKeys property was found. So we can use IgnoreDuplicateKeys property:

```<code>SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
{
    ConnectionString = connectionString,
    ErrorLogFile = "error.xml",
    ISQLXMLBulkLoad_IgnoreDuplicateKeys = true,
    IgnoreDuplicateKeys = true
};
objBL.Execute(xsdScheme, xmlFileName);
</code>```

In addition, CONSTRAINT should be used, not UNIQUE NONCLUSTERED INDEX:

```<code>CREATE TABLE BICYCLE
(
      BICYCLE_NUM   INT
    , BICYCLE_ORDER INT
    , CONSTRAINT PK_BICYCLENUM_BICYCLEORDER PRIMARY KEY
        NONCLUSTERED (BICYCLE_NUM, BICYCLE_ORDER)
)
GO
</code>```

Body:
I am wondering if is there a way to prevent insert of duplicate rows while we use SQLXMLBULKLOADLib? I've tried to add UNIQUE NONCLUSTERED INDEX to the SQL table, however insert by SQLXMLBulkLoad4Class fails.

So my code looks likes this

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class();
objBL.ConnectionString = "Provider=sqloledb;server=server;database=databaseName;integrated security=SSPI";
objBL.ErrorLogFile = "error.xml";
objBL.KeepIdentity = false;
objBL.Execute ("schema.xml","data.xml");

My xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <BICYCLE_NUM>624</BICYCLE_NUM>
      <BICYCLE_ORDER>1</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>623</BICYCLE_NUM>
      <BICYCLE_ORDER>2</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>681</BICYCLE_NUM>
      <BICYCLE_ORDER>3</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>625</BICYCLE_NUM>
      <BICYCLE_ORDER>4</BICYCLE_ORDER>
   </row>
   <row>
      <BICYCLE_NUM>680</BICYCLE_NUM>
      <BICYCLE_ORDER>5</BICYCLE_ORDER>
   </row>
</foo>

And  XSD looks like this:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="row" sql:relation="BICYCLE"
                        sql:key-fields="BICYCLE_NUM">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="BICYCLE_NUM"   type="xsd:integer" />
            <xsd:element name="BICYCLE_ORDER"   type="xsd:integer" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

SQL table looks like this:

CREATE TABLE BICYCLE (
         BICYCLE_NUM   INT ,
         BICYCLE_ORDER INT
GO

CREATE UNIQUE NONCLUSTERED INDEX IX_BICYCLE_NUM__BICYCLE_ORDER
   ON Wagon (BICYCLE_NUM, BICYCLE_ORDER);

I've tried to set CheckConstraints = true, nevertheless the result is the same

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
            {
                ConnectionString = connectionString,
                ErrorLogFile = "error.xml",
                KeepIdentity = true,
                CheckConstraints = true
            };

My question is how can I prevent insert of duplicates using SQLXMLBULKLOADLib?

Body:
After exploring SQLXMLBulkLoad4Class, IgnoreDuplicateKeys property was found. So we can use IgnoreDuplicateKeys property:

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
{
    ConnectionString = connectionString,
    ErrorLogFile = "error.xml",
    ISQLXMLBulkLoad_IgnoreDuplicateKeys = true,
    IgnoreDuplicateKeys = true
};
objBL.Execute(xsdScheme, xmlFileName);

In addition, CONSTRAINT should be used, not UNIQUE NONCLUSTERED INDEX:

CREATE TABLE BICYCLE
(
      BICYCLE_NUM   INT
    , BICYCLE_ORDER INT
    , CONSTRAINT PK_BICYCLENUM_BICYCLEORDER PRIMARY KEY
        NONCLUSTERED (BICYCLE_NUM, BICYCLE_ORDER)
)
GO


问:
JUnit, Android: What's a good level of detail in automated tests?
I'm finding writing tests literally around 10 times more time consuming than writing the code itself. This question has been asked here: Level of detail of your unit tests However, the answers all seemed pro-testing, and I'm not convinced.

I can appreciate how writing tests can save time, especially with all those bits of code which have caused me headaches in the past. However:

Annoyingly, it seems like the things most in need of automated testing are the hardest? (E.g. Testing for lack of GPS signal in Android)

Testing seems to need changes to the original code.

Test code adds dependencies And that's black box testing, let alone white box testing.

Under the assumption that I'll be the only person to deal with the code, and I'll only be developing relatively small apps, anything but the most important of tests on self contained code with a lot of logic is a waste of time?

Please share any information to help me write tests that ultimately save time and result in better code, I'm struggling to see the value at the moment!!

答:
Unit testing is very expensive.

It is useful if you plan to refactor your code deeply later on, for regression tests. Otherwise...

To test or not to test. That is the question.


问:
How to get data once from firebase by ID
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

and I get the data in the HTML calling it directly:

```<code><div class="msg_container_other" *ngIf="getUser(chat.uid); let otherUser">
                  {{chat.content}}
                  <span class="msg_time"><i class="fas fa-check-double" style="color: #292929;"></i> {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}</span>
</div>
</code>```

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

```<code>  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }
</code>```

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

```<code>    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}
</code>```

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

```<code>     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });
</code>```

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

```<code>   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});
</code>```

And this is the html with new change:

```<code>    <div class="card" *ngIf="authService.userData as user">

        <div id="card-box" class="card-box msg_head" ><!--  #scrollMe [scrollTop]="scrollMe.scrollHeight" DA ERROR  -->

            <div id="card-body" class="card-body msg_card_body">
              <div *ngFor="let chat of chatsList">
</code>```

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

```<code>getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }
</code>```

答:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN</p>

```<code>getPages(){
      const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
      return item.valueChanges().pipe(
      switchMap(arr => {
       const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
       return combineLatest(...userObservable) .pipe( map((...users) => {
          arr.forEach((author, index) => {
           author['author_avatar'] = users[0][index]['photoURL'];
           author['author_username'] = users[0][index]['displayName'];
          });
          return arr;
          })
          );
        })
        );
       }
</code>```

Body:
Hello im trying to get the user email of each message. (Each message (chat) have an userid).
I get the whole user data throught getUser on the *ngIf. And then just show the email. It works and on the website there isn't any repeat of data, but the tab soon freezes unless I don't pause with debugger. I don't know why but it makes an infinite loop.
It looks like this: https://i.imgur.com/XBku0uc.png It makes thousands of console logs.

This is getUser:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.valueChanges().subscribe(queriedItems => {
      this.userDT=new Usermodel(queriedItems[0].uid,queriedItems[0].email,queriedItems[0].displayName,queriedItems[0].photoURL,queriedItems[0].emailVerified);
    });
    console.log(this.userDT.email)
    return this.userDT;
  }

and I get the data in the HTML calling it directly:

                  {{chat.content}}
                   {{otherUser.email}}. {{ chat.date | date:'d/M/y H:mm'}}

If you need to see what is chats: https://i.imgur.com/iThi424.png and more context on html:https://i.imgur.com/GRupLAp.png

I've been several days trying things and don't know what else to try.
If I remove the subscription of getUser like this:

  getUser(uid:string){
    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));

    console.log(this.userDT.email)
    return this.userDT;
  }

Then it doesn't loops, but of course can't get data then.

People have told me that isn't the good way to get data once because im subscribing so I tried this way but have same effect infinite loop.

    getUser(uid:string){

    this.userCollection = this.db.collection('users', ref => ref.where('uid', '==', uid));
    this.userCollection.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data().email);
            return doc.data().email;
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
}

This getUser doesn't works either it also makes infinite loop :/ cant believe i cant find how to get a single data by query

     return this.db.collection('users', ref => ref.where('uid', '==', uid)).snapshotChanges().subscribe(data => {
    return data.map(e => {
      return {
        id: e.payload.doc.id,
        ...e.payload.doc.data()
      } as User;
    })
  });

EDIT:

Okay I think I tried to do it better, this is how I go throught the chats now:
https://i.imgur.com/oJAJDGA.png

   db.collection('chats', ref => ref.where('groupId', '==', this.pathId).orderBy('date')).snapshotChanges().subscribe(data => {
  this.chatsList = data.map(e => {
    return {
      id: e.payload.doc.id,
      ...e.payload.doc.data()
    } as Chat;
  })
});

And this is the html with new change:

Still can't make it to get the userdata by userid from chat uid without infinite loop tho

EDIT2:
Okay I think I understand better how the asyncronous thing works and I was trying to build a frankenstein, Ill update this when I build it in another way.

EDIT3:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN:

getPages(){
  const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
  return item.valueChanges().pipe(
  switchMap(arr => {
   const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
   return combineLatest(...userObservable) .pipe( map((...users) => {
      arr.forEach((author, index) => {
       author['author_avatar'] = users[0][index]['photoURL'];
       author['author_username'] = users[0][index]['displayName'];
      });
      return arr;
      })
      );
    })
    );
   }

Body:
Ok I fixed this by getting everything asyncronous (as it have to be) and doing a JOIN

getPages(){
      const item: AngularFirestoreCollection = this.afs.collection(`pages`, (ref) => ref.orderBy('createdAt', 'desc'));
      return item.valueChanges().pipe(
      switchMap(arr => {
       const userObservable = arr.map(user => this._afs.doc(`users/${user.uid}`) .valueChanges().pipe(first()) );
       return combineLatest(...userObservable) .pipe( map((...users) => {
          arr.forEach((author, index) => {
           author['author_avatar'] = users[0][index]['photoURL'];
           author['author_username'] = users[0][index]['displayName'];
          });
          return arr;
          })
          );
        })
        );
       }


问:
PyQt5 QLCDNumber Display
I´m new to PyQt5 have been playing with it for about two weeks now and I have encountered an issue with the QLCDNumber display method. I want to be able to display more than 5 digits which I currently can´t with the code I have. After I input the 6th digit the numbers stop showing.
I have researched for about a week on google and youtube but was not able to find a solution.
Code:

```<code>self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(91029)
</code>```

This above code works but the below does not display the numbers:

```<code>self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(910297)
</code>```

答:
As the docs points out:

digitCount : int

This property holds the current number of digits
displayed

Corresponds to the current number of digits. If
QLCDNumber::smallDecimalPoint is false, the decimal point occupies one
digit position.

By default, this property contains a value of 5.

This property was introduced in Qt 4.6.

Access functions:

int digitCount()

const void  setDigitCount(int numDigits)

(emphasis mine)

As indicated by default, only up to 5 digits are shown, so if you want to show more or less digits you must use the X method or point it in the constructor:

self.lcd = QLCDNumber(6, self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(910297)
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code>self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.setDigitCount(6)
self.lcd.display(910297)
</code>```

Title: PyQt5 QLCDNumber Display

Body:
I´m new to PyQt5 have been playing with it for about two weeks now and I have encountered an issue with the QLCDNumber display method. I want to be able to display more than 5 digits which I currently can´t with the code I have. After I input the 6th digit the numbers stop showing.
I have researched for about a week on google and youtube but was not able to find a solution.
Code:

self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(91029)

This above code works but the below does not display the numbers:

self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(910297)

Body:
As the docs points out:

digitCount : int

This property holds the current number of digits
displayed

Corresponds to the current number of digits. If
QLCDNumber::smallDecimalPoint is false, the decimal point occupies one
digit position.

By default, this property contains a value of 5.

This property was introduced in Qt 4.6.

Access functions:

int digitCount()

const void  setDigitCount(int numDigits)

(emphasis mine)

As indicated by default, only up to 5 digits are shown, so if you want to show more or less digits you must use the X method or point it in the constructor:

self.lcd = QLCDNumber(6, self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.display(910297)

or

self.lcd = QLCDNumber(self)
self.lcd.setGeometry(3, 120, 150, 30)
self.lcd.setDigitCount(6)
self.lcd.display(910297)


问:
Events provider is deprecating. Using Redux or Observables for state in ionic apps
I've been using events in my ionic application, where i subscribe in one page, and publish the event in the other page. Now I see a warning that Events are going to be changed with Observables and Redux state and effect.
I was using Events mainly to call for component function changes outside it, so I had a components for example:

Component1.ts

```<code>this.events.subscribe('event:addValue1', (data: any) => {
this.valueName = 'VALUE1';
});

this.events.subscribe('event:addValue2', (data: any) => {
this.valueName = 'VALUE2';
});
</code>```

and than outside this component I was calling the publish methods from any page, like:

Page1.ts

```<code>this.events.publish('event:addValue1');
</code>```

Page2.ts

```<code>this.events.publish('event:addValue2');
</code>```

By this i was able to change the data (this.valueName) outside the Component1.ts from any other page, simply by publishing the desired event.
I know that this might not sound or be right approach, but It was the only way I was doing changes to my Component1.ts outside it from any page.

I have now changed this and just put separate functions and than i access them via ViewChild component name like

```<code>@ViewChild('component') component: any;
....
this.component.functionAddValue1().
</code>```

and additionally I send additional params via Angular NavigationExtras if i need to calculate and call some function from the Component1.ts, lets say if I navigate to some route.
Before this I was just calling the events.publish and I was able to make the changes to the Component1.ts on the fly.

答:
Create event service.
In the EventService.ts:

```<code>    export class EventService {
    private dataObserved = new BehaviorSubject<any>('');
    currentEvent = this.dataObserved.asObservable();
    constructo(){}

    publish(param):void {
      this.dataObserved.next(param);
    }
   }
</code>```

For publishing the event from example page1:

```<code>    constructor(public eventService:EventService){}
updatePost(value){
this.eventService.publish({name:'post:updated',params:value});
}
</code>```

In page 2:

```<code>constructor(public eventService:EventService){
  eventService.currentEvent.subscribe(value=>{
if(value.name=='post:updated'){
//get value.name
}else if(value.name=='another:event'){
//get value or update view or trigger function or method...
}
 // here you can get the value or do whatever you want

});
}
</code>```

Body:
I've been using events in my ionic application, where i subscribe in one page, and publish the event in the other page. Now I see a warning that Events are going to be changed with Observables and Redux state and effect.
I was using Events mainly to call for component function changes outside it, so I had a components for example:

Component1.ts

this.events.subscribe('event:addValue1', (data: any) => {
this.valueName = 'VALUE1';
});

this.events.subscribe('event:addValue2', (data: any) => {
this.valueName = 'VALUE2';
});

and than outside this component I was calling the publish methods from any page, like:

Page1.ts

this.events.publish('event:addValue1');

Page2.ts

this.events.publish('event:addValue2');

By this i was able to change the data (this.valueName) outside the Component1.ts from any other page, simply by publishing the desired event.
I know that this might not sound or be right approach, but It was the only way I was doing changes to my Component1.ts outside it from any page.

I have now changed this and just put separate functions and than i access them via ViewChild component name like

@ViewChild('component') component: any;
....
this.component.functionAddValue1().

and additionally I send additional params via Angular NavigationExtras if i need to calculate and call some function from the Component1.ts, lets say if I navigate to some route.
Before this I was just calling the events.publish and I was able to make the changes to the Component1.ts on the fly.

Body:
Create event service.
In the EventService.ts:

    export class EventService {
    private dataObserved = new BehaviorSubject<any>('');
    currentEvent = this.dataObserved.asObservable();
    constructo(){}

    publish(param):void {
      this.dataObserved.next(param);
    }
   }

For publishing the event from example page1:

    constructor(public eventService:EventService){}
updatePost(value){
this.eventService.publish({name:'post:updated',params:value});
}

In page 2:

constructor(public eventService:EventService){
  eventService.currentEvent.subscribe(value=>{
if(value.name=='post:updated'){
//get value.name
}else if(value.name=='another:event'){
//get value or update view or trigger function or method...
}
 // here you can get the value or do whatever you want

});
}


问:
If statement checks the global var but runs both conditions
I'm banging my head to the wall, please help :(

EDIT: The script works on jsfiddle, my own server, but on client's server not :/

I have a simple price switcher based on global variable. I want to use the global var, because the switcher contains: text ie. Discount on (clickable), styled checkbox (with colors), text (clickable) ie. Discount off - so I can add listeners to clickable span elements with texts and change the color etc. of the styled checkbox.

Code for discount button:

```<code><p class="prices-starter-switch">
<span class="prices-starter-discount active">Prices with discount</span>
<label id="pricesSwitcher" class="switch"><input type="checkbox" checked>
<span class="slider round"></span></label>
<span class="prices-starter-discount-none">Prices without discount</span>
</p>
</code>```

The price elements are construced like this:

```<code><em data-normalprice="52" data-discountedprice="47" class="price-to-add-discount">47</em>
<em data-normalprice="60" data-discountedprice="54" class="price-to-add-discount">54</em>
<em data-normalprice="100" data-discountedprice="90" class="price-to-add-discount">90</em>
</code>```

data-normalprice and data-discountedprice hold the prices value to be swapped in the em element.

The prices are listed in two ways - normal listing and table at the bottom of the page. All the prices to be switched (normal price and discounted) have class price-to-add-discount

On the backend, I'm displaying the discounted price when the page loads.

I'd like to use global var to change all the prices (as em's and inside table).

I wrote the code, but when firing the listener on click the if statement goes all the way and don't  check the conditions :/

Here's the JS code:

```<code>window.pricesSetToDiscounted = true;
// I'm setting the global var to true, since from the backend side I'm showing the client the discounted prices
as he load's the website
window.prices_to_be_calculated = document.querySelectorAll(".price-to-add-discount");
// selecting all the elements with prices to work with

var btn = document.getElementById('pricesSwitcher'); // my simple button ID

btn.addEventListener('click', function() {
    if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==true) {
       pricesShowNormal();
   }
    else if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==false) {
        pricesShowDiscounted();
    }
}, false);

function pricesShowDiscounted() {
    var i;
    for (i = 0; i < prices_to_be_calculated.length; i++) {
        var discountedPrice = prices_to_be_calculated[i].dataset.discountedprice;
        prices_to_be_calculated[i].innerHTML = discountedPrice;     }
    pricesSetToDiscounted = true;
    console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};

function pricesShowNormal() {
    var y;
    for (y = 0; y < prices_to_be_calculated.length; y++) {
        var normalPrice = prices_to_be_calculated[y].dataset.normalprice;
        prices_to_be_calculated[y].innerHTML = normalPrice;
    }
    pricesSetToDiscounted = false;
    console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};
</code>```

What am I doing wrong?

答:
Figured it out.

```<code>document.getElementById('prices-switcher').onclick = function() {
    if (pricesSetToDiscounted == true) {
        pricesShowNormal();
    } else {
        pricesShowDiscounted();
    }
    return false;
}
</code>```

Works like a charm - both on jsfiddle, my server and client's server :)

Body:
I'm banging my head to the wall, please help :(

EDIT: The script works on jsfiddle, my own server, but on client's server not :/

I have a simple price switcher based on global variable. I want to use the global var, because the switcher contains: text ie. Discount on (clickable), styled checkbox (with colors), text (clickable) ie. Discount off - so I can add listeners to clickable span elements with texts and change the color etc. of the styled checkbox.

Code for discount button:

Prices with discount
<input type="checkbox" checked>

Prices without discount

The price elements are construced like this:

47
54
90

data-normalprice and data-discountedprice hold the prices value to be swapped in the em element.

The prices are listed in two ways - normal listing and table at the bottom of the page. All the prices to be switched (normal price and discounted) have class price-to-add-discount

On the backend, I'm displaying the discounted price when the page loads.

I'd like to use global var to change all the prices (as em's and inside table).

I wrote the code, but when firing the listener on click the if statement goes all the way and don't  check the conditions :/

Here's the JS code:

window.pricesSetToDiscounted = true;
// I'm setting the global var to true, since from the backend side I'm showing the client the discounted prices
as he load's the website
window.prices_to_be_calculated = document.querySelectorAll(".price-to-add-discount");
// selecting all the elements with prices to work with

var btn = document.getElementById('pricesSwitcher'); // my simple button ID

btn.addEventListener('click', function() {
    if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==true) {
       pricesShowNormal();
   }
    else if(typeof pricesSetToDiscounted != 'undefined' && pricesSetToDiscounted==false) {
        pricesShowDiscounted();
    }
}, false);

function pricesShowDiscounted() {
    var i;
    for (i = 0; i < prices_to_be_calculated.length; i++) {
        var discountedPrice = prices_to_be_calculated[i].dataset.discountedprice;
        prices_to_be_calculated[i].innerHTML = discountedPrice;     }
    pricesSetToDiscounted = true;
    console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};

function pricesShowNormal() {
    var y;
    for (y = 0; y < prices_to_be_calculated.length; y++) {
        var normalPrice = prices_to_be_calculated[y].dataset.normalprice;
        prices_to_be_calculated[y].innerHTML = normalPrice;
    }
    pricesSetToDiscounted = false;
    console.log("pricesSetToDiscounted has value: "+pricesSetToDiscounted);
};

What am I doing wrong?

Body:
Figured it out.

document.getElementById('prices-switcher').onclick = function() {
    if (pricesSetToDiscounted == true) {
        pricesShowNormal();
    } else {
        pricesShowDiscounted();
    }
    return false;
}

Works like a charm - both on jsfiddle, my server and client's server :)


问:
How do I get my flexbox footer to take up the entire space at the bottom?

There is a pixel or two of white space between the left, right, and bottom of the screen and my footer (see the red scribbles on the image above. How do I get the footer to take up all of this space?

Some things I've tried:

I created a margin-left: -10; margin-right:-10; - this worked but it messes with scrolling because the user can scroll sideways now, which I do not want.

I created a bottom
 which had height: 1; this worked for the bottom but there has to be a better way than sticking a
 here and it doesn't solve for the sideways white space.

Margins are not applied to the parent element of the footer.

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="col">

      <div>Privacy policy</div>

  </div>
  <div class="col" style="justify-content: center;">
    <div class="footer_submit">Subscribe</div>
  </div>
  <div class="col" style="justify-content: flex-end;">
    <i class="fa fa-linkedin-square" style="font-size:24px;"></i
        >
  </div>
</footer></code>```

答:
body has default margins 8px (in Chrome at least), set magrin: 0 to it.

body {
  margin: 0;
}

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="col">

      <div>Privacy policy</div>

  </div>
  <div class="col" style="justify-content: center;">
    <div class="footer_submit">Subscribe</div>
  </div>
  <div class="col" style="justify-content: flex-end;">
    <i class="fa fa-linkedin-square" style="font-size:24px;"></i
        >
  </div>
</footer></code>```

Body:
There is a pixel or two of white space between the left, right, and bottom of the screen and my footer (see the red scribbles on the image above. How do I get the footer to take up all of this space?

Some things I've tried:

I created a margin-left: -10; margin-right:-10; - this worked but it messes with scrolling because the user can scroll sideways now, which I do not want.

I created a bottom
 which had height: 1; this worked for the bottom but there has to be a better way than sticking a
 here and it doesn't solve for the sideways white space.

Margins are not applied to the parent element of the footer.

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}

Privacy policy

Subscribe

Body:
body has default margins 8px (in Chrome at least), set magrin: 0 to it.

body {
  margin: 0;
}

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}

<footer>
  <div class="col">
    <a href="" class="privacy_policy">
      <div>Privacy policy</div>
    </a>
  </div>
  <div class="col" style="justify-content: center;">
    <div class="footer_submit">Subscribe</div>
  </div>
  <div class="col" style="justify-content: flex-end;">
    <a href="" style="text-decoration: none; color:white"><i class="fa fa-linkedin-square" style="font-size:24px;"></i
        ></a>
  </div>
</footer>