问:
Adding multiple ARM toolchains to path
So I am aiming to compile armv2 32 bit on my Mac such that it does not use the FP register which I have been told was not in earlier versions of arm 32 by my instructor.

I am thinking that if I use an earlier version of the toolchain it might support armv2 so while I currently have gcc-arm-none-eabi-9-2019-q4-major added to path I might also add gcc-arm-none-eabi-8-2018-q4-major to path.

Heres the issue both of them have the binary arm-none-eabi-gcc in them which is what I want to use and if I add both to my path... I am not sure how to specify whether to use 2019-q4 or 2018-q4's version of gcc. Any good ideas on how to set this up?

Also as a bonus if anyone knows how to force compile as armv2 that would be useful too so I can see if earlier versions did not use fp. Thankyou!

答:
your tools will tell you everything you need to know, no need to use SO.

```<code>arm-none-eabi-gcc --version
arm-none-eabi-gcc (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

arm-none-eabi-gcc -O2 -c -march=armv2a so.c -o so.o
arm-none-eabi-gcc: error: unrecognized -march target: armv2a
arm-none-eabi-gcc: note: valid arguments are: armv4 armv4t armv5t armv5te armv5tej armv6 armv6j armv6k armv6z armv6kz armv6zk armv6t2 armv6-m armv6s-m armv7 armv7-a armv7ve armv7-r armv7-m armv7e-m armv8-a armv8.1-a armv8.2-a armv8.3-a armv8.4-a armv8.5-a armv8-m.base armv8-m.main armv8-r iwmmxt iwmmxt2; did you mean ‘armv4’?
arm-none-eabi-gcc --version
arm-none-eabi-gcc (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

arm-none-eabi-gcc -c -march=armvxx so.c -o so.o
arm-none-eabi-gcc: error: unrecognized argument in option ‘-march=armvxx’
arm-none-eabi-gcc: note: valid arguments to ‘-march=’ are: armv2 armv2a armv3 armv3m armv4 armv4t armv5 armv5e armv5t armv5te armv6 armv6-m armv6j armv6k armv6s-m armv6t2 armv6z armv6zk armv7 armv7-a armv7-m armv7-r armv7e-m armv7ve armv8-a armv8-a+crc iwmmxt iwmmxt2 native
</code>```

so somewhere between 5.4.0 and 9.2.0 gcc dropped support for armv2 I suspect it was 6.x.x but the release notes from gcc is where to look.

google

```<code>gcc no frame pointer
</code>```

and you find

```<code>-fomit-frame-pointer
-fno-omit-frame-pointer
</code>```

test it

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

arm-none-eabi-gcc -S -march=armv2 so.c

```<code>@ Function supports interworking.
@ args = 0, pretend = 0, frame = 8
@ frame_needed = 1, uses_anonymous_args = 0
@ link register save eliminated.
str fp, [sp, #-4]!
</code>```

now this builds unusable code because it uses bx lr, so maybe gcc 5.x.x is no good either.  but to continue

```<code>arm-none-eabi-gcc -fomit-frame-pointer -S -march=armv2 so.c

test:
    @ Function supports interworking.
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 0, uses_anonymous_args = 0
    @ link register save eliminated.
    sub sp, sp, #8
    str r0, [sp, #4]
</code>```

you can try this for armv4 and newer too gcc 5.x.x appears to default to using the frame pointer

9.2.0 is also using the frame pointer by default but the -fomit-frame-pointer option also works

(I intentionally didnt optimize as that would not use the stack, would have had to create a different test function that forced the use of the stack and a desire for a frame).

```<code>unsigned int another_test ( unsigned int );
unsigned int test ( unsigned int a, unsigned int b )
{
    return(another_test(a)<<b);
}

arm-none-eabi-gcc -O2 -S -march=armv7-a so.c

test:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
    push    {r4, lr}

arm-none-eabi-gcc -fno-omit-frame-pointer -O2 -S -march=armv7-a so.c

test:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    push    {r4, r5, fp, lr}
    add fp, sp, #12
</code>```

same/similar results with optimization and an older version of gcc where it determined it didnt need a frame and didnt use one by default but if you forced it it would.

Title: Adding multiple ARM toolchains to path

Body:
your tools will tell you everything you need to know, no need to use SO.

arm-none-eabi-gcc --version
arm-none-eabi-gcc (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

arm-none-eabi-gcc -O2 -c -march=armv2a so.c -o so.o
arm-none-eabi-gcc: error: unrecognized -march target: armv2a
arm-none-eabi-gcc: note: valid arguments are: armv4 armv4t armv5t armv5te armv5tej armv6 armv6j armv6k armv6z armv6kz armv6zk armv6t2 armv6-m armv6s-m armv7 armv7-a armv7ve armv7-r armv7-m armv7e-m armv8-a armv8.1-a armv8.2-a armv8.3-a armv8.4-a armv8.5-a armv8-m.base armv8-m.main armv8-r iwmmxt iwmmxt2; did you mean ‘armv4’?
arm-none-eabi-gcc --version
arm-none-eabi-gcc (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

arm-none-eabi-gcc -c -march=armvxx so.c -o so.o
arm-none-eabi-gcc: error: unrecognized argument in option ‘-march=armvxx’
arm-none-eabi-gcc: note: valid arguments to ‘-march=’ are: armv2 armv2a armv3 armv3m armv4 armv4t armv5 armv5e armv5t armv5te armv6 armv6-m armv6j armv6k armv6s-m armv6t2 armv6z armv6zk armv7 armv7-a armv7-m armv7-r armv7e-m armv7ve armv8-a armv8-a+crc iwmmxt iwmmxt2 native

so somewhere between 5.4.0 and 9.2.0 gcc dropped support for armv2 I suspect it was 6.x.x but the release notes from gcc is where to look.

google

gcc no frame pointer

and you find

-fomit-frame-pointer
-fno-omit-frame-pointer

test it

unsigned int test ( unsigned int a, unsigned int b )
{
    return(a+b);
}

arm-none-eabi-gcc -S -march=armv2 so.c

@ Function supports interworking.
@ args = 0, pretend = 0, frame = 8
@ frame_needed = 1, uses_anonymous_args = 0
@ link register save eliminated.
str fp, [sp, #-4]!

now this builds unusable code because it uses bx lr, so maybe gcc 5.x.x is no good either.  but to continue

arm-none-eabi-gcc -fomit-frame-pointer -S -march=armv2 so.c

test:
    @ Function supports interworking.
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 0, uses_anonymous_args = 0
    @ link register save eliminated.
    sub sp, sp, #8
    str r0, [sp, #4]

you can try this for armv4 and newer too gcc 5.x.x appears to default to using the frame pointer

9.2.0 is also using the frame pointer by default but the -fomit-frame-pointer option also works

(I intentionally didnt optimize as that would not use the stack, would have had to create a different test function that forced the use of the stack and a desire for a frame).

unsigned int another_test ( unsigned int );
unsigned int test ( unsigned int a, unsigned int b )
{
    return(another_test(a)<<b);
}

arm-none-eabi-gcc -O2 -S -march=armv7-a so.c

test:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
    push    {r4, lr}

arm-none-eabi-gcc -fno-omit-frame-pointer -O2 -S -march=armv7-a so.c

test:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    push    {r4, r5, fp, lr}
    add fp, sp, #12

same/similar results with optimization and an older version of gcc where it determined it didnt need a frame and didnt use one by default but if you forced it it would.


来源: stackexchange

问:
Nginx subpage location directive with error page
we use a typo3 CMS and need to redirect two subpages /en /de to different error pages.
I've come up with this:

```<code>location ~ ^/de/ {
    error_page 404 https://www.example.com/de/error-404/;
    error_page 403 https://www.example.com/de/error-403/;
}
location ~ ^/en/ {
    error_page 404 https://www.example.com/en/error-404/;
    error_page 403 https://www.example.com/en/error-403/;
}
</code>```

but this will redirect it in a loop.

Anyway i can achieve this within NGINX?

答:
Seems like i am too stupid for regex:

```<code>location ^/de/.+ {
    error_page 404 https://www.example.com/de/error-404/;
    error_page 403 https://www.example.com/de/error-403/;
}
</code>```

works fine.

ContentLicense: CC BY-SA 4.0

Body:
we use a typo3 CMS and need to redirect two subpages /en /de to different error pages.
I've come up with this:

location ~ ^/de/ {
    error_page 404 https://www.example.com/de/error-404/;
    error_page 403 https://www.example.com/de/error-403/;
}
location ~ ^/en/ {
    error_page 404 https://www.example.com/en/error-404/;
    error_page 403 https://www.example.com/en/error-403/;
}

but this will redirect it in a loop.

Anyway i can achieve this within NGINX?

Body:
Seems like i am too stupid for regex:

location ^/de/.+ {
    error_page 404 https://www.example.com/de/error-404/;
    error_page 403 https://www.example.com/de/error-403/;
}

works fine.


问:
Material-Table: styling is overiding all custom and Material UI styling and icons not rendering
I'm trying to use Material-Table component - it's perfect for a table that I'm buildling (add, edit, delete and search rows). I've installed and used it as a child component of a page - everything works but...

STYLING: all custom and built-in styling in the page is lost in all the Material UI components (ie. AppBar buttons have no padding/spacing between, custom font styling is messed up).

ICONS: The icons in the table won't render - they just appear as large cut-off text.

Styling and icons on other pages without the table are not affected.

Anybody have a solve? Thanks in advance.

For icons, I tried reinstalling the library and importing. Also tried putting
html method. Snippet of the Material Table code is below.

```<code><MaterialTable
  title="Editable Example"
  columns={state.columns}
  data={state.data}
  actions={[
    {
      icon: 'edit',
      tooltip: 'Edit Study',
      onClick: (event, rowData) => alert("Do you want to edit " + rowData.name + "?")
    },
    rowData => ({
      icon: 'clear',
      tooltip: 'Delete User',
      onClick: (event, rowData) => alert("You want to delete " + rowData.name),
      disabled: rowData.birthYear < 2000
    })
  ]}
  editable={{
    onRowAdd: newData =>
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          const data = [...state.data];
          data.push(newData);
          setState({ ...state, data });
        }, 600);
      }),
    onRowDelete: oldData =>
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          const data = [...state.data];
          data.splice(data.indexOf(oldData), 1);
          setState({ ...state, data });
        }, 600);
      }),
  }}
/>
</code>```

答:
to fix icons not showing you have to add :

```<code>import { forwardRef } from 'react';

import AddBox from '@material-ui/icons/AddBox';
import ArrowDownward from '@material-ui/icons/ArrowDownward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
  };

<MaterialTable
  icons={tableIcons}
  ...
/>
</code>```

official docs : https://github.com/mbrn/material-table

Body:
I'm trying to use Material-Table component - it's perfect for a table that I'm buildling (add, edit, delete and search rows). I've installed and used it as a child component of a page - everything works but...

STYLING: all custom and built-in styling in the page is lost in all the Material UI components (ie. AppBar buttons have no padding/spacing between, custom font styling is messed up).

ICONS: The icons in the table won't render - they just appear as large cut-off text.

Styling and icons on other pages without the table are not affected.

Anybody have a solve? Thanks in advance.

For icons, I tried reinstalling the library and importing. Also tried putting
html method. Snippet of the Material Table code is below.

<MaterialTable
  title="Editable Example"
  columns={state.columns}
  data={state.data}
  actions={[
    {
      icon: 'edit',
      tooltip: 'Edit Study',
      onClick: (event, rowData) => alert("Do you want to edit " + rowData.name + "?")
    },
    rowData => ({
      icon: 'clear',
      tooltip: 'Delete User',
      onClick: (event, rowData) => alert("You want to delete " + rowData.name),
      disabled: rowData.birthYear < 2000
    })
  ]}
  editable={{
    onRowAdd: newData =>
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          const data = [...state.data];
          data.push(newData);
          setState({ ...state, data });
        }, 600);
      }),
    onRowDelete: oldData =>
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          const data = [...state.data];
          data.splice(data.indexOf(oldData), 1);
          setState({ ...state, data });
        }, 600);
      }),
  }}
