问:
Asp.Net MVC - Change error class name
When I do field validation in Asp.Net MVC, it's generated the following error css classes :

input-validation-error

field-validation-error

Is there a way that I can change the names of the error classes that are generated?

I use xVal.

答:
Here's what I did:</p>

```<code>private void ChangeValidationClassNames()
{
    var helper = new HtmlHelper(new ViewContext(), new ViewPage());
    SetPublicStaticReadonly("ValidationInputCssClassName", helper, "errInput");
    SetPublicStaticReadonly("ValidationMessageCssClassName", helper, "errMsg");
}

public void SetPublicStaticReadonly(string readonlyPropName, object instance, object value)
{
    var field = instance.GetType().GetField(readonlyPropName, BindingFlags.Static | BindingFlags.Public);
    if (field == null)
        throw new NullReferenceException(string.Format("public static readonly field '{0}' not found in '{1}'", readonlyPropName, instance));
    field.SetValue(instance, value);
}
</code>```

Title: Asp.Net MVC - Change error class name

Body:
Here's what I did:

private void ChangeValidationClassNames()
{
    var helper = new HtmlHelper(new ViewContext(), new ViewPage());
    SetPublicStaticReadonly("ValidationInputCssClassName", helper, "errInput");
    SetPublicStaticReadonly("ValidationMessageCssClassName", helper, "errMsg");
}

public void SetPublicStaticReadonly(string readonlyPropName, object instance, object value)
{
    var field = instance.GetType().GetField(readonlyPropName, BindingFlags.Static | BindingFlags.Public);
    if (field == null)
        throw new NullReferenceException(string.Format("public static readonly field '{0}' not found in '{1}'", readonlyPropName, instance));
    field.SetValue(instance, value);
}


来源: stackexchange

问:
How to authenticate to Cloud Storage from a Docker app on Cloud Run
I have a Node.js app in a Docker container that I'm trying to deploy to Google Cloud Run.

I want my app to be able to read/write files from my GCS buckets that live under the same project, and I haven't been able to find much information around it.

This is what I've tried so far:

1. Hoping it works out of the box

A.k.a. initializing without credentials, like in App Engine.

const { Storage } = require('@google-cloud/storage');

// ...later in an async function

const storage = new Storage();

// This line throws the exception below
const [file] = await storage.bucket('mybucket')
  .file('myfile.txt')
  .download()
```

<p>The last line throws this exception</p>

```{ Error: Could not refresh access token: Unsuccessful response status code. Request failed with status code 500"
    at Gaxios._request (/server/node_modules/gaxios/build/src/gaxios.js:85:23)

```

<h3>2. Hoping it works out of the box after setting the Storage Admin IAM role to my Cloud Run service accounts.</h3>

<p>Nope. No difference with previous.</p>

<h3>3. Copying my credentials file as a <code>cloudbuild.yaml</code> step:</h3>

```...
- name: 'gcr.io/cloud-builders/gsutil'
    args: ['cp', 'gs://top-secret-bucket/gcloud-prod-credentials.json', '/www/gcloud-prod-credentials.json']
...
```

It copies the file just fine, but then the file is nor visible from my app. I'm still not sure where exactly it was copied to, but listing the /www directory from my app shows no trace of it.

4. Copy my credentials file as a Docker step

Wait, but for that I need to authenticate gsutil, and for that I need the credentials.

So...

What options do I have without uploading my credentials file to version control?

答:
This is how I managed to make it work:

The code for initializing the client library was correct. No changes here from the original question. You don't need to load any credentials if the GCS bucket belongs to the same project as your Cloud Run service.

I learned that the service account [myprojectid]-compute@developer.gserviceaccount.com (aka "Compute Engine default service account") is the one used by default for running the Cloud Run service unless you specify a different one.

I went to the Service Accounts page and made sure that the mentioned service account was enabled (mine wasn't, this was what I was missing).

Then I went here, edited the permissions for the mentioned service account and added the Storage Object Admin role.

More information on this article: https://cloud.google.com/run/docs/securing/service-identity

ContentLicense: CC BY-SA 4.0

Body:
I have a Node.js app in a Docker container that I'm trying to deploy to Google Cloud Run.

I want my app to be able to read/write files from my GCS buckets that live under the same project, and I haven't been able to find much information around it.

This is what I've tried so far:

1. Hoping it works out of the box

A.k.a. initializing without credentials, like in App Engine.

const { Storage } = require('@google-cloud/storage');

// ...later in an async function

const storage = new Storage();

// This line throws the exception below
const [file] = await storage.bucket('mybucket')
  .file('myfile.txt')
  .download()

The last line throws this exception

{ Error: Could not refresh access token: Unsuccessful response status code. Request failed with status code 500"
    at Gaxios._request (/server/node_modules/gaxios/build/src/gaxios.js:85:23)

2. Hoping it works out of the box after setting the Storage Admin IAM role to my Cloud Run service accounts.

Nope. No difference with previous.

3. Copying my credentials file as a cloudbuild.yaml step:

...
- name: 'gcr.io/cloud-builders/gsutil'
    args: ['cp', 'gs://top-secret-bucket/gcloud-prod-credentials.json', '/www/gcloud-prod-credentials.json']
...

It copies the file just fine, but then the file is nor visible from my app. I'm still not sure where exactly it was copied to, but listing the /www directory from my app shows no trace of it.

4. Copy my credentials file as a Docker step

Wait, but for that I need to authenticate gsutil, and for that I need the credentials.

So...

What options do I have without uploading my credentials file to version control?


问:
Erlang node communication - port forwarding
I have two erlang clients:

client@192.168.1.5

client@192.168.1.6

And one remote erlang server with global IP address “externalIP1”:

server@“externalIP1”

To connect the clients and the server by a two-way communication, I’m going to forward client machines through the second global IP address “externalIP2” on my router.

Which ports do I have to forward for The clients?

How to name erlang client nodes? After the forwarding actually they’ll be at one IP address for remote nodes!

How to tell to the server something like “work with ports .., .., .., during communication with node X”?

Thanks in advance!

答:
Port forwarding ? you mean NAT or SSH ?

I feel using SSH port forwarding is a way more easier to setup for erlang distribution . Please check the third answer in Run Erlang Observer with ssh port forwarding

Or else you alternatively try epmdless Erlang environment using Docker and this aviods making any addational network setup other than Docker's one

For it, Please check this

https://www.erlang-solutions.com/blog/erlang-and-elixir-distribution-without-epmd.html


问:
JavaScript map object not saving object keys?
So I'm trying to add an entry to a map object with the key being an object but it doesn't seem to work.

```<code>let myMap = new Map();
myMap.set({type : 'sum', val : 10},1);
console.log(myMap.get({type:'sum',val:10})); <---- this returns undefined
</code>```

why is it returning undefined instead of 1?

答: javascriot uses SameValueZero  algorithm to campare key when you set and get from this structure. SameValueZero is similar to strict equality (===). since in get method you are creating new object and pass it to this method as key this key is not strictly equal to the object you use when you set so you get null. </p>

Body:
So I'm trying to add an entry to a map object with the key being an object but it doesn't seem to work.

let myMap = new Map();
myMap.set({type : 'sum', val : 10},1);
console.log(myMap.get({type:'sum',val:10})); <---- this returns undefined

why is it returning undefined instead of 1?


答:
Map is a key value pair where you store a value with it's key.
Like:

```<code>let map = new Map();
         // key     // value
map.set('myKey','just a text');
</code>```

then to access that value, you need the key in this case which is 'myKey'

```<code>map.get('myKey'); // will return just a text
</code>```

if you wish to convert your object to a map, follow this article :

```<code>let obj = {
  name: "John",
  age: 30
};

let map = new Map(Object.entries(obj));

alert( map.get('name') ); // John
</code>```

Title: JavaScript map object not saving object keys?

Body:
Map is a key value pair where you store a value with it's key.
Like:

let map = new Map();
         // key     // value
map.set('myKey','just a text');

then to access that value, you need the key in this case which is 'myKey'

map.get('myKey'); // will return just a text

if you wish to convert your object to a map, follow this article :

let obj = {
  name: "John",
  age: 30
};

let map = new Map(Object.entries(obj));

alert( map.get('name') ); // John


问:
Javascript to remove an object from an array if one element in the object contains a string
I have an array of objects such as:

```<code>{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}
</code>```

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)

答:
Use

```<code>value.filter(x=>x.attachment_text.indexOf('Contact request') > -1);
</code>```

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

and works fine perfectly with every browser.

Body:
I have an array of objects such as:

{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)

Body:
Use

value.filter(x=>x.attachment_text.indexOf('Contact request') > -1);

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

and works fine perfectly with every browser.


问:
Remote workers on multiple servers with python-rq (redis)
I am using redis and python-rq to manage a data processing task. I wish to distribute the data processing across multiple servers (each server would manage several rq workers) but I would like to keep a unique queue on a master server.

Is there a way to achieve this using python-rq ?

Thank you.

答:
It turned out to be easy enough. There are two steps:

1) Configure Redis on the master machine so that it is open to external communications by the remote "agent" server. This is done by editing the bind information as explained in this post. Make sure to set a password if setting the bind value to 0.0.0.0 as this will open the Redis connection to anyone.

2) Start the worker on the remote "agent" server using the url parameter:

```<code>rq worker --url redis://:[your_master_redis_password]@[your_master_server_IP_address]
</code>```

On the master server, you can check that the connection was properly made by typing:

```<code>rq info --url redis://:[your_master_redis_password]@localhost
</code>```

If you enabled the localhost binding, this should display all the workers available to Redis from your "master" including the new worker you created on your remote server.

Body:
It turned out to be easy enough. There are two steps:

1) Configure Redis on the master machine so that it is open to external communications by the remote "agent" server. This is done by editing the bind information as explained in this post. Make sure to set a password if setting the bind value to 0.0.0.0 as this will open the Redis connection to anyone.

2) Start the worker on the remote "agent" server using the url parameter:

rq worker --url redis://:[your_master_redis_password]@[your_master_server_IP_address]

On the master server, you can check that the connection was properly made by typing:

rq info --url redis://:[your_master_redis_password]@localhost

If you enabled the localhost binding, this should display all the workers available to Redis from your "master" including the new worker you created on your remote server.


问:
How do I use the inet type with Python and postgresql?
I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver.
One table stores IP addresses using the inet type.

I have created the following prepared statement:

```<code>aID = db.prepare('SELECT id FROM a_records WHERE ip = $1 LIMIT 1')
</code>```

When calling aID(ip) I get the following error:

(ip is a python string)

```<code> File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
1517, in __call__
    c = SingleXactFetch(self, parameters)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
837, in __init__
    Output.__init__(self, '')
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
622, in __init__
    self._init()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
854, in _init
    STEP()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
2612, in _pq_step
    self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', Non
e))
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
507, in raise_error
    self.raise_server_error(error_message, **kw)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
498, in raise_server_error
    raise server_error
postgresql.exceptions.BinaryRepresentationError: invalid address family in exte
rnal "inet" value
  CODE: 22P03
  LOCATION: File 'network.c', line 218, in network_recv from SERVER
RESULT:
  type: SingleXactFetch
  parameters: ('139.78.113.1',)
STATEMENT: [prepared]
  sql_parameter_types: ['pg_catalog.inet']
  results: (id INTEGER)
  statement_id: py:0x2ff9a50
  string: SELECT id FROM a_records WHERE ip = $1 LIMIT 1
CONNECTION: [idle]
  client_address: 127.0.0.1/32
  client_port: 51563
  version:
    PostgreSQL 8.4.7 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debi
an 4.4.5-8) 4.4.5, 64-bit
CONNECTOR: [IP4] pq://python:***@127.0.0.1:5432/vdz
  category: None
DRIVER: postgresql.driver.pq3.Driver
</code>```

Can anyone help me debug this and figure out why postgresql is not liking the inet data?

Thanks!

答:
I've been having this problem all day, and I could not find any solution, so obviously I found the solution on my own a few minutes after posting here.

I need to replace $1 with inet($1::varchar), it seems that postgresql does not like it being a string when converting to an inet value, and you must typecast it as a varchar, and then turn the value into an inet variable.

So, the working line is:

```<code>aID = db.prepare('SELECT id FROM a_records WHERE ip = inet($1::varchar) LIMIT 1')
</code>```

Can anyone explain why this is, and why it wont work the way I tried to at first?

Thanks!

ContentLicense: CC BY-SA 3.0

Body:
I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver.
One table stores IP addresses using the inet type.

I have created the following prepared statement:

aID = db.prepare('SELECT id FROM a_records WHERE ip = $1 LIMIT 1')

When calling aID(ip) I get the following error:

(ip is a python string)

 File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
1517, in __call__
    c = SingleXactFetch(self, parameters)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
837, in __init__
    Output.__init__(self, '')
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
622, in __init__
    self._init()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
854, in _init
    STEP()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
2612, in _pq_step
    self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', Non
e))
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
507, in raise_error
    self.raise_server_error(error_message, **kw)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
498, in raise_server_error
    raise server_error
postgresql.exceptions.BinaryRepresentationError: invalid address family in exte
rnal "inet" value
  CODE: 22P03
  LOCATION: File 'network.c', line 218, in network_recv from SERVER
RESULT:
  type: SingleXactFetch
  parameters: ('139.78.113.1',)
STATEMENT: [prepared]
  sql_parameter_types: ['pg_catalog.inet']
  results: (id INTEGER)
  statement_id: py:0x2ff9a50
  string: SELECT id FROM a_records WHERE ip = $1 LIMIT 1
CONNECTION: [idle]
  client_address: 127.0.0.1/32
  client_port: 51563
  version:
    PostgreSQL 8.4.7 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debi
an 4.4.5-8) 4.4.5, 64-bit
CONNECTOR: [IP4] pq://python:***@127.0.0.1:5432/vdz
  category: None
DRIVER: postgresql.driver.pq3.Driver

Can anyone help me debug this and figure out why postgresql is not liking the inet data?

Thanks!

Body:
I've been having this problem all day, and I could not find any solution, so obviously I found the solution on my own a few minutes after posting here.

I need to replace $1 with inet($1::varchar), it seems that postgresql does not like it being a string when converting to an inet value, and you must typecast it as a varchar, and then turn the value into an inet variable.

So, the working line is:

aID = db.prepare('SELECT id FROM a_records WHERE ip = inet($1::varchar) LIMIT 1')

Can anyone explain why this is, and why it wont work the way I tried to at first?

Thanks!


答:
You use 2 different objects that just happen to have the same properties. They are not equal, though. To make it work, you would have to use the exact same object, like this:</p>

```<code>let myMap = new Map();
var obj = {type : 'sum', val : 10};
myMap.set(obj,1);
console.log(myMap.get(obj));
</code>```

Body:
You use 2 different objects that just happen to have the same properties. They are not equal, though. To make it work, you would have to use the exact same object, like this:

let myMap = new Map();
var obj = {type : 'sum', val : 10};
myMap.set(obj,1);
console.log(myMap.get(obj));


问:
Mongoimport of JSON file
I have a JSON file consisting of about 2000 records.  Each record which will correspond to a document in the mongo database is formatted as follows:

```<code>{jobID:"2597401",
account:"XXXXX",
user:"YYYYY",
pkgT:{"pgi/7.2-5":{libA:["libpgc.so"],flavor:["default"]}},
startEpoch:"1338497979",
runTime:"1022",
execType:"user:binary",
exec:"/share/home/01482/XXXXX/appker/ranger/NPB3.3.1/NPB3.3-MPI/bin/ft.D.64",
numNodes:"4",
sha1:"5a79879235aa31b6a46e73b43879428e2a175db5",
execEpoch:1336766742,
execModify: new Date("Fri May 11 15:05:42 2012"),
startTime: new Date("Thu May 31 15:59:39 2012"),
numCores:"64",
sizeT:{bss:"1881400168",text:"239574",data:"22504"}},
</code>```

Each record is on a single line in the JSON file, and the only line breaks are at the end of every record.  Therefore, each line in the document starts with "{jobID:"...  I am trying to import these into a mongo database using the following command:

```<code>mongoimport --db dbName --collection collectionName --file fileName.json
</code>```

However, I get the following error:

```<code>Sat Mar  2 01:26:12 Assertion: 10340:Failure parsing JSON string near: ,execModif
0x10059f12b 0x100562d5c 0x100562e9c 0x10025eb98 0x10000e643 0x100010b60 0x10055c4cc 0x1000014b7
0x100001454
 0   mongoimport                         0x000000010059f12b _ZN5mongo15printStackTraceERSo + 43
 1   mongoimport                         0x0000000100562d5c _ZN5mongo11msgassertedEiPKc + 204
 2   mongoimport                         0x0000000100562e9c _ZN5mongo11msgassertedEiRKSs + 12
 3   mongoimport                         0x000000010025eb98 _ZN5mongo8fromjsonEPKcPi + 1576
 4   mongoimport                         0x000000010000e643
                                         _ZN6Import8parseRowEPSiRN5mongo7BSONObjERi + 2739
 5   mongoimport                         0x0000000100010b60 _ZN6Import3runEv + 7376
 6   mongoimport                         0x000000010055c4cc _ZN5mongo4Tool4mainEiPPc + 5436
 7   mongoimport                         0x00000001000014b7 main + 55
 8   mongoimport                         0x0000000100001454 start + 52
Sat Mar  2 01:26:12 exception:BSON representation of supplied JSON is too large: Failure parsing
    JSON string near: ,execModif