/>

Body:
to fix icons not showing you have to add :

import { forwardRef } from 'react';

import AddBox from '@material-ui/icons/AddBox';
import ArrowDownward from '@material-ui/icons/ArrowDownward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
  };

<MaterialTable
  icons={tableIcons}
  ...
/>

official docs : https://github.com/mbrn/material-table


问:
Why is a Node.js 12 docker app connection to MongoDB 4 via the docker network giving a timeout while a connection via the public network works?
I'm seeing a problem I can't explain at all:

After upgrading a Meteor app to v 1.9 and therefore Node.js 12 we also have to switch docker containers to Node.js 12 based containers. In our case we use abernix/meteord:node-12-base (git).

After booting up the updated app we get a DB timeout in the docker container of the app:

```<code>/bundle/bundle/programs/server/node_modules/fibers/future.js:313
                                               throw(ex);
                                               ^

MongoTimeoutError: Server selection timed out after 10000 ms
    at Timeout._onTimeout (/bundle/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoTimeoutError',
  [Symbol(mongoErrorContextSymbol)]: {}
}
</code>```

This happens with the following MONGO_URL:

❌ mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin

Funnily enough when we expose the port 27017 in the MongoDB container the following MONGO_URL just works:

✔ mongodb://root:OurPw@docker-host:27017/meteor?authSource=admin

Now I thought we are having a docker problem but if I attach to a bash inside the Node.js 12 meteord container, apt install the MongoDB shell and try to connect with:

✔ mongo "mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin"

that also just works.

And now I'm left without a clue. I tried multiple MongoDB docker images between v4.0 and 4.2.3 as well as Node.js 12.14 and 12.10. And I also tried without MongoDB auth one time just to rule it out as the problem but the outcome is always the same.

Any idea would be very much appreciated since I'd like to avoid having to connect via an exposed port and the docker host's name because that is prone to errors obviously...

答: Check the /etc/mOngd.conf file for the network binding. You may need to allow it to respond on all network interfaces as the network might be a different ip/subnet when exposed (or not) which might explain why it works in some scenarios</p>

Body:
I'm seeing a problem I can't explain at all:

After upgrading a Meteor app to v 1.9 and therefore Node.js 12 we also have to switch docker containers to Node.js 12 based containers. In our case we use abernix/meteord:node-12-base (git).

After booting up the updated app we get a DB timeout in the docker container of the app:

/bundle/bundle/programs/server/node_modules/fibers/future.js:313
                                               throw(ex);
                                               ^

MongoTimeoutError: Server selection timed out after 10000 ms
    at Timeout._onTimeout (/bundle/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoTimeoutError',
  [Symbol(mongoErrorContextSymbol)]: {}
}

This happens with the following MONGO_URL:

❌ mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin

Funnily enough when we expose the port 27017 in the MongoDB container the following MONGO_URL just works:

✔ mongodb://root:OurPw@docker-host:27017/meteor?authSource=admin

Now I thought we are having a docker problem but if I attach to a bash inside the Node.js 12 meteord container, apt install the MongoDB shell and try to connect with:

✔ mongo "mongodb://root:OurPw@mongo-docker-alias:27017/meteor?authSource=admin"

that also just works.

And now I'm left without a clue. I tried multiple MongoDB docker images between v4.0 and 4.2.3 as well as Node.js 12.14 and 12.10. And I also tried without MongoDB auth one time just to rule it out as the problem but the outcome is always the same.

Any idea would be very much appreciated since I'd like to avoid having to connect via an exposed port and the docker host's name because that is prone to errors obviously...


问:
Error when sending web push Notification : no endpoint?
I have created a basic app trying to send Push Notifications, using the web-push node library.
However, I am always confronted to the error  :" You must at least pass in an endpoint"
Which I do not understand, because I "suscribe" ( using the ServiceWorker Api subscribe() method ) , which create an endpoint to my localhost adress

In fact, I do not really know what to do to try to fix the problem

here is my code of "susbcribing" :

```<code>async   subscribe() {
   const sw = await navigator.serviceWorker.ready;
   const applicationServerPublicKey = 'BADCyHKPTCj1B9Knvmz2_EF1iLieHVZX2eEcCnMLvmMJA2ADlcDILgDC31ztGp1T1TznLpaJ14GQbdIM4APrr6k';
   const applicationServerKey = this.urlB64ToUint8Array(applicationServerPublicKey);
   console.log("le service worker est " + sw);
   sw.pushManager.subscribe({
       userVisibleOnly: true,
      applicationServerKey: applicationServerKey,
   }).then(
       subscription => {
           console.log("User is subscribed with the subscription : ");
           console.log(subscription);
</code>```

On the console I can see that in the "subscription" object there is an endpoint
and here is the code to send the  notification :

```<code>console.log("Juste avant d'envoyer la notif on veut envoyer à  :")
console.log(this.state.endpoint)

webpush.sendNotification(
  this.state.endpoint,
  payload,
  options
);
</code>```

but I get  on the console :

Juste avant d'envoyer la notif on veut envoyer à :