Sat Mar  2 01:26:12
Sat Mar  2 01:26:12 imported 0 objects
Sat Mar  2 01:26:12 ERROR: encountered 1941 errors
</code>```

I do not know what the problem is. Can someone recommend a solution?

答:
Just copy path of json file like example "C:\persons.json"

go to C:\Program Files\MongoDB\Server\4.2\bin

open cmd on that mongodb bin folder and run this command

mongoimport --jsonArray --db dbname--collection collectionName--file FilePath

example mongoimport --jsonArray --db learnmongo --collection persons --file C:\persons.json

Title: Mongoimport of JSON file

Body:
I have a JSON file consisting of about 2000 records.  Each record which will correspond to a document in the mongo database is formatted as follows:

{jobID:"2597401",
account:"XXXXX",
user:"YYYYY",
pkgT:{"pgi/7.2-5":{libA:["libpgc.so"],flavor:["default"]}},
startEpoch:"1338497979",
runTime:"1022",
execType:"user:binary",
exec:"/share/home/01482/XXXXX/appker/ranger/NPB3.3.1/NPB3.3-MPI/bin/ft.D.64",
numNodes:"4",
sha1:"5a79879235aa31b6a46e73b43879428e2a175db5",
execEpoch:1336766742,
execModify: new Date("Fri May 11 15:05:42 2012"),
startTime: new Date("Thu May 31 15:59:39 2012"),
numCores:"64",
sizeT:{bss:"1881400168",text:"239574",data:"22504"}},

Each record is on a single line in the JSON file, and the only line breaks are at the end of every record.  Therefore, each line in the document starts with "{jobID:"...  I am trying to import these into a mongo database using the following command:

mongoimport --db dbName --collection collectionName --file fileName.json

However, I get the following error:

Sat Mar  2 01:26:12 Assertion: 10340:Failure parsing JSON string near: ,execModif
0x10059f12b 0x100562d5c 0x100562e9c 0x10025eb98 0x10000e643 0x100010b60 0x10055c4cc 0x1000014b7
0x100001454
 0   mongoimport                         0x000000010059f12b _ZN5mongo15printStackTraceERSo + 43
 1   mongoimport                         0x0000000100562d5c _ZN5mongo11msgassertedEiPKc + 204
 2   mongoimport                         0x0000000100562e9c _ZN5mongo11msgassertedEiRKSs + 12
 3   mongoimport                         0x000000010025eb98 _ZN5mongo8fromjsonEPKcPi + 1576
 4   mongoimport                         0x000000010000e643
                                         _ZN6Import8parseRowEPSiRN5mongo7BSONObjERi + 2739
 5   mongoimport                         0x0000000100010b60 _ZN6Import3runEv + 7376
 6   mongoimport                         0x000000010055c4cc _ZN5mongo4Tool4mainEiPPc + 5436
 7   mongoimport                         0x00000001000014b7 main + 55
 8   mongoimport                         0x0000000100001454 start + 52
Sat Mar  2 01:26:12 exception:BSON representation of supplied JSON is too large: Failure parsing
    JSON string near: ,execModif
Sat Mar  2 01:26:12
Sat Mar  2 01:26:12 imported 0 objects
Sat Mar  2 01:26:12 ERROR: encountered 1941 errors

I do not know what the problem is. Can someone recommend a solution?


问:
How do I make pratilk pages with ngTemplate and ngContainer
for example:

├── modal
│   ├── layer
│   └──── layer.component.html
│   └──── layer.component.ts
│   │
│   ├── warningModal
│   └──── warningModal.component.html
│   └──── warningModal.component.ts
└
```

<p>My goal is to create a modal structure with layer. And using this modal is to create only the inside of the warning modal.</p>

<p>layel.component.html</p>

```<ng-container *ngTemplateOutlet="control"></ng-container>
```

<p>warningModal.component.ts</p>

```<ng-template #control>

hello guys

</ng-template>
```

why not work? If I wrote it in a single file, it would work. But it doesn't work when you write to different components. How can I do this?

答:
1) When you write both in single line at that time template needed for ngTemplateOutlet is present at same place so it works

2) When these are in two different component there is no relation between each other So when passing ngTemplateOutlet="options" it just assumes it as string not a template reference variable so nothing display

Use this method

warningModal.component.html
│

```<code><app-layer [temp]="control"></app-layer>
<ng-template #control>
  <p>hello guys</p>
</ng-template>
</code>```

layer.component.ts

```<code>import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-layer',
  templateUrl: './layer.component.html',
  styleUrls: ['./layer.component.css']
})
export class LayerComponent{
  @Input() temp
}
</code>```

layer.component.html

```<code><ng-container *ngTemplateOutlet="temp"></ng-container>
</code>```

Working link

https://stackblitz.com/edit/angular-xzlyhq?embed=1&file=src/app/layer/layer.component.html

Body:
for example:

├── modal
│   ├── layer
│   └──── layer.component.html
│   └──── layer.component.ts
│   │
│   ├── warningModal
│   └──── warningModal.component.html
│   └──── warningModal.component.ts
└

My goal is to create a modal structure with layer. And using this modal is to create only the inside of the warning modal.

layel.component.html

<ng-container *ngTemplateOutlet="control"></ng-container>

warningModal.component.ts

<ng-template #control>

hello guys

</ng-template>

why not work? If I wrote it in a single file, it would work. But it doesn't work when you write to different components. How can I do this?

Body:
1) When you write both in single line at that time template needed for ngTemplateOutlet is present at same place so it works

2) When these are in two different component there is no relation between each other So when passing ngTemplateOutlet="options" it just assumes it as string not a template reference variable so nothing display

Use this method

warningModal.component.html
│

<app-layer [temp]="control"></app-layer>
<ng-template #control>
  <p>hello guys</p>
</ng-template>

layer.component.ts

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-layer',
  templateUrl: './layer.component.html',
  styleUrls: ['./layer.component.css']
})
export class LayerComponent{
  @Input() temp
}

layer.component.html

<ng-container *ngTemplateOutlet="temp"></ng-container>

Working link

https://stackblitz.com/edit/angular-xzlyhq?embed=1&file=src/app/layer/layer.component.html


问:
How do I write a Logary target for my .NET application?
I am trying to get started with Logary. I need to write a new target and I have tried following the following tutorial https://logary.tech/tutorials. I have downloaded Logary.sln from https://github.com/logary/logary, but I am not able to build Logary.sln. When I build it I get 40 errors and all of them say: The command ""paket.exe" restore" exited with code 9009.

When I try to add the nuget Logary (latest 5.0) with NuGet manager I get NU1108: Cycle detected. Logary -> Logary (>= 5.0.0).

When I try following this https://logary.tech/logary-dotnet-quickstart I get 2 errors as well.

So, I am totally lost. What am I missing out? I will provide more information if necessary. I want to write a target in F# for my .NET application that would be sent as an event to Logary's centralised event storage.

答: I seems that the problem is with the project name. Its name is the same as the referenced NuGet package. So to resolve this problem you should changed the project name and the build will succeeded.</p>


问:
Is there a way to explicitly say to android system resolve my intent to default app/activity for current intent action?
I need to open web link from my android application, but without prompt to user chooser dialog also known as "disambiguation dialog", just use default browser to handle this intent.

When I use this code:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
</code>```

there is no guarantee that resolving intent will be result in only one activity, according to description of Intent.resolveActivity method in official documentation:

...If multiple activities are found to satisfy the intent, the one with the highest priority will be used. If there are multiple activities with the same priority, the system will either pick the best activity based on user preference, or resolve to a system class that will allow the user to pick an activity and forward from there.

How to avoid chooser dialog and just pass to "best" activity or maybe default activity for this action type?

答:
You can resolve the Intent yourself by calling PackageManager.queryIntentActivities().

If this returns only 1 result, then you can just call startActivity() and you can be sure that Android won't show the chooser dialog.

If it returns more than 1 result, you can do something else. For example, since the results are returned from "best" to "worst" (whatever that means), you could just launch the first result explicitly. Or you could scan the results list looking for something that your code deems is appropriate (ie: matches a list of browser names).

Body:
I need to open web link from my android application, but without prompt to user chooser dialog also known as "disambiguation dialog", just use default browser to handle this intent.

When I use this code:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);

there is no guarantee that resolving intent will be result in only one activity, according to description of Intent.resolveActivity method in official documentation:

...If multiple activities are found to satisfy the intent, the one with the highest priority will be used. If there are multiple activities with the same priority, the system will either pick the best activity based on user preference, or resolve to a system class that will allow the user to pick an activity and forward from there.

How to avoid chooser dialog and just pass to "best" activity or maybe default activity for this action type?


问:
Not able to connect Steam and Discord
I have difficulty on connecting Steam and Discord using my Mobile tethering. While using WiFI i able to connect to Steam and Discord but maybe it gonna be bit lagging that's why I am using mobile tethering. But when i connect it, my Steam and Discord disconnected but I able to browse any website. My mobile tethering gives me "2404:6800:4001:801::200e" while my WiFi gives me normal ip address "172.xxx.xxx.xxx" in cmd.

Any suggestions?

答:
Try to disable your IPv6 in your the adapter settings of your WiFi controller.

Controlpanel

Network and sharing

Network connections

Properties of your wifi adapter

Disable the IPv6 setting: image

If it still doesn't work, first try to renew your IP adres.

CMD

ipconfig /release

ipconfig /renew

Hope this helps.

Title: Not able to connect Steam and Discord


问:
Email notification when disk drive reaches a certain percentage? (Laravel)
I'd love to be able to monitor my disk drives automatically with email notifications. I'm using Laravel (and therefore it should be possible to schedule a task to check) this but I'm unsure how to go about checking the available disk size through Laravel/PHP code. Any ideas?

I did find this article (but it's not strictly what I want as it uses shell directly to send emails and I want a laravel scheduled task to send the emails whenever it finds the disk drive at a specified percentage): https://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

答:
You can use disk_free_space() it Returns available space on filesystem or disk partition :

```<code><?php
  // $df contains the number of bytes available on "/"
  $df = disk_free_space("/");

  // On Windows:
  $df_c = disk_free_space("C:");
  $df_d = disk_free_space("D:");