```<code> {
   "endpoint":"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdR_E1S96XSL7LdqLk2i5alH49Ae9v-XeOn1nX6Su9xkY6ETv16NybutJ5pBoA7q4nqHkNxFFJvVpP15JSsIiGPL8vQHSKAkyReS1CpdhTXc13IWllOb0qnFnfD5dFhNFqA9nIlJgAOz-rB3cy9v-AFbnhNh8S_Ea68WLVjIt8WKtPZWc",
   "keys": {
     "auth": "uXYi9oYQArgv_3Z1wD_gMQ",
     "p256dh": "BDpEEP6NWHFGNKY9PWx3wMzjirY98m4S4ntN0E8A0FlVZHZXaeCbc7WO0S0pqwju2SWM0-ivDkAvaFetPrBKMAU"
   }
}
</code>```

index.js:271

  Error: You must pass in a subscription with at least an endpoint.

答: Do console.log(subscription.endpoint) right before calling webPush.sendNotification(subscription, payload);. Had the same issue and the subscription.endpoint was indeed not set. Then make sure the subscription.endpoint is set.

Body:
I have created a basic app trying to send Push Notifications, using the web-push node library.
However, I am always confronted to the error  :" You must at least pass in an endpoint"
Which I do not understand, because I "suscribe" ( using the ServiceWorker Api subscribe() method ) , which create an endpoint to my localhost adress

In fact, I do not really know what to do to try to fix the problem

here is my code of "susbcribing" :

async   subscribe() {
   const sw = await navigator.serviceWorker.ready;
   const applicationServerPublicKey = 'BADCyHKPTCj1B9Knvmz2_EF1iLieHVZX2eEcCnMLvmMJA2ADlcDILgDC31ztGp1T1TznLpaJ14GQbdIM4APrr6k';
   const applicationServerKey = this.urlB64ToUint8Array(applicationServerPublicKey);
   console.log("le service worker est " + sw);
   sw.pushManager.subscribe({
       userVisibleOnly: true,
      applicationServerKey: applicationServerKey,
   }).then(
       subscription => {
           console.log("User is subscribed with the subscription : ");
           console.log(subscription);

On the console I can see that in the "subscription" object there is an endpoint
and here is the code to send the  notification :

console.log("Juste avant d'envoyer la notif on veut envoyer à  :")
console.log(this.state.endpoint)

webpush.sendNotification(
  this.state.endpoint,
  payload,
  options
);

but I get  on the console :

Juste avant d'envoyer la notif on veut envoyer à :

 {
   "endpoint":"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdR_E1S96XSL7LdqLk2i5alH49Ae9v-XeOn1nX6Su9xkY6ETv16NybutJ5pBoA7q4nqHkNxFFJvVpP15JSsIiGPL8vQHSKAkyReS1CpdhTXc13IWllOb0qnFnfD5dFhNFqA9nIlJgAOz-rB3cy9v-AFbnhNh8S_Ea68WLVjIt8WKtPZWc",
   "keys": {
     "auth": "uXYi9oYQArgv_3Z1wD_gMQ",
     "p256dh": "BDpEEP6NWHFGNKY9PWx3wMzjirY98m4S4ntN0E8A0FlVZHZXaeCbc7WO0S0pqwju2SWM0-ivDkAvaFetPrBKMAU"
   }
}

index.js:271

  Error: You must pass in a subscription with at least an endpoint.


问:
Find question text block in image with Python Opencv
How can I select question blocks in a jpg file with questions in Python code? The codes below select texts. I want to select question blocks with their choices.

```<code>import cv2

image = cv2.imread('test2.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9,9), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,30)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
dilate = cv2.dilate(thresh, kernel, iterations=4)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts\[0\] if len(cnts) == 2 else cnts\[1\]

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10000:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
        ROI = image\[y:y+h, x:x+w\]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.waitKey()
</code>```

Desired result:

I drew the rectangles in the picture with the mouse. There are no rectangles in the original picture.

The original file is here:

答:
A simple approach is to obtain a binary image and perform morphological operations
 to connect the text into a single contour. Here's the result:

Binary image

Dilate to connect contours

Result

Code

```<code>import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph operations
opening_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, opening_kernel, iterations=1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,50))
dilate = cv2.dilate(opening, kernel, iterations=2)

# Remove center line
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    x,y,w,h = cv2.boundingRect(c)
    ar = w / float(h)
    if area > 10000 and area < 12500 and ar < .5:
        cv2.drawContours(dilate, [c], -1, 0, -1)

# Dilate more
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,10))
dilate = cv2.dilate(dilate, kernel, iterations=3)

# Draw boxes
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100000:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)

cv2.imwrite('thresh.png', thresh)
cv2.imwrite('dilate.png', dilate)
cv2.imwrite('opening.png', opening)
cv2.imwrite('image.png', image)
cv2.waitKey()
</code>```

Body:
How can I select question blocks in a jpg file with questions in Python code? The codes below select texts. I want to select question blocks with their choices.

import cv2

image = cv2.imread('test2.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9,9), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,30)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
dilate = cv2.dilate(thresh, kernel, iterations=4)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts\[0\] if len(cnts) == 2 else cnts\[1\]

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10000:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
        ROI = image\[y:y+h, x:x+w\]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.waitKey()

Desired result:

I drew the rectangles in the picture with the mouse. There are no rectangles in the original picture.

The original file is here:

Body:
A simple approach is to obtain a binary image and perform morphological operations
 to connect the text into a single contour. Here's the result:

Binary image

Dilate to connect contours

Result

Code

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph operations
opening_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, opening_kernel, iterations=1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,50))
dilate = cv2.dilate(opening, kernel, iterations=2)

# Remove center line
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    x,y,w,h = cv2.boundingRect(c)
    ar = w / float(h)
    if area > 10000 and area < 12500 and ar < .5:
        cv2.drawContours(dilate, [c], -1, 0, -1)

# Dilate more
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,10))
dilate = cv2.dilate(dilate, kernel, iterations=3)

# Draw boxes
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100000:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)

cv2.imwrite('thresh.png', thresh)
cv2.imwrite('dilate.png', dilate)
cv2.imwrite('opening.png', opening)
cv2.imwrite('image.png', image)
cv2.waitKey()


问:
Using MongoDb Atlas full text search with multi-tenant collection ($searchBeta)
I have a MongoDb collection that holds data of thousands of tenants which are separated by a field holding the tenant ID.

I want to perform a query that includes full-text search & faceting on a specific tenant (see below).

Since the $searchBeta must be the first phase in the aggregation pipeline, it means it will return a huge list of documents from all tenants just to filter them out on $match phase instead of using an index.

Is there a more efficient way to perform such a query?

Running it with $searchBeta takes 14 seconds while removing it reduces query time to 6ms (while faceting works on more documents since it includes all tenant's data).

* Using Doug's answer bellow reduce it to ~70-120ms.

* Time measurement was done on Atlas free tier so it doesn't mean too much

```<code>db.tenantData.aggregate( [
{
    $searchBeta: {
        "search": {
        "query": "test",
        "path": ["name","comment"],
      }
    }
},
{
    $match: {tenant:"tenant1"},
},
{
    $facet: {
        "AssetTypeFacet": [
          { $sortByCount: "$assetType" }
        ],
        "manufacturerFacet": [
          { $sortByCount: "$manufacturer" }
        ]
    }
}
])
</code>```

答:
You could combine the query into a compound like so:

```<code>db.tenantData.aggregate([
  {
    $searchBeta: {
      compound: {
        should: {
          search: { query: "test", path: ["name", "comment"] },
        },
        filter: {
          search: { query: "tenant1", path: "tenant" },
        },
      },
    },
  },
  {
    $facet: {
      AssetTypeFacet: [{ $sortByCount: "$assetType" }],
      manufacturerFacet: [{ $sortByCount: "$manufacturer" }],
    },
  },
]);
</code>```

This will eliminate the IO associated with $match. There is currently no way to do faceting directly in $searchBeta other than the way you've done it.

Body:
I have a MongoDb collection that holds data of thousands of tenants which are separated by a field holding the tenant ID.

I want to perform a query that includes full-text search & faceting on a specific tenant (see below).

Since the $searchBeta must be the first phase in the aggregation pipeline, it means it will return a huge list of documents from all tenants just to filter them out on $match phase instead of using an index.

Is there a more efficient way to perform such a query?

Running it with $searchBeta takes 14 seconds while removing it reduces query time to 6ms (while faceting works on more documents since it includes all tenant's data).

* Using Doug's answer bellow reduce it to ~70-120ms.

* Time measurement was done on Atlas free tier so it doesn't mean too much

db.tenantData.aggregate( [
{
    $searchBeta: {
        "search": {
        "query": "test",
        "path": ["name","comment"],
      }
    }
},
{
    $match: {tenant:"tenant1"},
},
{
    $facet: {
        "AssetTypeFacet": [
          { $sortByCount: "$assetType" }
        ],
        "manufacturerFacet": [
          { $sortByCount: "$manufacturer" }
        ]
    }
}
])

Body:
You could combine the query into a compound like so:

db.tenantData.aggregate([
  {
    $searchBeta: {
      compound: {
        should: {
          search: { query: "test", path: ["name", "comment"] },
        },
        filter: {
          search: { query: "tenant1", path: "tenant" },
        },
      },
    },
  },
  {
    $facet: {
      AssetTypeFacet: [{ $sortByCount: "$assetType" }],
      manufacturerFacet: [{ $sortByCount: "$manufacturer" }],
    },
  },
]);

This will eliminate the IO associated with $match. There is currently no way to do faceting directly in $searchBeta other than the way you've done it.


问:
How to change SVG stroke color on mouse over when using an object
I am trying to make an svg image stroke color change when the mouse moves over the image. What I have now does not change the color of the stroke, and I am not sure why. If I manually change the stroke color through devtools it works fine.

I do notice that when I use an object to load an svg I get #document item in the inspector. Does that have any effect on why my color isn't changing when I mouse over the image?

    <object data="/images/icon.svg"></object>

```

```.nav-item {
    svg:hover {
        path {
            stroke: #da25e7;
        }
    }
}
```

答:
Looks like I can directly put the style within the svg file. The downside to this is that it is used everywhere, and places that I don't want a hover effect with the image will still have one.

<svg>

  <rect ...>...</rect>
</svg>
```

<p>Then include the file:</p>

<pre class="lang-html prettyprint-override"><code><object data="/images/icon.svg"></object>
</code>```

Body:
I am trying to make an svg image stroke color change when the mouse moves over the image. What I have now does not change the color of the stroke, and I am not sure why. If I manually change the stroke color through devtools it works fine.

I do notice that when I use an object to load an svg I get #document item in the inspector. Does that have any effect on why my color isn't changing when I mouse over the image?

    <object data="/images/icon.svg"></object>

.nav-item {
    svg:hover {
        path {
            stroke: #da25e7;
        }
    }
}

Body:
Looks like I can directly put the style within the svg file. The downside to this is that it is used everywhere, and places that I don't want a hover effect with the image will still have one.

<svg>
  <style>
    svg:hover path {stroke: #da25e7;}
  </style>
  <rect ...>...</rect>
</svg>

Then include the file:

<object data="/images/icon.svg"></object>


问:
Microsoft Teams bot - debug link unfurling
I'm trying to implement pretty simple teams bot but constantly facing an issues with unpredictable behavior. E.g. documentation clearly says that Teams applies Adaptive card as link unfurling response but when I'm sending pretty simple response like:

```<code>var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock { Text = "Title", Size = AdaptiveTextSize.ExtraLarge });
var attachment = new MessagingExtensionAttachment { ContentType = AdaptiveCard.ContentType, Content = card };
var result = new MessagingExtensionResult(AttachmentLayoutTypes.List, "result", new[] { attachment });
return new MessagingExtensionResponse(result);
</code>```

Teams doesn't render anything or follback to the default behavior.
So the question is - are there any way to debug why it doesn't work?

答:
one easy way to find out what's going on and if your part is generally ok is by sending a full "static" card as a test. Just create the JSON layout somewhere, load it and sent it unchanged to MS Teams.

Also creating AdaptiveCard's like that is not the best way to do it, have a look at https://learn.microsoft.com/en-us/adaptive-cards/templating/ its a lot easier to handle cards like that.

Specific to your question there's no real way to debug anything inside ms teams. You can get a few errors in the analytics part of the bot framework and some times console output of your browser gives a few hints.

I wrote a similar thing some time ago which inserts a card on specific links similar to what you're trying to do and generally, that was (and still is) working fine.

Body:
I'm trying to implement pretty simple teams bot but constantly facing an issues with unpredictable behavior. E.g. documentation clearly says that Teams applies Adaptive card as link unfurling response but when I'm sending pretty simple response like:

var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock { Text = "Title", Size = AdaptiveTextSize.ExtraLarge });
var attachment = new MessagingExtensionAttachment { ContentType = AdaptiveCard.ContentType, Content = card };
var result = new MessagingExtensionResult(AttachmentLayoutTypes.List, "result", new[] { attachment });
return new MessagingExtensionResponse(result);

Teams doesn't render anything or follback to the default behavior.
So the question is - are there any way to debug why it doesn't work?


问:
Use jq to merge keys with common id
consider a file 'b.json':

```<code>[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "should be replaced with 'foo new2'",
    "baz": "do not touch2"
  }
]
</code>```

and 'a.json':

```<code>[
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "don't care"
  }
]
</code>```

I want to update the key "foo" in b.json using jq with the matching value from a.json. It should also work with more than one entry in a.json.

Thus the desired output is:

```<code>[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "do not touch2"
  }
]
</code>```

答:
Here's a generic answer that makes no assumptions about the values of the .id keys except that they are distinct JSON values.

Generalization of INDEX/2

```<code>def type2: [type, if type == "string" then . else tojson end];

def dictionary(stream; f):
  reduce stream as $s ({}; setpath($s|f|type2; $s));

def lookup(value):
  getpath(value|type2);

def indictionary(value):
  (value|type2) as $t
  | has($t[0]) and (.[$t[0]] | has($t[1]));
</code>```

Invocation

```<code>jq --argfile a a.json -f program.jq b.json
</code>```

main

```<code>dictionary($a[]; .id) as $dict
| b
| map( .id as $id
       | if ($dict|indictionary($id))
         then .foo = ($dict|lookup($id).foo)
         else . end)
</code>```

Title: Use jq to merge keys with common id

Body:
consider a file 'b.json':

[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "should be replaced with 'foo new2'",
    "baz": "do not touch2"
  }
]

and 'a.json':

[
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "don't care"
  }
]

I want to update the key "foo" in b.json using jq with the matching value from a.json. It should also work with more than one entry in a.json.

Thus the desired output is:

[
  {
    "id": 3,
    "foo": "cannot be replaced, id isn't in a.json, stay untouched",
    "baz": "do not touch3"
  },
  {
    "id": 2,
    "foo": "foo new2",
    "baz": "do not touch2"
  }
]

Body:
Here's a generic answer that makes no assumptions about the values of the .id keys except that they are distinct JSON values.

Generalization of INDEX/2

def type2: [type, if type == "string" then . else tojson end];

def dictionary(stream; f):
  reduce stream as $s ({}; setpath($s|f|type2; $s));

def lookup(value):
  getpath(value|type2);

def indictionary(value):
  (value|type2) as $t
  | has($t[0]) and (.[$t[0]] | has($t[1]));

Invocation

jq --argfile a a.json -f program.jq b.json

main

dictionary($a[]; .id) as $dict
| b
| map( .id as $id
       | if ($dict|indictionary($id))
         then .foo = ($dict|lookup($id).foo)
         else . end)


问:
Compare 2 collections in MongoDB and put difference in 3rd
I have two collections in MongoDb and want to compare those and get the difference into another collections. Also is it possible to have a generic code for this.</p>

答: yep you can do just u need to use a setter for your 3rd property by using $set and other operators check this out: Query and Projection Operators</p>


问:
Categorical features correlation
I have some categorical features in my data along with continuous ones. Is it a good or absolutely bad idea to hot encode category features to find correlation of it to labels along with other continuous creatures?</p>

答:
I was looking to do same thing in BigQuery.
For numeric features you can use built in CORR(x,y) function.
For categorical features, you can calculate it as:
cardinality (cat1 x cat2) / max (cardinality(cat1),  cardinality(cat2).
Which translates to following SQL:

```<code>SELECT
COUNT(DISTINCT(CONCAT(cat1, cat2))) / GREATEST (COUNT(DISTINCT(cat1)), COUNT(DISTINCT(cat2))) as cat1_2,
COUNT(DISTINCT(CONCAT(cat1, cat3))) / GREATEST (COUNT(DISTINCT(cat1)), COUNT(DISTINCT(cat3))) as cat1_3,
....
FROM ...
</code>```

Higher number means lower correlation.

I used following python script to generate SQL:

```<code>import itertools

arr = range(1,10)

query = ',\n'.join(list('COUNT(DISTINCT(CONCAT({a}, {b}))) / GREATEST (COUNT(DISTINCT({a})), COUNT(DISTINCT({b}))) as cat{a}_{b}'.format(a=a,b=b)
  for (a,b) in itertools.combinations(arr,2)))