?>
</code>```

If you want to check total space of your disk, then use disk_total_space()

```<code><?php
  // $ds contains the total number of bytes available on "/"
  $ds = disk_total_space("/");

  // On Windows:
  $ds = disk_total_space("C:");
  $ds = disk_total_space("D:");
?>
</code>```

Body:
You can use disk_free_space() it Returns available space on filesystem or disk partition :

<?php
  // $df contains the number of bytes available on "/"
  $df = disk_free_space("/");

  // On Windows:
  $df_c = disk_free_space("C:");
  $df_d = disk_free_space("D:");
?>

If you want to check total space of your disk, then use disk_total_space()

<?php
  // $ds contains the total number of bytes available on "/"
  $ds = disk_total_space("/");

  // On Windows:
  $ds = disk_total_space("C:");
  $ds = disk_total_space("D:");
?>


问:
Set the default directory in mac terminal
I only use terminal (mac) for git, and I only use git for one directory. Is it possible to set the default directory (the directory when terminal is opened) to the directory where I use git, and if so how?</p>

答: Use a Window Group. Arrange your shell window(s) as you'd want them to be on startup - cd to the directory you want in each, set colors, Shell--Edit Title, etc. Then go to Window--"Save Windows as Group...". Give it a name, check "Use window group when Terminal starts". Next time you start, this arrangement will be your starting point.</p>


问:
SQLAlchemy polymorphic on multiple identities for a class
I'm trying to implement Single Table Inheritance using SQLAlchemy.
According to the official SQLAlchemy's documentation (here: official docs), the way to assign a single polymorphic identity, is as follows:

```<code>class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }
</code>```

I want to assign multiple identities, for a single class. For example:

```<code> class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Manager(Employee):
    manager_name = Column(String(30))

    company_id = Column(ForeignKey('company.id'))
    company = relationship("Company", back_populates="managers")

    __mapper_args__ = {
        'polymorphic_identity': ['manager', 'ceo'],
    }
</code>```

Notice the following line:

```<code>'polymorphic_identity': ['manager', 'ceo']
</code>```

This line isn't possible (unfortunately).

I would like to know if there's any way of assigning multiple polymorphic identities to a single class.
Unfortunately I couldn't find any example like that in the docs.

答:
I know this has long been answered, but this is another option.

The polymorphic_on can also take a case according to the docs

https://docs.sqlalchemy.org/en/13/orm/mapping_api.html#sqlalchemy.orm.mapper.params.polymorphic_on

So each class still only has 1 polymorphic_identity but in the polymorphic_on you can map multiple values to the same identity.

In your case it could look like:

 class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        "polymorphic_on":case(
            [
                (type == "manager", "manager"),
                (type == "ceo", "manager"),
            ],
            else_="employee"
         )
    }

class Manager(Employee):
    manager_name = Column(String(30))

    company_id = Column(ForeignKey('company.id'))
    company = relationship("Company", back_populates="managers")

    __mapper_args__ = {
        'polymorphic_identity': 'manager',
    }
```

I have not tried with in or SQLAlchemy's .in_

Body:
I'm trying to implement Single Table Inheritance using SQLAlchemy.
According to the official SQLAlchemy's documentation (here: official docs), the way to assign a single polymorphic identity, is as follows:

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

I want to assign multiple identities, for a single class. For example:

 class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Manager(Employee):
    manager_name = Column(String(30))

    company_id = Column(ForeignKey('company.id'))
    company = relationship("Company", back_populates="managers")

    __mapper_args__ = {
        'polymorphic_identity': ['manager', 'ceo'],
    }

Notice the following line:

'polymorphic_identity': ['manager', 'ceo']

This line isn't possible (unfortunately).

I would like to know if there's any way of assigning multiple polymorphic identities to a single class.
Unfortunately I couldn't find any example like that in the docs.

Body:
I know this has long been answered, but this is another option.

The polymorphic_on can also take a case according to the docs

https://docs.sqlalchemy.org/en/13/orm/mapping_api.html#sqlalchemy.orm.mapper.params.polymorphic_on

So each class still only has 1 polymorphic_identity but in the polymorphic_on you can map multiple values to the same identity.

In your case it could look like:

 class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        "polymorphic_on":case(
            [
                (type == "manager", "manager"),
                (type == "ceo", "manager"),
            ],
            else_="employee"
         )
    }

class Manager(Employee):
    manager_name = Column(String(30))

    company_id = Column(ForeignKey('company.id'))
    company = relationship("Company", back_populates="managers")

    __mapper_args__ = {
        'polymorphic_identity': 'manager',
    }

I have not tried with in or SQLAlchemy's .in_


问:
Progress bar in uploading Xml file
i want to use a background thread for the process of loading the XML data, possibly with a progress bar to let the user know that the application is actively doing something.
i have written this code through searching the net.

i want to load a XML tree in treeview on winform when a user cliks a Browse button.
In case of a large XML file the winform freezes.So to let the user know that in background the work is going on i want to add a progress bar.i have used a background worker here.

But it is raising an exception of  System.ArgumentException showing this message "The URL cannot be empty.\r\nParameter name: url" on     xmlDocument.Load(txtFileName.Text);  this line.

My xml file is in correct format and is at the proper location where i selected.
But i am unable to find the cause of this exception.
Can you please help out or tell me the correction in my code?

Thanks....

```<code>       private void btnBrowse_Click(object sender,EventArgs e)
        {
            bgWorker1.RunWorkerAsync();
            StripProgressBar.Value = 0;
            toolStripStatusLabel1.Text = "Browsing for a  Xml file";

            if (open.ShowDialog(this) == DialogResult.OK)
            {
                txtFileName.Text = open.FileName;
                initiatingTree(open.FileName); //this variable gives the name of selected file
            }
            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }//Browse button
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            xmlDocument = new XmlDocument();
            Thread.Sleep(5000);
            xmlDocument.Load(txtFileName.Text);
            btnBrowse.Enabled = false;
        }
        private void bgworker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {
             // Set progress bar to 100% in case it's not already there.
             StripProgressBar.Value = 100;
             if (e.Error == null)
             {
                 MessageBox.Show(xmlDocument.InnerXml, "Download Complete");
             }
             else
             {
                 MessageBox.Show("Failed to download file");
             }
             // Enable the Browse button and reset the progress bar.
             this.btnBrowse.Enabled = true;
             StripProgressBar.Value = 0;
             toolStripStatusLabel1.Text = "work finished processing request.";
         }//workerCompleted
</code>```

答:
When the method bgWorker1.RunWorkerAsync(); is called the event DoWork is fired.

Because the method is called in the beginning of the application, the file name text box is empty.

I hope you've understood.

ContentLicense: CC BY-SA 2.5

Title: Progress bar in uploading Xml file

Body:
i want to use a background thread for the process of loading the XML data, possibly with a progress bar to let the user know that the application is actively doing something.
i have written this code through searching the net.

i want to load a XML tree in treeview on winform when a user cliks a Browse button.
In case of a large XML file the winform freezes.So to let the user know that in background the work is going on i want to add a progress bar.i have used a background worker here.

But it is raising an exception of  System.ArgumentException showing this message "The URL cannot be empty.\r\nParameter name: url" on     xmlDocument.Load(txtFileName.Text);  this line.

My xml file is in correct format and is at the proper location where i selected.
But i am unable to find the cause of this exception.
Can you please help out or tell me the correction in my code?

Thanks....

       private void btnBrowse_Click(object sender,EventArgs e)
        {
            bgWorker1.RunWorkerAsync();
            StripProgressBar.Value = 0;
            toolStripStatusLabel1.Text = "Browsing for a  Xml file";

            if (open.ShowDialog(this) == DialogResult.OK)
            {
                txtFileName.Text = open.FileName;
                initiatingTree(open.FileName); //this variable gives the name of selected file
            }
            while (this.bgWorker1.IsBusy)
            {
                StripProgressBar.Increment(1);
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.
                Application.DoEvents();
            }
        }//Browse button
        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            xmlDocument = new XmlDocument();
            Thread.Sleep(5000);
            xmlDocument.Load(txtFileName.Text);
            btnBrowse.Enabled = false;
        }
        private void bgworker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
         {
             // Set progress bar to 100% in case it's not already there.
             StripProgressBar.Value = 100;
             if (e.Error == null)
             {
                 MessageBox.Show(xmlDocument.InnerXml, "Download Complete");
             }
             else
             {
                 MessageBox.Show("Failed to download file");
             }
             // Enable the Browse button and reset the progress bar.
             this.btnBrowse.Enabled = true;
             StripProgressBar.Value = 0;
             toolStripStatusLabel1.Text = "work finished processing request.";
         }//workerCompleted

LastEditorDisplayName: Daniel L

OwnerDisplayName: arpf


问:
How do we give constraint on foreign key column based on ERD cardinality?
Let's say I have a 2 tables like below :

Department:

```<code>DeptId   Name
</code>```

Employee:

```<code>EmpId  Name    DeptId
</code>```

Here I have a 0-to-many relationship between Department and Employee table.

Now when I read the relationship from Department to Employee, it says 1 department can have 0 or more employees.

Does this mean while creating Employee table, I will set DepartmentId (foreign key) as null due to zero or many relationship?