query = 'SELECT \n ' + query + '\n FROM  `...`;'
print (query)
</code>```

It should be straightforward to do same thing in numpy.

ContentLicense: CC BY-SA 3.0

Title: Categorical features correlation

Body:
I was looking to do same thing in BigQuery.
For numeric features you can use built in CORR(x,y) function.
For categorical features, you can calculate it as:
cardinality (cat1 x cat2) / max (cardinality(cat1),  cardinality(cat2).
Which translates to following SQL:

SELECT
COUNT(DISTINCT(CONCAT(cat1, cat2))) / GREATEST (COUNT(DISTINCT(cat1)), COUNT(DISTINCT(cat2))) as cat1_2,
COUNT(DISTINCT(CONCAT(cat1, cat3))) / GREATEST (COUNT(DISTINCT(cat1)), COUNT(DISTINCT(cat3))) as cat1_3,
....
FROM ...

Higher number means lower correlation.

I used following python script to generate SQL:

import itertools

arr = range(1,10)

query = ',\n'.join(list('COUNT(DISTINCT(CONCAT({a}, {b}))) / GREATEST (COUNT(DISTINCT({a})), COUNT(DISTINCT({b}))) as cat{a}_{b}'.format(a=a,b=b)
  for (a,b) in itertools.combinations(arr,2)))
query = 'SELECT \n ' + query + '\n FROM  `...`;'
print (query)

It should be straightforward to do same thing in numpy.


问:
How do I add a variable as a column value in a result set?
I have a variable that loops through values from a CSV file. As the loop returns result sets for each value I have in the CSV, I also want that value (the variable) returned in the result set. I tried to add my variable, $user, in my Select statement, but it just shows in the column header and my value is either blank or {}.

Here's the loop code:

$users = Get-Content C:\AD\ad_groups.txt

ForEach ($User in $users)
{
    Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,$user
}
```

答:
Your code might be only a handful of characters away from working.

You don't say what the format is of $User, but since it's something acceptable to the -Identity parameter that means, according to the documentation, it must be one of the following (links to output object property mine, interleaved with the code to select that value)...

Distinguished Name

Example:
  CN=saradavisreports,OU=europe,CN=users,DC=corp,DC=contoso,DC=com

Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,DistinguishedName
```

<blockquote>
  <p>GUID (objectGUID)</p>

  <p>Example: 599c3d2e-f72d-4d20-8a88-030d99495f20</p>
</blockquote>

<pre class="lang-bsh prettyprint-override"><code>Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,objectGUID
</code>```

Security Identifier (objectSid)

Example: S-1-5-21-3165297888-301567370-576410423-1103

Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,objectSid
```

Security Accounts Manager (SAM) Account Name (sAMAccountName)

Example: saradavisreports

(sAMAccountName property already selected in original code)

If $users contains identifiers in multiple formats, or you want to retain the exact text passed to Get-ADGroupMember, then you will need to use one of the other answers to select it as a property using a ScriptBlock.

Body:
Your code might be only a handful of characters away from working.

You don't say what the format is of $User, but since it's something acceptable to the -Identity parameter that means, according to the documentation, it must be one of the following (links to output object property mine, interleaved with the code to select that value)...

Distinguished Name

Example:
  CN=saradavisreports,OU=europe,CN=users,DC=corp,DC=contoso,DC=com

Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,DistinguishedName

GUID (objectGUID)

Example: 599c3d2e-f72d-4d20-8a88-030d99495f20

Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,objectGUID

Security Identifier (objectSid)

Example: S-1-5-21-3165297888-301567370-576410423-1103

Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,objectSid

Security Accounts Manager (SAM) Account Name (sAMAccountName)

Example: saradavisreports

(sAMAccountName property already selected in original code)

If $users contains identifiers in multiple formats, or you want to retain the exact text passed to Get-ADGroupMember, then you will need to use one of the other answers to select it as a property using a ScriptBlock.


问:
PowerShell Check User Group Membership
I am writing a powershell script to to change GPO Ownership and I am able to change the Ownership of the GPO's to a new user.  What I am wanting to do is verify that the current owner of the GPO is no long an employee.  This is for a school situation and there are Students and Employees.  Students belong to "Student Domain Users" while Employees belong to just "Domain Users".  I am able to pull all the groups a member belongs to, however, I want to use [bool] to just set true or false.

This is what I am working with

```<code>Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName

SamAccountName
--------------
Domain Users
Organization Management
Enterprise Admins
Domain Admins
Schema Admins
</code>```

In the above example I can see that the Domain Admins is listed.  I am trying to only pull that out with this code and I don't even know if it is possible.  Here is what I have tried and none have worked

Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName | select Domain Admins

Get-ADPrincipalGroupMembership -Identity 12345 | where {SamAccountName -like "Domain Admin"}

Thanks in advance for the help.

This is kind of what I am wanting to do with it as a verification process - this verifies that the person is no longer in the system at all and we need to clean stuff up.

$adtest = [bool] (Get-ADUser -Filter { SamAccountName -eq $input })

If they are in the system they could be a student and students are not going to be allowed access to GPO's so we need to remove them as owner.  Eventually all GPO's will be changed to Domain Admins owned and upon creation it will default to the Domain Admins.

答:
```<code>(Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname).SamAccountName | ? {$_ -eq "Domain Admins" }

# or

Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname | ? {$_.samAccountName -eq "Domain Admins" }

# Or Check the Domain Admins to see if Domain Admins contain the users you are looking for
Get-ADGroupMember -Identity "Domain Admins" | ? { $_.name -eq 12345 }
</code>```

First example gives you the string response with name, "Domain Admins" if it exists.

Second example gives you Object with SamAccountName property only since thats what you used in Select statement

Title: PowerShell Check User Group Membership

Body:
I am writing a powershell script to to change GPO Ownership and I am able to change the Ownership of the GPO's to a new user.  What I am wanting to do is verify that the current owner of the GPO is no long an employee.  This is for a school situation and there are Students and Employees.  Students belong to "Student Domain Users" while Employees belong to just "Domain Users".  I am able to pull all the groups a member belongs to, however, I want to use [bool] to just set true or false.

This is what I am working with

Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName

SamAccountName
--------------
Domain Users
Organization Management
Enterprise Admins
Domain Admins
Schema Admins

In the above example I can see that the Domain Admins is listed.  I am trying to only pull that out with this code and I don't even know if it is possible.  Here is what I have tried and none have worked

Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName | select Domain Admins

Get-ADPrincipalGroupMembership -Identity 12345 | where {SamAccountName -like "Domain Admin"}

Thanks in advance for the help.

This is kind of what I am wanting to do with it as a verification process - this verifies that the person is no longer in the system at all and we need to clean stuff up.

$adtest = [bool] (Get-ADUser -Filter { SamAccountName -eq $input })

If they are in the system they could be a student and students are not going to be allowed access to GPO's so we need to remove them as owner.  Eventually all GPO's will be changed to Domain Admins owned and upon creation it will default to the Domain Admins.

Body:
(Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname).SamAccountName | ? {$_ -eq "Domain Admins" }

# or

Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname | ? {$_.samAccountName -eq "Domain Admins" }

# Or Check the Domain Admins to see if Domain Admins contain the users you are looking for
Get-ADGroupMember -Identity "Domain Admins" | ? { $_.name -eq 12345 }

First example gives you the string response with name, "Domain Admins" if it exists.

Second example gives you Object with SamAccountName property only since thats what you used in Select statement


问:
Best way style on mouseover/mouseout Angular
I'm dealing with the following issue:

As you can see,  all of my elements are taking the mouseover instead of just one. There's a way with arrays on this thread but I don't know if it's the better suit for me.

Here's my component code.
I'm using an *ngFor to generate all of the necessary elements and with the event (mouseover) and (mouseend) change the style of the image to css display: none and css display: block.

component.html

  <ng-container *ngFor="let auto of autos">

      {{ auto.submarca }} - {{ auto.marca }}

        Pellentesque habitant morbi tristique senectus et netus et malesuada
        fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
        ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
        egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend
        leo.

  </ng-container>

```

<h2>component.ts</h2>

<pre class="lang-js prettyprint-override"><code>export class CuadrosComponent implements OnInit {
  autos: any;
  constructor() {}
  displayText: string;
  displayImage: string;
  ngOnInit() {
    this.autos = AUTOS;
    this.displayImage = "block";
    this.displayText = "none";
  }

  onMouseOver() {
    this.displayText = "block";
    this.displayImage = "none";
  }

  onMouseOut(auto, cardCuadroTag) {
    this.displayText = "none";
    this.displayImage = "block";
  }

  setImageOnError(img) {
    img.src = "/assets/images/autos/not-found.png";
  }
}
</code>```

答:
I already make a solution.
Getting the reference for my html element and acceding his children array where is the image to hide and the text to show and then just changing the style to display: block and vice versa.
Im noob lol.

  onMouseOver(cardCuadroTag) {
    cardCuadroTag.children["2"].style.display = "none";
    cardCuadroTag.children["1"].style.display = "block";
  }

  onMouseOut(cardCuadroTag) {
    cardCuadroTag.children["2"].style.display = "block";
    cardCuadroTag.children["1"].style.display = "none";
  }
```

Body:
I'm dealing with the following issue:

As you can see,  all of my elements are taking the mouseover instead of just one. There's a way with arrays on this thread but I don't know if it's the better suit for me.

Here's my component code.
I'm using an *ngFor to generate all of the necessary elements and with the event (mouseover) and (mouseend) change the style of the image to css display: none and css display: block.

component.html

  <ng-container *ngFor="let auto of autos">

      {{ auto.submarca }} - {{ auto.marca }}

        Pellentesque habitant morbi tristique senectus et netus et malesuada
        fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
        ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
        egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend
        leo.

  </ng-container>

component.ts

export class CuadrosComponent implements OnInit {
  autos: any;
  constructor() {}
  displayText: string;
  displayImage: string;
  ngOnInit() {
    this.autos = AUTOS;
    this.displayImage = "block";
    this.displayText = "none";
  }

  onMouseOver() {
    this.displayText = "block";
    this.displayImage = "none";
  }

  onMouseOut(auto, cardCuadroTag) {
    this.displayText = "none";
    this.displayImage = "block";
  }

  setImageOnError(img) {
    img.src = "/assets/images/autos/not-found.png";
  }
}


问:
Determine the selected days of the week from row in sysschedules table?
Based on the SQLServer's dbo.sysschedules table:

freq_type  int

How frequently a job runs for this schedule.

freq_interval  int

Days that the job is executed. Depends on the value of freq_type. The
default value is 0, which indicates that freq_interval is unused. See
the table below for the possible values and their effects.

If the freq_type column is 8 (weekly) and the freq_interval column is 38

How do you determine the selected days of the week given their values:

```<code>1,2,4,8,16,32,64 for Su,M,T,W,Th,F,S
</code>```

I'm looking for SQL Server or C# answers.

答:
Microsoft seems to have an example in their C# documentation on enumeration types. Elegant enough for me. I adjusted the Day enum assignments to match those that SQLServer uses for the freq_interval.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum#enumeration-types-as-bit-flags

```<code>[Flags]
public enum Days
{
    Sunday    = 0b_0000_0001,  // 1
    Monday   = 0b_0000_0010,  // 2
    Tuesday = 0b_0000_0100,  // 4
    Wednesday  = 0b_0000_1000,  // 8
    Thursday    = 0b_0001_0000,  // 16
    Friday  = 0b_0010_0000,  // 32
    Saturday    = 0b_0100_0000,  // 64
}
public class FlagsEnumExample
{
    public static void Main()
    {
        var a = (Days)38;
        Console.WriteLine(a);
        // Output:
        // Monday, Tuesday, Friday
    }
}
</code>```

Body:
Based on the SQLServer's dbo.sysschedules table:

freq_type  int

How frequently a job runs for this schedule.

freq_interval  int

Days that the job is executed. Depends on the value of freq_type. The
default value is 0, which indicates that freq_interval is unused. See
the table below for the possible values and their effects.

If the freq_type column is 8 (weekly) and the freq_interval column is 38

How do you determine the selected days of the week given their values:

1,2,4,8,16,32,64 for Su,M,T,W,Th,F,S

I'm looking for SQL Server or C# answers.

Body:
Microsoft seems to have an example in their C# documentation on enumeration types. Elegant enough for me. I adjusted the Day enum assignments to match those that SQLServer uses for the freq_interval.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum#enumeration-types-as-bit-flags

[Flags]
public enum Days
{
    Sunday    = 0b_0000_0001,  // 1
    Monday   = 0b_0000_0010,  // 2
    Tuesday = 0b_0000_0100,  // 4
    Wednesday  = 0b_0000_1000,  // 8
    Thursday    = 0b_0001_0000,  // 16
    Friday  = 0b_0010_0000,  // 32
    Saturday    = 0b_0100_0000,  // 64
}
public class FlagsEnumExample
{
    public static void Main()
    {
        var a = (Days)38;
        Console.WriteLine(a);
        // Output:
        // Monday, Tuesday, Friday
    }
}


问:
Trying to stop a single thread out of multiple running at the same time in java
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

```<code>public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}
</code>```

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

```<code>public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}
</code>```

答:
I would suggest you try to avoid Threads. The Animation API is designed to make doing work that would normally be done in a Thread easier. In this example, the IncrementingTimer class consists of two Labels and three Buttons. The Labels are used to show the time. The Buttons are used to control the Timeline. The Timeline is used to increment the Labels value each second or every sixty seconds. I have added three IncrementingTimers to the app.

Main

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {
        var scene = new Scene(new VBox(new IncrementingTimer(), new IncrementingTimer(), new IncrementingTimer()), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
</code>```

IncrementingTimer

```<code>import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
final public class IncrementingTimer extends HBox
{
    IntegerProperty secondsCounter = new SimpleIntegerProperty();//Keeps up with seconds
    IntegerProperty minutesCounter = new SimpleIntegerProperty();//Keeps up with minutes

    Label lblSeconds = new Label();//Displays the seconds
    Label lblMinutes = new Label();//Displays the minutes
    Label lblColon = new Label(":");//Display the colon between minutes and seconds

    Button btnPlay = new Button("Play");//Plays the Timeline
    Button btnStop = new Button("Stop");//Stops the Timeline
    Button btnPause = new Button("Pause");//Pauses the Timeline

    Timeline timeline;//Used to run code that changes the Labels. This Timeline runs every one second.

    public IncrementingTimer()
    {
        lblSeconds.textProperty().bind(secondsCounter.asString("%02d"));//Binds the seconds label to the seconds counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.
        lblMinutes.textProperty().bind(minutesCounter.asString("%02d"));//Binds the minutes label to the minutes counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.

        getChildren().addAll(lblMinutes, lblColon, lblSeconds, btnPlay, btnStop, btnPause);

        timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {//Replace the one with .016 to speed this up for testing purposes.
            secondsCounter.set(secondsCounter.get() + 1);
            if (secondsCounter.get() == 60) {
                secondsCounter.set(0);
                minutesCounter.set(minutesCounter.get() + 1);
                if (minutesCounter.get() == 60) {
                    minutesCounter.set(0);
                }
            }
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);
        btnPlay.setOnAction((event) -> {
            timeline.play();
        });
        btnPause.setOnAction((event) -> {
            timeline.pause();
        });
        btnStop.setOnAction((event) -> {
            timeline.stop();
            secondsCounter.set(0);
            minutesCounter.set(0);
        });

        this.setAlignment(Pos.CENTER);
    }

}
</code>```

Body:
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}

Body:
I would suggest you try to avoid Threads. The Animation API is designed to make doing work that would normally be done in a Thread easier. In this example, the IncrementingTimer class consists of two Labels and three Buttons. The Labels are used to show the time. The Buttons are used to control the Timeline. The Timeline is used to increment the Labels value each second or every sixty seconds. I have added three IncrementingTimers to the app.

Main

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {
        var scene = new Scene(new VBox(new IncrementingTimer(), new IncrementingTimer(), new IncrementingTimer()), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

IncrementingTimer

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
final public class IncrementingTimer extends HBox
{
    IntegerProperty secondsCounter = new SimpleIntegerProperty();//Keeps up with seconds
    IntegerProperty minutesCounter = new SimpleIntegerProperty();//Keeps up with minutes

    Label lblSeconds = new Label();//Displays the seconds
    Label lblMinutes = new Label();//Displays the minutes
    Label lblColon = new Label(":");//Display the colon between minutes and seconds

    Button btnPlay = new Button("Play");//Plays the Timeline
    Button btnStop = new Button("Stop");//Stops the Timeline
    Button btnPause = new Button("Pause");//Pauses the Timeline

    Timeline timeline;//Used to run code that changes the Labels. This Timeline runs every one second.

    public IncrementingTimer()
    {
        lblSeconds.textProperty().bind(secondsCounter.asString("%02d"));//Binds the seconds label to the seconds counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.
        lblMinutes.textProperty().bind(minutesCounter.asString("%02d"));//Binds the minutes label to the minutes counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.

        getChildren().addAll(lblMinutes, lblColon, lblSeconds, btnPlay, btnStop, btnPause);

        timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {//Replace the one with .016 to speed this up for testing purposes.
            secondsCounter.set(secondsCounter.get() + 1);
            if (secondsCounter.get() == 60) {
                secondsCounter.set(0);
                minutesCounter.set(minutesCounter.get() + 1);
                if (minutesCounter.get() == 60) {
                    minutesCounter.set(0);
                }
            }
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);
        btnPlay.setOnAction((event) -> {
            timeline.play();
        });
        btnPause.setOnAction((event) -> {
            timeline.pause();
        });
        btnStop.setOnAction((event) -> {
            timeline.stop();
            secondsCounter.set(0);
            minutesCounter.set(0);
        });

        this.setAlignment(Pos.CENTER);
    }

}


问:
ISerialization Constructor not getting called
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

```<code>public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }
</code>```

If I send the following XML to be deserialzed

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>
</code>```

using the following code to deserialize

```<code>serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");
</code>```

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>
</code>```

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

答:
To customise XML serialization I believe you need to use IXmlSerializable rather than ISerializable.

I think that requires a parameterless constructor, and you then need to implement ReadXml and WriteXml. In other words, it doesn't use the same constructor as binary serialization.

OwnerDisplayName: Paleta

ContentLicense: CC BY-SA 2.5

Body:
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }

If I send the following XML to be deserialzed

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>

using the following code to deserialize

serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

LastEditorDisplayName: Paleta

OwnerDisplayName: Jon Skeet


问:
Rules for binding query parameters in Razor Pages
In Razor Pages, it is quite convenient that if you were to call, for example,

```<code>http://localhost/foo?bar=42
</code>```

In the corresponding model, the bar key is automatically accessible in the OnGet constructor

```<code>public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}
</code>```

But what if the query parameter is poo?

```<code>http://localhost/foo?poo=42
</code>```

then in the model, bar does not get the value 42.

So simple enough, get the variables to match the query parameter key. But what if the key is hyphenated?

```<code>http://localhost/foo?foo-bar=42
</code>```

foo-bar is definitely not an acceptable variable name. How do I access this query parameter? What are the rules here?

In my specific case, I don't really have a choice but to receive these hyphenated query string parameters. Also, I'm on .net core 2.2.

答:
The simplest solution in Razor Pages is to use Request.Query:

```<code>public void OnGet()
{
    var data = Request.Query["foo-bar"];
}
</code>```

Body:
In Razor Pages, it is quite convenient that if you were to call, for example,

http://localhost/foo?bar=42

In the corresponding model, the bar key is automatically accessible in the OnGet constructor

public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}

But what if the query parameter is poo?

http://localhost/foo?poo=42

then in the model, bar does not get the value 42.

So simple enough, get the variables to match the query parameter key. But what if the key is hyphenated?

http://localhost/foo?foo-bar=42

foo-bar is definitely not an acceptable variable name. How do I access this query parameter? What are the rules here?

In my specific case, I don't really have a choice but to receive these hyphenated query string parameters. Also, I'm on .net core 2.2.

Body:
The simplest solution in Razor Pages is to use Request.Query:

public void OnGet()
{
    var data = Request.Query["foo-bar"];
}


问:
Unpacking an php array
So i'm printing an array that i'm getting but i can't figure out how to access the stuff, im an complete noob by the way.

Thing i want to unpack:

code:

```<code><?php
    $file = $_FILES['files'];

    $fileName = $_FILES['files']['name'];
    $fileTmpName = $_FILES['files']['tmp_name'];
    $fileSize = $_FILES['files']['size'];
    $fileError = $_FILES['files']['error'];
    $fileType = $_FILES['files']['type'];

    print_r(in_array("screenshot.jpg", $fileName)."woooo");

    print_r($file);
    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', "jpeg", "png", "pdf");

    if (in_array($fileActualExt, $allowed)){
        if ($fileError === 0) {
            if($fileSize < 1000000) {
                $fileNameNew =  uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;

                move_uploaded_file($fileTmpName, $fileDestination);

            } else {
                echo 'You can not have a file bigger than 1 GigaByte!';
            }
        }else {
            print_r($fileError);
            echo 'There was an error uploading your file!';
        }
    }else {
        echo "You cannot upload files of this type!";
}
</code>```

but i do not know how to print the name that first name that im getting.

答:
You have a multiple file selector in your form, so all the elements of $_FILES are arrays, to allow for uploading multiple files. So you need to loop over them.

```<code><?php
$file = $_FILES['files'];