And how do we represent 1 or many relationship like for eg If relationship in ERD says 1 department can have 0 or more employees then DepartmentId (foreign key) will be non nullable in Employee table?

Basically I am just trying to understand how do we give constraint on foreign key based on ERD cardinality (1 to many relation,1 to zero or more relationship).

Can anyone please help me clear this confusion? I will really really appreciate that :)

答:
ERD tools are great, but the most powerful design tool is still natural language, predicates, and constraints. So, when in doubt, use a plain text editor instead of an ERD tool. Also do not allow NULLs in the design phase.

All attributes (columns) NOT NULL

[p x]   = predicate  x
(c x.y) = constraint x.y

PK = Primary Key
AK = Alternate Key (Unique)
FK = Foreign Key
```

<hr>

<p>Starting with the department, this part does not change.</p>

<p><strong>[p 1]</strong> Department identified by number <code>DEPT_ID</code>, named <code>DEPT_NAME</code> exists.</p>

<p><em>(c 1.1)</em> Department is identified by department number.</p>

<p><em>(c 1.2)</em> For each department name, exactly one department has that name; for each department, that department has exactly one name.</p>

<pre class="lang-none prettyprint-override"><code>department {DEPT_ID, DEPT_NAME} -- p 1
        PK {DEPT_ID}            -- c 1.1
        AK {DEPT_NAME}          -- c 1.2
</code>```

Case 1:  Emp * ---- 1 Dept

[p 2] Employee identified by number EMP_ID, named EMP_NAME, works for department DEPT_ID.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

(c 2.3) Each employee works for exactly one department; for each department more than one employee may work for that department.

(c 2.4) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME, DEPT_ID}  -- p 2
      PK {EMP_ID}                     -- c 2.1, c 2.2, c 2.3

      FK {DEPT_ID} REFERENCES department {DEPT_ID} -- c 2.4
```

<hr>

<h2>Case 2:  Emp <code>* ---- 0..1</code> Dept</h2>

<p><strong>[p 2]</strong> Employee identified by number <code>EMP_ID</code>, named <code>EMP_NAME</code>, exists.</p>

<p><em>(c 2.1)</em> Employee is identified by employee number.</p>

<p><em>(c 2.2)</em>  Each employee has exactly one name; for each employee name, more than one employee can have that name.</p>

<p><strong>[p 3]</strong> Employee identified by number <code>EMP_ID</code> works for department identified by number <code>DEPT_ID</code>.</p>

<p><em>(c 3.1)</em> Each employee works for <em>at most one</em> department; for each department <em>more than one</em> employee <em>may work</em> in that department.</p>

<p><em>(c 3.2)</em> If an employee works for a department, then that employee must exist.</p>

<p><em>(c 3.3)</em> If an employee works for a department, then that department must exist.</p>

<pre class="lang-none prettyprint-override"><code>employee {EMP_ID, EMP_NAME}  -- p 2
      PK {EMP_ID}            -- c 2.1, c 2.2

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID}           -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3
</code>```

Case 3:  Emp * ---- * Dept

[p 2] Employee identified by number EMP_ID, named EMP_NAME, exists.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

[p 3] Employee identified by number EMP_ID works for department identified by number DEPT_ID.

(c 3.1) Each employee may work for more than one department; for each department more than one employee may work in that department.

(c 3.2) If an employee works for a department, then that employee must exist.

(c 3.3) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME}  -- p 2
      PK {EMP_ID}            -- c 2.1, c 2.2

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID, DEPT_ID}  -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3
```

<hr>

<h2>Case 4:  Emp <code>* ---- 1..*</code> Dept</h2>

<p>This one is tricky, combine cases 1 and 3 by introducing the concept of a home (primary, default) department.</p>

<p><strong>[p 2]</strong> Employee identified by number <code>EMP_ID</code>, named <code>EMP_NAME</code>, works for home department <code>HOME_DEPT_ID</code>.</p>

<p><em>(c 2.1)</em> Employee is identified by employee number.</p>

<p><em>(c 2.2)</em>  Each employee has exactly one name; for each employee name, more than one employee can have that name.</p>

<p><em>(c 2.3)</em> Each employee works <em>for exactly one</em> home department; for each home department more than one employee may work for that home department.</p>

<p><em>(c 2.4)</em> If an employee works for a home department, then that department must exist.</p>

<p><strong>[p 3]</strong> In addition to the home department, employee identified by number <code>EMP_ID</code> also works for another department identified by number <code>DEPT_ID</code>.</p>

<p><em>(c 3.1)</em> In addition to the home department, each employee <em>may work</em> for <em>more than one</em> other department; for each department <em>more than one</em> employee <em>may work</em> for that department.</p>

<p><em>(c 3.2)</em> If an employee works for a department, then that employee must exist.</p>

<p><em>(c 3.3)</em> If an employee works for a department, then that department must exist.</p>

<pre class="lang-none prettyprint-override"><code>employee {EMP_ID, EMP_NAME, HOME_DEPT_ID}  -- p 2
      PK {EMP_ID}                          -- c 2.1, c 2.2, c 2.3

      FK {HOME_DEPT_ID} REFERENCES department {DEPT_ID} -- c 2.4

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID, DEPT_ID}  -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3
</code>```

On the application level check that, for a given employee, HOME_DEPT_ID is not repeated as EMP_ID in the emp_dept.

Body:
Let's say I have a 2 tables like below :

Department:

DeptId   Name

Employee:

EmpId  Name    DeptId

Here I have a 0-to-many relationship between Department and Employee table.

Now when I read the relationship from Department to Employee, it says 1 department can have 0 or more employees.

Does this mean while creating Employee table, I will set DepartmentId (foreign key) as null due to zero or many relationship?

And how do we represent 1 or many relationship like for eg If relationship in ERD says 1 department can have 0 or more employees then DepartmentId (foreign key) will be non nullable in Employee table?

Basically I am just trying to understand how do we give constraint on foreign key based on ERD cardinality (1 to many relation,1 to zero or more relationship).

Can anyone please help me clear this confusion? I will really really appreciate that :)

Body:
ERD tools are great, but the most powerful design tool is still natural language, predicates, and constraints. So, when in doubt, use a plain text editor instead of an ERD tool. Also do not allow NULLs in the design phase.

All attributes (columns) NOT NULL

[p x]   = predicate  x
(c x.y) = constraint x.y

PK = Primary Key
AK = Alternate Key (Unique)
FK = Foreign Key

Starting with the department, this part does not change.

[p 1] Department identified by number DEPT_ID, named DEPT_NAME exists.

(c 1.1) Department is identified by department number.

(c 1.2) For each department name, exactly one department has that name; for each department, that department has exactly one name.

department {DEPT_ID, DEPT_NAME} -- p 1
        PK {DEPT_ID}            -- c 1.1
        AK {DEPT_NAME}          -- c 1.2

Case 1:  Emp * ---- 1 Dept

[p 2] Employee identified by number EMP_ID, named EMP_NAME, works for department DEPT_ID.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

(c 2.3) Each employee works for exactly one department; for each department more than one employee may work for that department.

(c 2.4) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME, DEPT_ID}  -- p 2
      PK {EMP_ID}                     -- c 2.1, c 2.2, c 2.3

      FK {DEPT_ID} REFERENCES department {DEPT_ID} -- c 2.4

Case 2:  Emp * ---- 0..1 Dept

[p 2] Employee identified by number EMP_ID, named EMP_NAME, exists.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

[p 3] Employee identified by number EMP_ID works for department identified by number DEPT_ID.

(c 3.1) Each employee works for at most one department; for each department more than one employee may work in that department.

(c 3.2) If an employee works for a department, then that employee must exist.

(c 3.3) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME}  -- p 2
      PK {EMP_ID}            -- c 2.1, c 2.2

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID}           -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3

Case 3:  Emp * ---- * Dept

[p 2] Employee identified by number EMP_ID, named EMP_NAME, exists.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

[p 3] Employee identified by number EMP_ID works for department identified by number DEPT_ID.

(c 3.1) Each employee may work for more than one department; for each department more than one employee may work in that department.

(c 3.2) If an employee works for a department, then that employee must exist.

(c 3.3) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME}  -- p 2
      PK {EMP_ID}            -- c 2.1, c 2.2

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID, DEPT_ID}  -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3

Case 4:  Emp * ---- 1..* Dept

This one is tricky, combine cases 1 and 3 by introducing the concept of a home (primary, default) department.

[p 2] Employee identified by number EMP_ID, named EMP_NAME, works for home department HOME_DEPT_ID.

(c 2.1) Employee is identified by employee number.

(c 2.2)  Each employee has exactly one name; for each employee name, more than one employee can have that name.

(c 2.3) Each employee works for exactly one home department; for each home department more than one employee may work for that home department.

(c 2.4) If an employee works for a home department, then that department must exist.

[p 3] In addition to the home department, employee identified by number EMP_ID also works for another department identified by number DEPT_ID.

(c 3.1) In addition to the home department, each employee may work for more than one other department; for each department more than one employee may work for that department.

(c 3.2) If an employee works for a department, then that employee must exist.

(c 3.3) If an employee works for a department, then that department must exist.