foreach ($_FILES['files']['name'] as $i => $fileName) {
    $fileTmpName = $_FILES['files']['tmp_name'][$i];
    $fileSize = $_FILES['files']['size'][$i];
    $fileError = $_FILES['files']['error'][$i];
    $fileType = $_FILES['files']['type'][$i];

    print_r(in_array("screenshot.jpg", $fileName)."woooo");

    print_r($file);
    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', "jpeg", "png", "pdf");

    if (in_array($fileActualExt, $allowed)){
        if ($fileError === 0) {
            if($fileSize < 1000000) {
                $fileNameNew =  uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;

                move_uploaded_file($fileTmpName, $fileDestination);

            } else {
                echo 'You can not have a file bigger than 1 GigaByte!';
            }
        }else {
            print_r($fileError);
            echo 'There was an error uploading your file!';
        }
    }else {
        echo "You cannot upload files of this type!";
    }
}
</code>```

Title: Unpacking an php array

Body:
So i'm printing an array that i'm getting but i can't figure out how to access the stuff, im an complete noob by the way.

Thing i want to unpack:

code:

<?php
    $file = $_FILES['files'];

    $fileName = $_FILES['files']['name'];
    $fileTmpName = $_FILES['files']['tmp_name'];
    $fileSize = $_FILES['files']['size'];
    $fileError = $_FILES['files']['error'];
    $fileType = $_FILES['files']['type'];

    print_r(in_array("screenshot.jpg", $fileName)."woooo");

    print_r($file);
    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', "jpeg", "png", "pdf");

    if (in_array($fileActualExt, $allowed)){
        if ($fileError === 0) {
            if($fileSize < 1000000) {
                $fileNameNew =  uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;

                move_uploaded_file($fileTmpName, $fileDestination);

            } else {
                echo 'You can not have a file bigger than 1 GigaByte!';
            }
        }else {
            print_r($fileError);
            echo 'There was an error uploading your file!';
        }
    }else {
        echo "You cannot upload files of this type!";
}

but i do not know how to print the name that first name that im getting.

Body:
You have a multiple file selector in your form, so all the elements of $_FILES are arrays, to allow for uploading multiple files. So you need to loop over them.

<?php
$file = $_FILES['files'];

foreach ($_FILES['files']['name'] as $i => $fileName) {
    $fileTmpName = $_FILES['files']['tmp_name'][$i];
    $fileSize = $_FILES['files']['size'][$i];
    $fileError = $_FILES['files']['error'][$i];
    $fileType = $_FILES['files']['type'][$i];

    print_r(in_array("screenshot.jpg", $fileName)."woooo");

    print_r($file);
    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', "jpeg", "png", "pdf");

    if (in_array($fileActualExt, $allowed)){
        if ($fileError === 0) {
            if($fileSize < 1000000) {
                $fileNameNew =  uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;

                move_uploaded_file($fileTmpName, $fileDestination);

            } else {
                echo 'You can not have a file bigger than 1 GigaByte!';
            }
        }else {
            print_r($fileError);
            echo 'There was an error uploading your file!';
        }
    }else {
        echo "You cannot upload files of this type!";
    }
}


问:
how to remove(toggle) 'active' classlist that is already selected
I'm struggling with removing 'active' class from a link that is already selected.

Looking at the line 20 in JavaScript. Shouldn't classLink.toggle add / remove "active" on clickedElement?
I even tried few approaches like

```<code> if (clickedElement.classList.contains('active')) {
  clickedElement.classList.remove('active');
} else {
  clickedElement.classList.add('active');
}
</code>```

but none seem to work on this particular class (works fine on any other class i add).
What am i missing?

https://jsfiddle.net/Evenclan/09sn2kd3/15/

答:
classList includes a toggle method.

```<code>this.classList.toggle('active');
</code>```

How to toggle class using pure javascript in html

EDIT:
The JsFiddle you included is working. I opened the console and clicked the different links and they were toggling active properly.

Body:
I'm struggling with removing 'active' class from a link that is already selected.

Looking at the line 20 in JavaScript. Shouldn't classLink.toggle add / remove "active" on clickedElement?
I even tried few approaches like

 if (clickedElement.classList.contains('active')) {
  clickedElement.classList.remove('active');
} else {
  clickedElement.classList.add('active');
}

but none seem to work on this particular class (works fine on any other class i add).
What am i missing?

https://jsfiddle.net/Evenclan/09sn2kd3/15/

Body:
classList includes a toggle method.

this.classList.toggle('active');

How to toggle class using pure javascript in html

EDIT:
The JsFiddle you included is working. I opened the console and clicked the different links and they were toggling active properly.


问:
can't import custom python module in vscode
I'm trying to get my vscode project to mimic functionality that pycharm is able to produce. With pycharm, I'm able to create, via an XML, a custom pycharm project file that lists the various different sources of the different folder locations of the custom modules I need to have available.

In vscode, I'm going about this by creating a workspace file and adding these sources as folders in the JSON object. The workspace will populate properly in vscode, but when I try to reference an import, Intellisense is able to see the module I'm trying to import 1 but when I try to start a debug session, vscode barfs and says it can't find this module 2.

My folder structure is:

workspace

|--> obscura

|-->|--> obscura

|-->|-->|--> database.py

|-->|--> obscura_test

|-->|-->|--> mytestfile.py --- where I'm starting debug session

Here are the screenshots:

-- Intellisense shows what the module is

-- Vscode fails on debug

答:
This is what I did in my python project in VSCode

If my module is a class

from folder_name.python_file_name_without_extension import class_name

# then I can use it as follow
class_name.function_name()
```

<p>If my module is just a script</p>

<pre class="lang-py prettyprint-override"><code>from folder_name.python_file_name_without_extension import function_name

# then I can use it as follow
function_name()
</code>```

Body:
This is what I did in my python project in VSCode

If my module is a class

from folder_name.python_file_name_without_extension import class_name

# then I can use it as follow
class_name.function_name()

If my module is just a script

from folder_name.python_file_name_without_extension import function_name

# then I can use it as follow
function_name()


问:
Is there any flow diagram or wai-aria "debugger" about how the reader should read the web page?
I'm working on the accessibility of a page.

I think that I understand the examples I see at WAI-ARIA Authoring Practices 1.1 and I keep reading it.

I'm pretty lost now trying NVDA Reader will read a modal form deep inside a

.. "lasagna"

My Question is: Is there any aria "debugger" that could tell me why or why not is reading some word or why it stop reads? or, which is the best way to approach this "debug" job?

Is it very inefficient to change aria-* attributes randomly...?

Thanks a lot.

答:
No, there's not really any debugger for aria or accessibility. All assistive tech (NVDA, JAWS, ChromeVox, etc) have slightly different behavior, and it also depends on the browser and OS. There isn't a debugger or tool that will tell us what should happen as each tech combiniation has its own interaction and result. It drives us all crazy to be sure.

The closest we can get is to determine what 'should' happen in a best case scenario. For that, we have examples from the W3, Mozilla documentation, and other reputable sources.
Best most of us can do is test on the platforms that 'most' users will be using and make sure those are solid.

To help debug your particular case, you can try checking the accessibility tree in something like the Chrome inspector. Open the Accessibility tab in the inspector (near Styles, Computed, Event Listeners, etc), and it should tell you what assistive tech will be able to see (at least, while using Chrome). If you're expecting a text node and you see 'Ignored. Accessibility node not exposed', that's a clue.

As a side note, NVDA only reads a line or so at a time if you're on a massive block of text. You'll need to keep hitting down arrow to hear the rest. I assume that's not your issue, but FYI just in case.


问:
Is there a way to retrieve the value of object instead of its ID?
Is there any way to retrieve the object instead of the ID (pk) when using django.core.serializers.serialize.

I have a model named MenuItem with a ManyToManyField releated to a MenuSubItem.

When I execute this code serializers.serialize('json', MenuItem.objects.all()) I got

```<code>{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**3**]}}
</code>```

But what I really wanna get is

```<code>{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**objects or objects_attribute**]}}
</code>```

Or if there is a workaround using other libs

答:
Possible, It's actually a very common thing to do in APIs that there's an article in the docs about it, have a look at DRF serializer relations, This is called a nested serialization, When you want to serializer something that has another something serializable in it, DRF is very fun to learn, There's also JustDjango on YouTube who's explaining some basics to work with DRF

Your code should look look

```<code>class mySerializer(serializers.ModelSerializer):

    Meta:
        model = myModelThatIwantToNest
        fields = ['....']

class myOtherSerializer(serializers.ModeSerializer):
    myModelThatIwantToNest = mySerializer();
    Meta:
        model = myOtherModel
        fields = ['myModelThatIwantToNest', '...']

</code>```

Body:
Is there any way to retrieve the object instead of the ID (pk) when using django.core.serializers.serialize.

I have a model named MenuItem with a ManyToManyField releated to a MenuSubItem.

When I execute this code serializers.serialize('json', MenuItem.objects.all()) I got

{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**3**]}}

But what I really wanna get is

{'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**objects or objects_attribute**]}}

Or if there is a workaround using other libs

Body:
Possible, It's actually a very common thing to do in APIs that there's an article in the docs about it, have a look at DRF serializer relations, This is called a nested serialization, When you want to serializer something that has another something serializable in it, DRF is very fun to learn, There's also JustDjango on YouTube who's explaining some basics to work with DRF

Your code should look look

class mySerializer(serializers.ModelSerializer):

    Meta:
        model = myModelThatIwantToNest
        fields = ['....']

class myOtherSerializer(serializers.ModeSerializer):
    myModelThatIwantToNest = mySerializer();
    Meta:
        model = myOtherModel
        fields = ['myModelThatIwantToNest', '...']


问:
Identical bases conflict in multiple empty member optimization
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));
```

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

答:
This was surprisingly hard. The following code allows inheriting from an arbitrary list of types and each type of the list will be used exactly once as base:

```<code>#include <type_traits>

template<class T, class... Ts>
struct is_among;

template<class T, class... Ts>
struct is_among<T, T, Ts...> : std::true_type {
    using value_t = T;
};

template<class T, class U, class... Ts>
struct is_among<T, U, Ts...> : is_among<T, Ts...> {};

template<class T>
struct is_among<T> : std::false_type{};

template<class SFINAE, class... Ts>
struct inherit_once;

template<class T, class... Ts>
struct inherit_once<std::enable_if_t<!is_among<T, Ts...>::value>,T, Ts...> : inherit_once<void, Ts...>, T {};

template<class T, class... Ts>
struct inherit_once< std::enable_if_t<is_among<T, Ts...>::value>, T, Ts...> : inherit_once<void, Ts...> {};

template<>
struct inherit_once<void>{};

struct A{
    void operator()(int){}
    };

struct B : inherit_once<void, A, A> {
    int i;
};
int main(){
    static_assert(sizeof(int) == sizeof(B));
    B b;
    b(1);
}
</code>```

Edit: Having multiple instances:

```<code>#include <utility>

template<class F, size_t id>
struct id_wrap: F {};

template<class id_seq, class... Funcs>
struct OptHelper;

template<class... Funcs, size_t... ids>
struct OptHelper<std::index_sequence<ids...>, Funcs...> : id_wrap<Funcs, ids>... {};

template<class... Funcs>
struct Opt: OptHelper<std::index_sequence_for<Funcs...>, Funcs...> {int i;};

struct Functor {
    void operator()(int) {}
};

int main(int argc, char *argv[])
{
    static_assert(sizeof(Opt<Functor,Functor>) == sizeof(int));
    Opt<Functor> f{};
    f(1);
}
</code>```

Body:
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

Body:
This was surprisingly hard. The following code allows inheriting from an arbitrary list of types and each type of the list will be used exactly once as base:

#include <type_traits>

template<class T, class... Ts>
struct is_among;

template<class T, class... Ts>
struct is_among<T, T, Ts...> : std::true_type {
    using value_t = T;
};

template<class T, class U, class... Ts>
struct is_among<T, U, Ts...> : is_among<T, Ts...> {};

template<class T>
struct is_among<T> : std::false_type{};

template<class SFINAE, class... Ts>
struct inherit_once;

template<class T, class... Ts>
struct inherit_once<std::enable_if_t<!is_among<T, Ts...>::value>,T, Ts...> : inherit_once<void, Ts...>, T {};

template<class T, class... Ts>
struct inherit_once< std::enable_if_t<is_among<T, Ts...>::value>, T, Ts...> : inherit_once<void, Ts...> {};

template<>
struct inherit_once<void>{};

struct A{
    void operator()(int){}
    };

struct B : inherit_once<void, A, A> {
    int i;
};
int main(){
    static_assert(sizeof(int) == sizeof(B));
    B b;
    b(1);
}

Edit: Having multiple instances:

#include <utility>

template<class F, size_t id>
struct id_wrap: F {};

template<class id_seq, class... Funcs>
struct OptHelper;

template<class... Funcs, size_t... ids>
struct OptHelper<std::index_sequence<ids...>, Funcs...> : id_wrap<Funcs, ids>... {};

template<class... Funcs>
struct Opt: OptHelper<std::index_sequence_for<Funcs...>, Funcs...> {int i;};

struct Functor {
    void operator()(int) {}
};

int main(int argc, char *argv[])
{
    static_assert(sizeof(Opt<Functor,Functor>) == sizeof(int));
    Opt<Functor> f{};
    f(1);
}