employee {EMP_ID, EMP_NAME, HOME_DEPT_ID}  -- p 2
      PK {EMP_ID}                          -- c 2.1, c 2.2, c 2.3

      FK {HOME_DEPT_ID} REFERENCES department {DEPT_ID} -- c 2.4

emp_dept {EMP_ID, DEPT_ID}  -- p 3
      PK {EMP_ID, DEPT_ID}  -- c 3.1

      FK1 {EMP_ID}  REFERENCES employee   {EMP_ID}  -- c 3.2
      FK2 {DEPT_ID} REFERENCES department {DEPT_ID} -- c 3.3

On the application level check that, for a given employee, HOME_DEPT_ID is not repeated as EMP_ID in the emp_dept.


问:
Vector of std::function with variable Number of Arguments
I want to store event_handler into std::vector, then I will store  a std::vector into a map According to the map key I will call listeners[index].handler_(args...) with different arguments.

I realise the above isn't possible, because std::vector can not store different types; but I wonder if there are any alternatives I should consider.

```<code>template<class... Args>
using Handler = std::function<void(Args &&... args)>;

template<typename T>
struct event_handler  {
    event_handler(Handler<T> handler, bool once) : handler_(std::move(handler)), once_(once) {}

    Handler<T> handler_;
    bool once_;
};

std::vector<event_handler> listeners; // I known this line is wrong, here is just for example
</code>```

答:
You have to separate the values that you want to pass to the event handling functions from your event_handler (maybe none/zero) and those that the application/user of the event_handler want to pass.

The former you define as parameters in your std::function type, this list of parameters must of course be the same for all functions.

The latter are bound to the function calls when the function is passed to your event handler, using std::bind().

Be aware that this solution bears the risk that a user of your library binds pointers or references to variables/objects that don't exist anymore when the handler is executed.

Body:
I want to store event_handler into std::vector, then I will store  a std::vector into a map According to the map key I will call listeners[index].handler_(args...) with different arguments.

I realise the above isn't possible, because std::vector can not store different types; but I wonder if there are any alternatives I should consider.

template<class... Args>
using Handler = std::function<void(Args &&... args)>;

template<typename T>
struct event_handler  {
    event_handler(Handler<T> handler, bool once) : handler_(std::move(handler)), once_(once) {}

    Handler<T> handler_;
    bool once_;
};

std::vector<event_handler> listeners; // I known this line is wrong, here is just for example


问:
"Cannot find module" when importing .csv file in Create React App
I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.

I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.

The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).

I am using TypeScript but I don't think this has anything to do with the problem.

```<code>import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';

const BarChart: React.FC = () => {
  d3.csv(CSVData).then(res => {
    console.log(res);
  });
  return <div>Test</div>;
};

export default BarChart;
</code>```

答:
CRA doesn't support importing .csv files. Without ejecting from CRA, your best option is to copy that file along with the results of yarn/npm build to your web server and then fetching it at runtime.

If that CSV is big (more than a few kb), then it is also the better option in terms of performance/code splitting.

Body:
I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.

I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.

The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).

I am using TypeScript but I don't think this has anything to do with the problem.

import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';

const BarChart: React.FC = () => {
  d3.csv(CSVData).then(res => {
    console.log(res);
  });
  return
Test
;
};

export default BarChart;


问:
LINQ to add continuous records based on a flag to JSON
I have an Entity with set of records

```<code>public class Employee
{
    public int EmpID { get; set; }
    public DateTime EntryTime { get; set; }
    public DateTime ExitTime { get; set; }
    public bool CheckFlag { get; set; }
}

var employees = new List<Employee>();
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0), CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 4, 50, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 3, 35, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 3, 20, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 4, 45, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 2, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 15, 0), CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 1, 45, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0), CheckFlag = false });
</code>```

I want the json group by Employee and sorted by EntryTime and add the records based on CheckFlag. If CheckFlag is true, then it will be a single result and if CheckFlag is false, then iterate till next CheckFlag is true.

I have solved this using foreach loop, but I am wondering whether I can achieve this using LINQ

What is Expected

```<code>[
    {
        "EmpID": 1,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T01:00:00",
                "EndTime": "2020-02-16T02:15:00"
            }
        ]
    },
    {
        "EmpID": 1,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T03:20:00",
                "EndTime": "2020-02-16T03:30:00"
            },
            {
                "StartTime": "2020-02-16T03:35:00",
                "EndTime": "2020-02-16T03:45:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T01:45:00",
                "EndTime": "2020-02-16T02:15:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T02:30:00",
                "EndTime": "2020-02-16T03:15:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T03:30:00",
                "EndTime": "2020-02-16T04:45:00"
            },
            {
                "StartTime": "2020-02-16T04:50:00",
                "EndTime": "2020-02-16T05:15:00"
            }
        ]
    }
]
</code>```

What I tried (foreach group by and order by)

```<code>public class TrackRecord
{
    public int EmpID { get; set; }
    public List<TrackTime> TrackTimes { get; set; }
}

public class TrackTime
{
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
}

var trackRecord = new List<TrackRecord>();
var trackTimes = new List<TrackTime>();
bool checkflag = true;
int prevEmpId = 0;
foreach (var result in employees.GroupBy(x => x.EmpID))
{
    if (!checkflag && trackTimes.Count > 0)
    {
        trackRecord.Add(new TrackRecord()
        {
            EmpID = prevEmpId,
            TrackTimes = trackTimes
        });
        checkflag = true;
        trackTimes = new List<TrackTime>();
    }

    foreach (var employee in result.OrderBy(x => x.EntryTime))
    {
        if (employee.CheckFlag)
        {
            if (!checkflag && trackTimes.Count > 0)
            {
                trackRecord.Add(new TrackRecord()
                {
                    EmpID = employee.EmpID,
                    TrackTimes = trackTimes
                });
                checkflag = true;
                trackTimes = new List<TrackTime>();
            }

            trackRecord.Add(new TrackRecord()
            {
                EmpID = employee.EmpID,
                TrackTimes = new List<TrackTime>() { new TrackTime() { StartTime = employee.EntryTime, EndTime = employee.ExitTime } }
            });
        }
        else
        {
            trackTimes.Add(new TrackTime() { StartTime = employee.EntryTime, EndTime = employee.ExitTime });
            checkflag = false;
        }
    }

    prevEmpId = result.Key;
}

if (!checkflag && trackTimes.Count > 0)
{
    trackRecord.Add(new TrackRecord()
    {
        EmpID = prevEmpId,
        TrackTimes = trackTimes
    });
    checkflag = true;
    trackTimes = new List<TrackTime>();
}

Console.WriteLine(JsonConvert.SerializeObject(trackRecord));
</code>```

答:
For convenience, let's move Employee's DateTime properties into your-already-defined TrackTime class, as follows:

```<code>public class Employee
{
    public int EmpID { get; set; }
    public TrackTime TrackTime { get; set; }
    public bool CheckFlag { get; set; }
}
</code>```

Then your Linq would be:

```<code>var records = employees
  .GroupBy(e => new { e.EmpID, e.CheckFlag })
  .SelectMany(g =>
     g.Key.CheckFlag ?
     g.Select(e => new List<Employee> { e }).ToList() :
     new List<List<Employee>> { g.ToList() })
  .Select(es => new TrackRecord
  {
      EmpID = es.First().EmpID,
      TrackTimes = es.Select(e => e.TrackTime).ToList()
  })
  .OrderBy(e => e.EmpID)
  .ThenBy(e => e.TrackTimes.First().EntryTime)
  .ToList();
</code>```

And with the following input:

```<code>var employees = new List<Employee>();
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 15, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 45, 0), ExitTime = new DateTime(2020, 02, 16, 4, 15, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 4, 30, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 15, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 45, 0), ExitTime = new DateTime(2020, 02, 16, 4, 15, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 4, 30, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0) }, CheckFlag = true });
</code>```

You'd get the following output:

```<code>[
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T01:00:00  ",
        "ExitTime  ": "2020-02-16T02:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T03:15:00  ",
        "ExitTime  ": "2020-02-16T03:30:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:30:00  ",
        "ExitTime  ": "2020-02-16T03:45:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:45:00  ",
        "ExitTime  ": "2020-02-16T04:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T04:30:00  ",
        "ExitTime  ": "2020-02-16T05:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T01:00:00  ",
        "ExitTime  ": "2020-02-16T02:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T03:15:00  ",
        "ExitTime  ": "2020-02-16T03:30:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:30:00  ",
        "ExitTime  ": "2020-02-16T03:45:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:45:00  ",
        "ExitTime  ": "2020-02-16T04:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T04:30:00  ",
        "ExitTime  ": "2020-02-16T05:15:00  "
      }
    ]
  }
]
</code>```

Body:
I have an Entity with set of records

public class Employee
{
    public int EmpID { get; set; }
    public DateTime EntryTime { get; set; }
    public DateTime ExitTime { get; set; }
    public bool CheckFlag { get; set; }
}

var employees = new List<Employee>();
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0), CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 4, 50, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 3, 35, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, EntryTime = new DateTime(2020, 02, 16, 3, 20, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 4, 45, 0), CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 2, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 15, 0), CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, EntryTime = new DateTime(2020, 02, 16, 1, 45, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0), CheckFlag = false });

I want the json group by Employee and sorted by EntryTime and add the records based on CheckFlag. If CheckFlag is true, then it will be a single result and if CheckFlag is false, then iterate till next CheckFlag is true.

I have solved this using foreach loop, but I am wondering whether I can achieve this using LINQ

What is Expected

[
    {
        "EmpID": 1,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T01:00:00",
                "EndTime": "2020-02-16T02:15:00"
            }
        ]
    },
    {
        "EmpID": 1,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T03:20:00",
                "EndTime": "2020-02-16T03:30:00"
            },
            {
                "StartTime": "2020-02-16T03:35:00",
                "EndTime": "2020-02-16T03:45:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T01:45:00",
                "EndTime": "2020-02-16T02:15:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T02:30:00",
                "EndTime": "2020-02-16T03:15:00"
            }
        ]
    },
    {
        "EmpID": 2,
        "TrackTimes": [
            {
                "StartTime": "2020-02-16T03:30:00",
                "EndTime": "2020-02-16T04:45:00"
            },
            {
                "StartTime": "2020-02-16T04:50:00",
                "EndTime": "2020-02-16T05:15:00"
            }
        ]
    }
]

What I tried (foreach group by and order by)

public class TrackRecord
{
    public int EmpID { get; set; }
    public List<TrackTime> TrackTimes { get; set; }
}

public class TrackTime
{
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
}

var trackRecord = new List<TrackRecord>();
var trackTimes = new List<TrackTime>();
bool checkflag = true;
int prevEmpId = 0;
foreach (var result in employees.GroupBy(x => x.EmpID))
{
    if (!checkflag && trackTimes.Count > 0)
    {
        trackRecord.Add(new TrackRecord()
        {
            EmpID = prevEmpId,
            TrackTimes = trackTimes
        });
        checkflag = true;
        trackTimes = new List<TrackTime>();
    }

    foreach (var employee in result.OrderBy(x => x.EntryTime))
    {
        if (employee.CheckFlag)
        {
            if (!checkflag && trackTimes.Count > 0)
            {
                trackRecord.Add(new TrackRecord()
                {
                    EmpID = employee.EmpID,
                    TrackTimes = trackTimes
                });
                checkflag = true;
                trackTimes = new List<TrackTime>();
            }

            trackRecord.Add(new TrackRecord()
            {
                EmpID = employee.EmpID,
                TrackTimes = new List<TrackTime>() { new TrackTime() { StartTime = employee.EntryTime, EndTime = employee.ExitTime } }
            });
        }
        else
        {
            trackTimes.Add(new TrackTime() { StartTime = employee.EntryTime, EndTime = employee.ExitTime });
            checkflag = false;
        }
    }

    prevEmpId = result.Key;
}

if (!checkflag && trackTimes.Count > 0)
{
    trackRecord.Add(new TrackRecord()
    {
        EmpID = prevEmpId,
        TrackTimes = trackTimes
    });
    checkflag = true;
    trackTimes = new List<TrackTime>();
}

Console.WriteLine(JsonConvert.SerializeObject(trackRecord));

Body:
For convenience, let's move Employee's DateTime properties into your-already-defined TrackTime class, as follows:

public class Employee
{
    public int EmpID { get; set; }
    public TrackTime TrackTime { get; set; }
    public bool CheckFlag { get; set; }
}

Then your Linq would be:

var records = employees
  .GroupBy(e => new { e.EmpID, e.CheckFlag })
  .SelectMany(g =>
     g.Key.CheckFlag ?
     g.Select(e => new List<Employee> { e }).ToList() :
     new List<List<Employee>> { g.ToList() })
  .Select(es => new TrackRecord
  {
      EmpID = es.First().EmpID,
      TrackTimes = es.Select(e => e.TrackTime).ToList()
  })
  .OrderBy(e => e.EmpID)
  .ThenBy(e => e.TrackTimes.First().EntryTime)
  .ToList();

And with the following input:

var employees = new List<Employee>();
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 15, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 45, 0), ExitTime = new DateTime(2020, 02, 16, 4, 15, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 1, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 4, 30, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 1, 0, 0), ExitTime = new DateTime(2020, 02, 16, 2, 15, 0) }, CheckFlag = true });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 15, 0), ExitTime = new DateTime(2020, 02, 16, 3, 30, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 30, 0), ExitTime = new DateTime(2020, 02, 16, 3, 45, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 3, 45, 0), ExitTime = new DateTime(2020, 02, 16, 4, 15, 0) }, CheckFlag = false });
employees.Add(new Employee() { EmpID = 2, TrackTime = new TrackTime { EntryTime = new DateTime(2020, 02, 16, 4, 30, 0), ExitTime = new DateTime(2020, 02, 16, 5, 15, 0) }, CheckFlag = true });

You'd get the following output:

[
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T01:00:00  ",
        "ExitTime  ": "2020-02-16T02:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T03:15:00  ",
        "ExitTime  ": "2020-02-16T03:30:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:30:00  ",
        "ExitTime  ": "2020-02-16T03:45:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:45:00  ",
        "ExitTime  ": "2020-02-16T04:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 1,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T04:30:00  ",
        "ExitTime  ": "2020-02-16T05:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T01:00:00  ",
        "ExitTime  ": "2020-02-16T02:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T03:15:00  ",
        "ExitTime  ": "2020-02-16T03:30:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:30:00  ",
        "ExitTime  ": "2020-02-16T03:45:00  "
      },
      {
        "EntryTime  ": "2020-02-16T03:45:00  ",
        "ExitTime  ": "2020-02-16T04:15:00  "
      }
    ]
  },
  {
    "EmpID  ": 2,
    "TrackTimes  ": [
      {
        "EntryTime  ": "2020-02-16T04:30:00  ",
        "ExitTime  ": "2020-02-16T05:15:00  "
      }
    ]
  }
]


问:
Capture Metal MTKView as Movie in realtime?
What is the most efficient way to capture frames from a MTKView? If possible, I would like to save a .mov file from the frames in realtime. Is it possible to render into an AVPlayer frame or something?

It is currently drawing with this code (based on @warrenm PerformanceShaders project):

```<code>func draw(in view: MTKView) {
     _ = inflightSemaphore.wait(timeout: DispatchTime.distantFuture)
             updateBuffers()

    let commandBuffer = commandQueue.makeCommandBuffer()

    commandBuffer.addCompletedHandler{ [weak self] commandBuffer in
        if let strongSelf = self {
            strongSelf.inflightSemaphore.signal()
        }
    }
   // Dispatch the current kernel to perform the selected image filter
    selectedKernel.encode(commandBuffer: commandBuffer,
        sourceTexture: kernelSourceTexture!,
        destinationTexture: kernelDestTexture!)

    if let renderPassDescriptor = view.currentRenderPassDescriptor, let currentDrawable = view.currentDrawable
    {
        let clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
        renderPassDescriptor.colorAttachments[0].clearColor = clearColor

        let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
        renderEncoder.label = "Main pass"

        renderEncoder.pushDebugGroup("Draw textured square")
        renderEncoder.setFrontFacing(.counterClockwise)
        renderEncoder.setCullMode(.back)

        renderEncoder.setRenderPipelineState(pipelineState)
        renderEncoder.setVertexBuffer(vertexBuffer, offset: MBEVertexDataSize * bufferIndex, at: 0)
        renderEncoder.setVertexBuffer(uniformBuffer, offset: MBEUniformDataSize * bufferIndex , at: 1)
        renderEncoder.setFragmentTexture(kernelDestTexture, at: 0)
        renderEncoder.setFragmentSamplerState(sampler, at: 0)
        renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)

        renderEncoder.popDebugGroup()
        renderEncoder.endEncoding()

        commandBuffer.present(currentDrawable)
    }

    bufferIndex = (bufferIndex + 1) % MBEMaxInflightBuffers

    commandBuffer.commit()
 }
</code>```

答:
Upgraded to Swift 5

```<code>
import AVFoundation

class MetalVideoRecorder {
    var isRecording = false
    var recordingStartTime = TimeInterval(0)

    private var assetWriter: AVAssetWriter
    private var assetWriterVideoInput: AVAssetWriterInput
    private var assetWriterPixelBufferInput: AVAssetWriterInputPixelBufferAdaptor

    init?(outputURL url: URL, size: CGSize) {
        do {
          assetWriter = try AVAssetWriter(outputURL: url, fileType: AVFileType.m4v)
        } catch {
            return nil
        }

      let outputSettings: [String: Any] = [ AVVideoCodecKey : AVVideoCodecType.h264,
            AVVideoWidthKey : size.width,
            AVVideoHeightKey : size.height ]

      assetWriterVideoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: outputSettings)
        assetWriterVideoInput.expectsMediaDataInRealTime = true

        let sourcePixelBufferAttributes: [String: Any] = [
            kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA,
            kCVPixelBufferWidthKey as String : size.width,
            kCVPixelBufferHeightKey as String : size.height ]

        assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: assetWriterVideoInput,
                                                                           sourcePixelBufferAttributes: sourcePixelBufferAttributes)

        assetWriter.add(assetWriterVideoInput)
    }

    func startRecording() {
        assetWriter.startWriting()
      assetWriter.startSession(atSourceTime: CMTime.zero)

        recordingStartTime = CACurrentMediaTime()
        isRecording = true
    }

    func endRecording(_ completionHandler: @escaping () -> ()) {
        isRecording = false

        assetWriterVideoInput.markAsFinished()
        assetWriter.finishWriting(completionHandler: completionHandler)
    }

    func writeFrame(forTexture texture: MTLTexture) {
        if !isRecording {
            return
        }

        while !assetWriterVideoInput.isReadyForMoreMediaData {}

        guard let pixelBufferPool = assetWriterPixelBufferInput.pixelBufferPool else {
            print("Pixel buffer asset writer input did not have a pixel buffer pool available; cannot retrieve frame")
            return
        }

        var maybePixelBuffer: CVPixelBuffer? = nil
        let status  = CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &maybePixelBuffer)
        if status != kCVReturnSuccess {
            print("Could not get pixel buffer from asset writer input; dropping frame...")
            return
        }

        guard let pixelBuffer = maybePixelBuffer else { return }

        CVPixelBufferLockBaseAddress(pixelBuffer, [])
        let pixelBufferBytes = CVPixelBufferGetBaseAddress(pixelBuffer)!

        // Use the bytes per row value from the pixel buffer since its stride may be rounded up to be 16-byte aligned
        let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
        let region = MTLRegionMake2D(0, 0, texture.width, texture.height)

        texture.getBytes(pixelBufferBytes, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)

        let frameTime = CACurrentMediaTime() - recordingStartTime
        let presentationTime = CMTimeMakeWithSeconds(frameTime, preferredTimescale:   240)
        assetWriterPixelBufferInput.append(pixelBuffer, withPresentationTime: presentationTime)

        CVPixelBufferUnlockBaseAddress(pixelBuffer, [])

        // You need to release memory allocated to pixelBuffer
        CVPixelBufferRelease(pixelBuffer)
    }
}
</code>```

EDIT: added CVPixelBufferRelease(pixelBuffer) to avoid memory leaks.
Without this during each frame newly created pixelBuffer will stay in the memory and eventually app will you all of the available system memory.

Body:
What is the most efficient way to capture frames from a MTKView? If possible, I would like to save a .mov file from the frames in realtime. Is it possible to render into an AVPlayer frame or something?

It is currently drawing with this code (based on @warrenm PerformanceShaders project):

func draw(in view: MTKView) {
     _ = inflightSemaphore.wait(timeout: DispatchTime.distantFuture)
             updateBuffers()

    let commandBuffer = commandQueue.makeCommandBuffer()

    commandBuffer.addCompletedHandler{ [weak self] commandBuffer in
        if let strongSelf = self {
            strongSelf.inflightSemaphore.signal()
        }
    }
   // Dispatch the current kernel to perform the selected image filter
    selectedKernel.encode(commandBuffer: commandBuffer,
        sourceTexture: kernelSourceTexture!,
        destinationTexture: kernelDestTexture!)

    if let renderPassDescriptor = view.currentRenderPassDescriptor, let currentDrawable = view.currentDrawable
    {
        let clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
        renderPassDescriptor.colorAttachments[0].clearColor = clearColor

        let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
        renderEncoder.label = "Main pass"

        renderEncoder.pushDebugGroup("Draw textured square")
        renderEncoder.setFrontFacing(.counterClockwise)
        renderEncoder.setCullMode(.back)

        renderEncoder.setRenderPipelineState(pipelineState)
        renderEncoder.setVertexBuffer(vertexBuffer, offset: MBEVertexDataSize * bufferIndex, at: 0)
        renderEncoder.setVertexBuffer(uniformBuffer, offset: MBEUniformDataSize * bufferIndex , at: 1)
        renderEncoder.setFragmentTexture(kernelDestTexture, at: 0)
        renderEncoder.setFragmentSamplerState(sampler, at: 0)
        renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)

        renderEncoder.popDebugGroup()
        renderEncoder.endEncoding()

        commandBuffer.present(currentDrawable)
    }

    bufferIndex = (bufferIndex + 1) % MBEMaxInflightBuffers

    commandBuffer.commit()
 }

Body:
Upgraded to Swift 5

import AVFoundation

class MetalVideoRecorder {
    var isRecording = false
    var recordingStartTime = TimeInterval(0)

    private var assetWriter: AVAssetWriter
    private var assetWriterVideoInput: AVAssetWriterInput
    private var assetWriterPixelBufferInput: AVAssetWriterInputPixelBufferAdaptor

    init?(outputURL url: URL, size: CGSize) {
        do {
          assetWriter = try AVAssetWriter(outputURL: url, fileType: AVFileType.m4v)
        } catch {
            return nil
        }

      let outputSettings: [String: Any] = [ AVVideoCodecKey : AVVideoCodecType.h264,
            AVVideoWidthKey : size.width,
            AVVideoHeightKey : size.height ]

      assetWriterVideoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: outputSettings)
        assetWriterVideoInput.expectsMediaDataInRealTime = true

        let sourcePixelBufferAttributes: [String: Any] = [
            kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA,
            kCVPixelBufferWidthKey as String : size.width,
            kCVPixelBufferHeightKey as String : size.height ]

        assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: assetWriterVideoInput,
                                                                           sourcePixelBufferAttributes: sourcePixelBufferAttributes)

        assetWriter.add(assetWriterVideoInput)
    }

    func startRecording() {
        assetWriter.startWriting()
      assetWriter.startSession(atSourceTime: CMTime.zero)

        recordingStartTime = CACurrentMediaTime()
        isRecording = true
    }

    func endRecording(_ completionHandler: @escaping () -> ()) {
        isRecording = false

        assetWriterVideoInput.markAsFinished()
        assetWriter.finishWriting(completionHandler: completionHandler)
    }

    func writeFrame(forTexture texture: MTLTexture) {
        if !isRecording {
            return
        }

        while !assetWriterVideoInput.isReadyForMoreMediaData {}

        guard let pixelBufferPool = assetWriterPixelBufferInput.pixelBufferPool else {
            print("Pixel buffer asset writer input did not have a pixel buffer pool available; cannot retrieve frame")
            return
        }

        var maybePixelBuffer: CVPixelBuffer? = nil
        let status  = CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &maybePixelBuffer)
        if status != kCVReturnSuccess {
            print("Could not get pixel buffer from asset writer input; dropping frame...")
            return
        }

        guard let pixelBuffer = maybePixelBuffer else { return }

        CVPixelBufferLockBaseAddress(pixelBuffer, [])
        let pixelBufferBytes = CVPixelBufferGetBaseAddress(pixelBuffer)!

        // Use the bytes per row value from the pixel buffer since its stride may be rounded up to be 16-byte aligned
        let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
        let region = MTLRegionMake2D(0, 0, texture.width, texture.height)

        texture.getBytes(pixelBufferBytes, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)

        let frameTime = CACurrentMediaTime() - recordingStartTime
        let presentationTime = CMTimeMakeWithSeconds(frameTime, preferredTimescale:   240)
        assetWriterPixelBufferInput.append(pixelBuffer, withPresentationTime: presentationTime)

        CVPixelBufferUnlockBaseAddress(pixelBuffer, [])

        // You need to release memory allocated to pixelBuffer
        CVPixelBufferRelease(pixelBuffer)
    }
}

EDIT: added CVPixelBufferRelease(pixelBuffer) to avoid memory leaks.
Without this during each frame newly created pixelBuffer will stay in the memory and eventually app will you all of the available system memory.


问:
Is it possible to use Cloud NAT with public GKE Cluster?
I have one public GKE cluster with 2 nodes and with that, 2 public external IPs. I want only one egress IP.

I want to use Cloud NAT for that. It seems it is possible.

An alias IP range assigned to the VM's network interface: Even if the
  network interface has an external IP address assigned to it, you can
  configure a Cloud NAT gateway to provide NAT for packets whose sources
  come from an alias IP range of the interface. An external IP address
  on an interface never performs one-to-one NAT for alias IP addresses.

I created a Cloud NAT but it is not working. I use the following commands to get the IP and it always returns one of the IPs of the nodes.

```<code>kubectl run -i --tty get-ip-address --image=dwdraju/alpine-curl-jq --restart=Never
</code>```

and

```<code>curl checkip.amazonaws.com
</code>```

My cluster has VPC native enabled.

答:
Cloud NAT does not work with public clusters. However, this just means that your nodes will not have public IPs. Private clusters can still use public endpoints by using service type LoadBalancer or using ingress resources.

For your endpoint REST API endpoint, use either an ingress or loadbalancer with a static IP to make sure the endpoint is reachable from outside the cluster and the endpoint (IP or URL) is stable.

Body:
I have one public GKE cluster with 2 nodes and with that, 2 public external IPs. I want only one egress IP.

I want to use Cloud NAT for that. It seems it is possible.

An alias IP range assigned to the VM's network interface: Even if the
  network interface has an external IP address assigned to it, you can
  configure a Cloud NAT gateway to provide NAT for packets whose sources
  come from an alias IP range of the interface. An external IP address
  on an interface never performs one-to-one NAT for alias IP addresses.

I created a Cloud NAT but it is not working. I use the following commands to get the IP and it always returns one of the IPs of the nodes.

kubectl run -i --tty get-ip-address --image=dwdraju/alpine-curl-jq --restart=Never

and

curl checkip.amazonaws.com

My cluster has VPC native enabled.