问:
Count the amount of array-childs / items in received nested array in angular, rxjs
I would like to count the amount of array items from a nested array.

I have done this successfully in a not so deeply nested array, and I am curious how I can create a similar outcome with a one level deeper example.

This is how the well-working one goes:

```<code>  const listId = this.route.snapshot.paramMap.get('listId');
  this.listService.getShortlist(listId)
    .subscribe(list =>
      {this.list = list;
      this.showEditlink = this.list.sublistCreators.find(element => element === this.username);
      this.itemcount = this.list.shortlistItem.length;
      });
}
</code>```

The itemcount is what I am looking for. This is usable in my template.

Now, another similar component has the length/count one level deeper, this was my attempt at gaining the array-item-count:

```<code>getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.itemcount = this.list.sublist.item.length;
  })
  )
  }
</code>```

Also tried this (among a lot more):

```<code>   getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.sublist = this.list.sublist
    this.itemcount = this.sublist.item.length;
  })
  )
  }
</code>```

Here I added the this.sublist = this.list.sublist in between. However not able to get this one working.

Can you help me to count the amount of array-items inside 'item'?

Maybe useful to add, below the json I receive from my backend:

In this particular example the outcomes should be 4 and 3.

```<code>{
  "_id": {
    "$oid": "dummy"
  },
  "listTitle": "dummy",
  "listCreator": "dummy",
  "sublist": [
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 4,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        }
      ]
    },
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy"
        }
      ]
    }
  ]
}
</code>```

Thanks a lot for having a look!

答:
I made a small loop to check if we have an Array on key item and if so, we count its length and add it to the sum. If you want any deeper we could introduce recursion on this but I hope this gets you going.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  itemCount: number;
  constructor() {
    this.countItems();
  }

  countItems() {
    let count: number = 0;
    for (let obj of this.returnObjWithArray(this.target)) {
      if (Object.keys(obj).some((key) => key == 'item')) {
        console.log('match: ', obj);
        console.log('the count:', obj.item.length);
        count += obj.item.length;
      }
    }
    console.warn('the sum: ', count);
  }

  returnObjWithArray(obj: any) {
    for (let prop in obj) {
      if (Array.isArray(this.target[prop])) {
        console.log('the obj with array: ', this.target[prop]);
        return this.target[prop];
      }
    }
  }

  target = {
    _id: {
      $oid: 'dummy',
    },
    listTitle: 'dummy',
    listCreator: 'dummy',
    sublist: [
      {
        subListCreator: 'dummy',
        subListAdded: {
          $date: 'dummy',
        },
        item: [
          {
            positionId: 1,
            itemScore: 3,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 2,
            itemScore: 2,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 3,
            itemScore: 1,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 4,
            itemScore: 1,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
        ],
      },
      {
        subListCreator: 'dummy',
        subListAdded: {
          $date: 'dummy',
        },
        item: [
          {
            positionId: 1,
            itemScore: 3,
            itemTitle: 'dummy',
          },
          {
            positionId: 2,
            itemScore: 2,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 3,
            itemScore: 1,
            itemTitle: 'dummy',
          },
        ],
      },
    ],
  };
}
```
<p>console.log()</p>
```match:
{subListCreator: "dummy", subListAdded: {…}, item: Array[4]}
the count:
4
match:
{subListCreator: "dummy", subListAdded: {…}, item: Array[3]}
the count:
3
the sum:
7
```

Here is a working example: https://stackblitz.com/edit/angular-ivy-wpyfox?file=src%2Fapp%2Fapp.component.ts

Body:
I would like to count the amount of array items from a nested array.

I have done this successfully in a not so deeply nested array, and I am curious how I can create a similar outcome with a one level deeper example.

This is how the well-working one goes:

  const listId = this.route.snapshot.paramMap.get('listId');
  this.listService.getShortlist(listId)
    .subscribe(list =>
      {this.list = list;
      this.showEditlink = this.list.sublistCreators.find(element => element === this.username);
      this.itemcount = this.list.shortlistItem.length;
      });
}

The itemcount is what I am looking for. This is usable in my template.

Now, another similar component has the length/count one level deeper, this was my attempt at gaining the array-item-count:

getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.itemcount = this.list.sublist.item.length;
  })
  )
  }

Also tried this (among a lot more):

   getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.sublist = this.list.sublist
    this.itemcount = this.sublist.item.length;
  })
  )
  }

Here I added the this.sublist = this.list.sublist in between. However not able to get this one working.

Can you help me to count the amount of array-items inside 'item'?

Maybe useful to add, below the json I receive from my backend:

In this particular example the outcomes should be 4 and 3.

{
  "_id": {
    "$oid": "dummy"
  },
  "listTitle": "dummy",
  "listCreator": "dummy",
  "sublist": [
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 4,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        }
      ]
    },
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy"
        }
      ]
    }
  ]
}

Thanks a lot for having a look!

Body:
I made a small loop to check if we have an Array on key item and if so, we count its length and add it to the sum. If you want any deeper we could introduce recursion on this but I hope this gets you going.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  itemCount: number;
  constructor() {
    this.countItems();
  }

  countItems() {
    let count: number = 0;
    for (let obj of this.returnObjWithArray(this.target)) {
      if (Object.keys(obj).some((key) => key == 'item')) {
        console.log('match: ', obj);
        console.log('the count:', obj.item.length);
        count += obj.item.length;
      }
    }
    console.warn('the sum: ', count);
  }

  returnObjWithArray(obj: any) {
    for (let prop in obj) {
      if (Array.isArray(this.target[prop])) {
        console.log('the obj with array: ', this.target[prop]);
        return this.target[prop];
      }
    }
  }

  target = {
    _id: {
      $oid: 'dummy',
    },
    listTitle: 'dummy',
    listCreator: 'dummy',
    sublist: [
      {
        subListCreator: 'dummy',
        subListAdded: {
          $date: 'dummy',
        },
        item: [
          {
            positionId: 1,
            itemScore: 3,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 2,
            itemScore: 2,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 3,
            itemScore: 1,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 4,
            itemScore: 1,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
        ],
      },
      {
        subListCreator: 'dummy',
        subListAdded: {
          $date: 'dummy',
        },
        item: [
          {
            positionId: 1,
            itemScore: 3,
            itemTitle: 'dummy',
          },
          {
            positionId: 2,
            itemScore: 2,
            itemTitle: 'dummy',
            itemContext: 'dummy',
          },
          {
            positionId: 3,
            itemScore: 1,
            itemTitle: 'dummy',
          },
        ],
      },
    ],
  };
}

console.log()

match:
{subListCreator: "dummy", subListAdded: {…}, item: Array[4]}
the count:
4
match:
{subListCreator: "dummy", subListAdded: {…}, item: Array[3]}
the count:
3
the sum:
7

Here is a working example: https://stackblitz.com/edit/angular-ivy-wpyfox?file=src%2Fapp%2Fapp.component.ts


来源: stackexchange

问:
Validate decimal numbers in JavaScript - IsNumeric()
What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

Clarity. Solution should be clean and simple.

Cross-platform.

Test cases:

```<code>01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false
</code>```

答:
With regex we can cover all the cases ask in the question. Here it is:

isNumeric for all integers and decimals:

```<code>const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');
</code>```

isInteger for just integers:

```<code>const isInteger = num => /^-?[0-9]+$/.test(num+'');
</code>```

OwnerDisplayName: mharen

ContentLicense: CC BY-SA 3.0

Body:
What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

Clarity. Solution should be clean and simple.

Cross-platform.

Test cases:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

Body:
With regex we can cover all the cases ask in the question. Here it is:

isNumeric for all integers and decimals:

const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');

isInteger for just integers:

const isInteger = num => /^-?[0-9]+$/.test(num+'');

ContentLicense: CC BY-SA 4.0


问:
Github + VSC - badges for new commits?
I am the repo owner and have recently added 3 more collaborators to the project, all of which are now committing changes to the code. Since they are designated as collaborators, they are essentially exempt from approvals, meaning their code is meant to be automatically approved and committed, which so far is working fine.

Where things get weird now is that I am unable to see any file change badges in my VSC Source Control tab. It is my understanding (and please correct me if I am wrong) that if one of my collaborators commits new code (= outdating my local code), VSC Source Control would show me a badge and the files that were updated. Correct?

I now find myself constantly checking the Github repo website for any recent changes so I can manually run git pull in order to get the latest code, which pretty much defeats the purpose of having source control.

So what my question boils down to is this:

is the above described behaviour considered normal when using VSC + Github?

is there a way for me to receive badges/notifications whenever a commit has been issued, alerting me to update my code and making me aware of which files were changed?

Running latest VSC for MAC with the default Source Control tab that is linked to my repo.

Appreciate any help on this, thank you.

答:
First, you would see anything only if new commits are done on the same remote branch as the local one you are working.

In your case, if you are working on main, and the collaborator's PRs are approved and merged to main, then you would see changes.

As noted for VSCode Remotes, you need to set git.autofetch to true:

```<code>  // When set to true, commits will automatically be fetched from the default remote of the current Git repository. Setting to `all` will fetch from all remotes.
  "git.autofetch": false,

  // Duration in seconds between each automatic git fetch, when `git.autofetch` is enabled.
  "git.autofetchPeriod": 180,
</code>```

Title: Github + VSC - badges for new commits?

Body:
First, you would see anything only if new commits are done on the same remote branch as the local one you are working.

In your case, if you are working on main, and the collaborator's PRs are approved and merged to main, then you would see changes.

As noted for VSCode Remotes, you need to set git.autofetch to true:

  // When set to true, commits will automatically be fetched from the default remote of the current Git repository. Setting to `all` will fetch from all remotes.
  "git.autofetch": false,

  // Duration in seconds between each automatic git fetch, when `git.autofetch` is enabled.
  "git.autofetchPeriod": 180,


问:
llc: Too many positional arguments specified (error generating assembly from llvm-ir)
I am getting an error with llc for llvm, which I just installed on my Mac with HomeBrew.

```<code>$ llc –o malloc.s malloc.ll
llc: Too many positional arguments specified!
Can specify at most 1 positional arguments: See: llc --help
</code>```

I have generated a malloc.ll file like this:

```<code>$ clang -emit-llvm -S malloc.c -o malloc.ll
</code>```

How do I set this up to emit assembly?

答:
The llc --help output says to use -o=<filename>, not two separate args like -o and filename.

So when parsing its command line, it sees two options that don't start with -: malloc.s and malloc.ll, and complains about the situation.  Presumably they're rolling their own command line handling instead of using getopt, or they intentionally don't want to support the style where the following arg is consumed by an arg like -o.

Body:
I am getting an error with llc for llvm, which I just installed on my Mac with HomeBrew.

$ llc –o malloc.s malloc.ll
llc: Too many positional arguments specified!
Can specify at most 1 positional arguments: See: llc --help

I have generated a malloc.ll file like this:

$ clang -emit-llvm -S malloc.c -o malloc.ll

How do I set this up to emit assembly?


问:
Interface get returns null value
I'm new with C# and my console application for some reason the interface IService doesn't transfer the value to the Service.  I tried to debug: _service.GetAccountName(name), name has value and then I get System.NullReferenceException for _service.GetAccountName. What I'm doing wrong here? Thank you for your patience.

Program:

```<code>static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Show();

}
</code>```

Menu

```<code> public class Menu
{
    private IService _service { get; set; }

    public void Show()
    {

        var shouldStop = "";

        while (shouldStop.ToLower() != "yes")
        {
            Console.WriteLine("Please select one of the following options:");
            Console.WriteLine("1.Create BC \n2.View BC\n3.Edit BC\n4.Delete BC");
            var response = int.Parse(Console.ReadLine());

            switch (response)
            {
                case 1:
                    Console.WriteLine("You choose to create bank account");
                    ChooseTypeOfAccount();
                    break;
                case 2:
                    Console.WriteLine("You choose to view bank account");
                    var user = ChooseToViewBankAccount();
                    if (user != null)
                    {
                        Console.WriteLine("Id:" + user.Id + "\n"+ user.Name + "\n" + user.Surname);
                    }
                    else
                    {
                        Console.WriteLine("User can not be found");
                    }

                    Console.WriteLine("ALL USERS");
                    var allUs = _service.GetAllUsers();
                    for(var i = 0; i < allUs.Item1.Count; i++)
                    {
                        Console.WriteLine(allUs.Item1[i].Name + " " + allUs.Item1[i].Surname);
                        for(var j = 0; j < allUs.Item2.Count; j++)
                        {
                            Console.WriteLine(allUs.Item2[i].Name + " " + allUs.Item2[i].Surname);
                        }
                    }

                    break;
                case 3:
                    Console.WriteLine("You choose to edit BC");
                    break;
                case 4:
                    Console.WriteLine("You choose to delete BC");
                    break;
                default:
                    Console.WriteLine("oops wrong choice");
                    break;
            }
            Console.WriteLine("To exit type yes");
            shouldStop = Console.ReadLine();
        }

    }

    private User ChooseToViewBankAccount()
    {
        Console.WriteLine("Please enter your name");
        var name = Console.ReadLine();

        User user = _service.GetAccountByName(name);

        return user;
    }
</code>```

Service:

```<code>public class Service : IService
{
    public AccountsData _accountsRepository { get; set; }

    public ChildAccountsData _childAccountRepository { get; set; }

    public Service()
    {
        _accountsRepository = new AccountsData();
        _childAccountRepository = new ChildAccountsData();
    }
</code>```

IService

```<code>public interface IService
{
    User GetAccountByName(string name);
    void CreateRegularAccount(string name, string surname);
    void CreateChildAccount(string childName, string childSurname);
    (List<Account>, List<ChildAccount>) GetAllUsers();
}
</code>```

答:
the most common way is to use dependency injection using a constructor.

```<code> var newMenu = new Menu(new Service ());
</code>```

but you will need to add the constructor to Menu class

```<code> public class Menu
{
    private IService _service { get; set; }

   public Menu (IService service)
{
         _service = service;
}

....
}

</code>```

or less popular way

```<code>var newMenu= new Menu { Service = new Service()}
</code>```

but in this case you will have to change  Service property to public

```<code>public class Menu
{
    public IService Service { get; set; }
   .....
}
</code>```

Title: Interface get returns null value

Body:
I'm new with C# and my console application for some reason the interface IService doesn't transfer the value to the Service.  I tried to debug: _service.GetAccountName(name), name has value and then I get System.NullReferenceException for _service.GetAccountName. What I'm doing wrong here? Thank you for your patience.

Program:

static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Show();

}

Menu

 public class Menu
{
    private IService _service { get; set; }

    public void Show()
    {

        var shouldStop = "";

        while (shouldStop.ToLower() != "yes")
        {
            Console.WriteLine("Please select one of the following options:");
            Console.WriteLine("1.Create BC \n2.View BC\n3.Edit BC\n4.Delete BC");
            var response = int.Parse(Console.ReadLine());

            switch (response)
            {
                case 1:
                    Console.WriteLine("You choose to create bank account");
                    ChooseTypeOfAccount();
                    break;
                case 2:
                    Console.WriteLine("You choose to view bank account");
                    var user = ChooseToViewBankAccount();
                    if (user != null)
                    {
                        Console.WriteLine("Id:" + user.Id + "\n"+ user.Name + "\n" + user.Surname);
                    }
                    else
                    {
                        Console.WriteLine("User can not be found");
                    }

                    Console.WriteLine("ALL USERS");
                    var allUs = _service.GetAllUsers();
                    for(var i = 0; i < allUs.Item1.Count; i++)
                    {
                        Console.WriteLine(allUs.Item1[i].Name + " " + allUs.Item1[i].Surname);
                        for(var j = 0; j < allUs.Item2.Count; j++)
                        {
                            Console.WriteLine(allUs.Item2[i].Name + " " + allUs.Item2[i].Surname);
                        }
                    }

                    break;
                case 3:
                    Console.WriteLine("You choose to edit BC");
                    break;
                case 4:
                    Console.WriteLine("You choose to delete BC");
                    break;
                default:
                    Console.WriteLine("oops wrong choice");
                    break;
            }
            Console.WriteLine("To exit type yes");
            shouldStop = Console.ReadLine();
        }

    }

    private User ChooseToViewBankAccount()
    {
        Console.WriteLine("Please enter your name");
        var name = Console.ReadLine();

        User user = _service.GetAccountByName(name);

        return user;
    }

Service:

public class Service : IService
{
    public AccountsData _accountsRepository { get; set; }

    public ChildAccountsData _childAccountRepository { get; set; }

    public Service()
    {
        _accountsRepository = new AccountsData();
        _childAccountRepository = new ChildAccountsData();
    }

IService

public interface IService
{
    User GetAccountByName(string name);
    void CreateRegularAccount(string name, string surname);
    void CreateChildAccount(string childName, string childSurname);
    (List<Account>, List<ChildAccount>) GetAllUsers();
}

Body:
the most common way is to use dependency injection using a constructor.

 var newMenu = new Menu(new Service ());

but you will need to add the constructor to Menu class

 public class Menu
{
    private IService _service { get; set; }

   public Menu (IService service)
{
         _service = service;
}

....
}

or less popular way

var newMenu= new Menu { Service = new Service()}

but in this case you will have to change  Service property to public

public class Menu
{
    public IService Service { get; set; }
   .....
}


问:
Trying to center text vertically and horizontally next to an image
https://github.com/Yankysamurai/Personal-Website-P5

I am new to posting questions but I am trying to center my text "Welcome to my site" horizontally and vertically. I want it half the distance from the image and from the right margin. I tried display flex but it didn't work.

I just opened a git hub account so I hope you can see the code from the link.

Thank you.

答:
So, the flex container has an img and h2. In order to vertically center the text (relative to the image), you need to set align-items: center;

```<code>.about_img_h2 {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</code>```

I would suggest using jsfiddle next time, because it makes it easier to review the problem. I created this one (using the GitHub repo you shared) with the fix:
https://jsfiddle.net/13sc4m76/

Let me know if I misunderstood your question and I can take a second look.

Body:
So, the flex container has an img and h2. In order to vertically center the text (relative to the image), you need to set align-items: center;

.about_img_h2 {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

I would suggest using jsfiddle next time, because it makes it easier to review the problem. I created this one (using the GitHub repo you shared) with the fix:
https://jsfiddle.net/13sc4m76/

Let me know if I misunderstood your question and I can take a second look.


问:
Event Sourced many-to-many aggregates
We have an event sourced system where we are caching data into aggregates for performance reasons.

Let's say we have 3 entities.  Patient, Doctor, Appointment.

What works well for us is the one-to-many type relations.  Example, imagine the following events:

```<code>* DOCTOR_CREATED
* DOCTOR_ARRIVED
* DOCTOR_LEFT
</code>```

This we could aggregate into a one-to-many type relation.  When a Doctor is added to the system, we can create a row in the database.

Every time they arrive to work, we can add that time to the doctor record, and every time they leave we can also add that.  So we could end up with something like this:

{
  "id": 23,
  "name": "Dr Bill",
  "totalHoursWorked": 124,
  "timesheet": [
    {
      "arrivedAt": "2022-01-04 09:00:00",
      "leftAt": "2022-01-04 14:00:00",
      "hoursWorked":  5,
    },
    // etc...
  ]
}
```
<p>No problems there.</p>
<p>Now let's suppose that we want to track the appointments.  This is a many-to-many relation between users and doctors.</p>
<p>I'm interested in these events:</p>
```* DOCTOR_CREATED
* PATIENT_CREATED
* APPOINTMENT_CREATED
```
<p>Because the event stream must be sequential through time, I cannot create an appointment record BEFORE either the relevant doctor or patient has been created.</p>
<p>How do I go about creating a view of the data model from the perspective of the appointments.</p>
<p>Maybe thinking about it in graphql terminology might help, but I want to optimise this query:</p>
```query {
  appointment {
    day
    time
    patient {
      name
      age
    }
    doctor {
      name
      specialty
    }
  }
}
```

I'd love to be able to store this data structure in the database as an aggregate.  So that fetching appointment by ID can be done in one database query.

I'm going to run into problems here with timelines, because if I wait for the first APPOINTMENT_CREATED event before I create a row in the database, then I've missed the relevant PATIENT and DOCTOR events.

If I capture the PATIENT and DOCTOR events first in anticipation, then I have to store all possible combinations of Doctor and Patient just on the off-chance one of them might want to have an appointment later on.  I'm also faced with this issue of the aggregate having an inconsistent data structure.  Rows in the table might be indexed by doctor-patient id, or appointment id depending on what stage of the event stream we have got to.

The only way I can currently think to do this, is to have the aggregate trying to optimise this query wait for the APPOINTMENT_CREATED event, and then have to asynchronously query the database to retrieve the patient and doctor records at that point in time.

Although the way we've implemented our system, all our aggregates are built up from composition of pure functions which just take the previous aggregate state, the event in question, and return the new aggregate state.

Is what I want impossible with the architecture we have built so far?  Do I need an escape hatch to allow our aggregate hydration to perform async db queries (not keen on this)?

Or is an aggregate the wrong technique to be solving this problem, and that I actually need to use something else (like a cache).  Although having said that, one of the benefits sold to me of going event-sourced was that we wouldn't have to bother with caching as we can just pre-build all our aggregates to be read-optimised for the front end.

答:
I can categorically state that event sourcing does not confer a benefit of not having to bother with caching, nor does it really have anything to do with pre-building aggregates to be read-optimized for the front end.  Read-optimized data models is CQRS, which is not the same thing at all as event sourcing (neither requires the other, though they are a really good fit).

The read-side in a CQRS/ES system is generally not going to be event-sourced: the reason you're doing CQRS alongside event-sourcing is that event-sourced models are terrible for queries, so you're implementing a non-event-sourced data model (e.g. relational or NoSQL documents...) to allow for effective queries.

So don't feel like you need to use the same structures in the read-side as you'd use in the write-side.  Event-sourcing with the same aggregates as the write-side is especially unlikely to be beneficial.

If you do use event-sourced aggregates in the read-side, note that these are going to be different from the aggregates in the write-side.  For instance, the process of constructing a denormalized view of the appointments might be a fine fit for an event-sourced aggregate:

on an APPOINTMENT_CREATED event (which presumably includes a doctor ID and a patient ID) record that this process began to construct a denormalized view

a subscriber for that "began to construct..." event then replays events for the appropriate doctor and patient (any event store should support this: replaying the events for a specific aggregate is the canonical operation in event sourcing) and uses those events to build a "here's the doctor (resp. patient) information for this appointment" command to the process aggregate

the aggregate records the information found and might even record an "everything found" event

another subscriber is building the denormalized view to be saved for easy querying by appointment ID

Note that in this, the "denormalization process" aggregate is pure; the side effects happen in projections of its events.

Would I do this in practice?  Probably not.  I might use a relational DB and have readers do a join.  I might just have the appointment created events kick off async queries to build a denormalized view.  Still, this sort of thing is possible.

Title: Event Sourced many-to-many aggregates

Body:
We have an event sourced system where we are caching data into aggregates for performance reasons.

Let's say we have 3 entities.  Patient, Doctor, Appointment.

What works well for us is the one-to-many type relations.  Example, imagine the following events:

* DOCTOR_CREATED
* DOCTOR_ARRIVED
* DOCTOR_LEFT

This we could aggregate into a one-to-many type relation.  When a Doctor is added to the system, we can create a row in the database.

Every time they arrive to work, we can add that time to the doctor record, and every time they leave we can also add that.  So we could end up with something like this:

{
  "id": 23,
  "name": "Dr Bill",
  "totalHoursWorked": 124,
  "timesheet": [
    {
      "arrivedAt": "2022-01-04 09:00:00",
      "leftAt": "2022-01-04 14:00:00",
      "hoursWorked":  5,
    },
    // etc...
  ]
}

No problems there.

Now let's suppose that we want to track the appointments.  This is a many-to-many relation between users and doctors.

I'm interested in these events:

* DOCTOR_CREATED
* PATIENT_CREATED
* APPOINTMENT_CREATED

Because the event stream must be sequential through time, I cannot create an appointment record BEFORE either the relevant doctor or patient has been created.

How do I go about creating a view of the data model from the perspective of the appointments.

Maybe thinking about it in graphql terminology might help, but I want to optimise this query:

query {
  appointment {
    day
    time
    patient {
      name
      age
    }
    doctor {
      name
      specialty
    }
  }
}

I'd love to be able to store this data structure in the database as an aggregate.  So that fetching appointment by ID can be done in one database query.

I'm going to run into problems here with timelines, because if I wait for the first APPOINTMENT_CREATED event before I create a row in the database, then I've missed the relevant PATIENT and DOCTOR events.

If I capture the PATIENT and DOCTOR events first in anticipation, then I have to store all possible combinations of Doctor and Patient just on the off-chance one of them might want to have an appointment later on.  I'm also faced with this issue of the aggregate having an inconsistent data structure.  Rows in the table might be indexed by doctor-patient id, or appointment id depending on what stage of the event stream we have got to.

The only way I can currently think to do this, is to have the aggregate trying to optimise this query wait for the APPOINTMENT_CREATED event, and then have to asynchronously query the database to retrieve the patient and doctor records at that point in time.

Although the way we've implemented our system, all our aggregates are built up from composition of pure functions which just take the previous aggregate state, the event in question, and return the new aggregate state.

Is what I want impossible with the architecture we have built so far?  Do I need an escape hatch to allow our aggregate hydration to perform async db queries (not keen on this)?

Or is an aggregate the wrong technique to be solving this problem, and that I actually need to use something else (like a cache).  Although having said that, one of the benefits sold to me of going event-sourced was that we wouldn't have to bother with caching as we can just pre-build all our aggregates to be read-optimised for the front end.


问:
How do you change the title of a pdf using django?
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason :

Screenshot

urls.py

```<code>urlpatterns = [
               path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ),
]
</code>```

views.py

```<code>def show_file(response,file_id):
    doc = Document.objects.get(id=file_id)
    pdf = open(f"media/{doc.file}", 'rb')
    return FileResponse(pdf, content_type='application/pdf')
</code>```

models.py

class Document(models.Model):
    title = models.CharField(max_length=65, null=False, blank=False)
    subject = models.CharField(max_length=20)
    grade = models.IntegerField()
    file = models.FileField(upload_to="documents/")
    date_uploaded = models.DateField(null=False)
```
<p><code>forms.py</code></p>
<pre class="lang-py prettyprint-override"><code>class DocumentsForm(forms.ModelForm):
    subject = forms.ChoiceField(choices=subject_choices)
    grade = forms.ChoiceField(choices=grade_choices)
    class Meta:
        model = Document
        fields = ("title","subject","grade","file","date_uploaded")
</code>```

答:
You just have to include the file title in the URL like so, but first pass it from your template.

urls.py

```<code>    urlpatterns = [
     path("show_file/<file_id>/<file_title>",v.show_file, name="show_file" ),
            ]

</code>```

like:

```<code>    <a href=
    "{% url 'show_file' file_id=file.id file_title=file.title %}"
    class="text-right">View</a>

</code>```

Body:
So I have this app that allows you to upload pdfs then you can view them in the browser and it works fine but the only problem is that my title is a regex for some reason :

Screenshot

urls.py

urlpatterns = [
               path("show_file/r'^(?P<file_id>\d+)",v.show_file, name="show_file" ),
]

views.py

def show_file(response,file_id):
    doc = Document.objects.get(id=file_id)
    pdf = open(f"media/{doc.file}", 'rb')
    return FileResponse(pdf, content_type='application/pdf')

models.py

class Document(models.Model):
    title = models.CharField(max_length=65, null=False, blank=False)
    subject = models.CharField(max_length=20)
    grade = models.IntegerField()
    file = models.FileField(upload_to="documents/")
    date_uploaded = models.DateField(null=False)

forms.py

class DocumentsForm(forms.ModelForm):
    subject = forms.ChoiceField(choices=subject_choices)
    grade = forms.ChoiceField(choices=grade_choices)
    class Meta:
        model = Document
        fields = ("title","subject","grade","file","date_uploaded")

Body:
You just have to include the file title in the URL like so, but first pass it from your template.

urls.py

    urlpatterns = [
     path("show_file/<file_id>/<file_title>",v.show_file, name="show_file" ),
            ]

like:

    <a href=
    "{% url 'show_file' file_id=file.id file_title=file.title %}"
    class="text-right">View</a>


问:
Is there a Linux equivalent of LightIngest.exe?
Is there a Linux equivalent of LightIngest.exe? The page of the utility does not mention that, search brings no luck either. In case it is not available, what is the preferred way to post ingestion items through CLI in Linux?</p>

答:
Thanks to Vladik's answer I was able to download the package and use the included LightIngest.dll to execute an ingest through my Mac. Here are the steps:

Use nuget to download the Microsoft.Azure.Kusto.Tools.NETCore package installed:

```<code>nuget install Microsoft.Azure.Kusto.Tools.NETCore  -Source nuget.org -OutputDirectory SPECIFY_OUTPUT_DIRECTORY
</code>```

Navigate to the directory, and go to the tools subfolder. There you should find LightIngest.dll

Assuming you have dotnet installed (CLI) and SDK (v2.1) you should be able to execute an ingestion:

```<code>dotnet ./LightIngest.dll ...
</code>```

Replace the ... with the Windows equivalent command that Azure Data Explorer Ingestion wizard suggested, and it should start ingesting!

Body:
Thanks to Vladik's answer I was able to download the package and use the included LightIngest.dll to execute an ingest through my Mac. Here are the steps:

Use nuget to download the Microsoft.Azure.Kusto.Tools.NETCore package installed:

nuget install Microsoft.Azure.Kusto.Tools.NETCore  -Source nuget.org -OutputDirectory SPECIFY_OUTPUT_DIRECTORY

Navigate to the directory, and go to the tools subfolder. There you should find LightIngest.dll

Assuming you have dotnet installed (CLI) and SDK (v2.1) you should be able to execute an ingestion:

dotnet ./LightIngest.dll ...

Replace the ... with the Windows equivalent command that Azure Data Explorer Ingestion wizard suggested, and it should start ingesting!


问:
nodejs variable undefined when exporting
Hey I was wondering why the following returns undefined:

```<code>let variable;

module.exports.initialize = () => {
  variable = "123";
};

module.exports.variable = variable;

</code>```

I simply require the module in file A and then call the initialize function. In file B I require it and console.log the variable but it returns undefined. What am I missing here?

答:
In JavaScript there are two types of values: 1) primitive type and 2) reference type. primitive values are always copied by their value and reference types are always copied by their references (not by their values).

Examples of primitive values: undefined, null, boolean, string, number.
Examples of reference types: every types other than primitive types. e.g., Object, array etc. See the snippet below.

Example of Primitive type

let a = 10;
let b = a;

console.log(a);
console.log(b);

b = 20;

console.log(a);
console.log(b);```
</div>
</div>
</p>
<h2>Example of Reference type</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj_a = {value: 1}
let obj_b = obj_a;

console.log(obj_a);
console.log(obj_b);

obj_b.value = 20;

console.log(obj_a);
console.log(obj_b);</code>```

So when you declare the variable as let variable its value is undefined and when you assign module.exports.variable = variable then you're just setting it's value to undefined.

See the example below.

const myExports = {};

let variable;

function initialize() {
  variable = 10;
}

myExports.variable = variable;

console.log(variable);
console.log(myExports.variable);

initialize();

console.log(variable);
console.log(myExports.variable);```
</div>
</div>
</p>
<p>But if you were to initialize the the <code>variable</code> with a <strong>reference type</strong> e.g., an <strong>object</strong> then <code>module.exports.variable</code> would reflect any change to the properties of your <code>variable</code> variable.</p>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const myExports = {};

let object = {};

function initialize() {
  object.value = 10;
}

myExports.variable = object;

console.log(object);
console.log(myExports.variable);

initialize();

console.log(object);
console.log(myExports.variable);</code>```

Hope it make sense.

Body:
Hey I was wondering why the following returns undefined:

let variable;

module.exports.initialize = () => {
  variable = "123";
};

module.exports.variable = variable;

I simply require the module in file A and then call the initialize function. In file B I require it and console.log the variable but it returns undefined. What am I missing here?

Body:
In JavaScript there are two types of values: 1) primitive type and 2) reference type. primitive values are always copied by their value and reference types are always copied by their references (not by their values).

Examples of primitive values: undefined, null, boolean, string, number.
Examples of reference types: every types other than primitive types. e.g., Object, array etc. See the snippet below.

Example of Primitive type

let a = 10;
let b = a;

console.log(a);
console.log(b);

b = 20;

console.log(a);
console.log(b);

Example of Reference type

let obj_a = {value: 1}
let obj_b = obj_a;

console.log(obj_a);
console.log(obj_b);

obj_b.value = 20;

console.log(obj_a);
console.log(obj_b);

So when you declare the variable as let variable its value is undefined and when you assign module.exports.variable = variable then you're just setting it's value to undefined.

See the example below.

const myExports = {};

let variable;

function initialize() {
  variable = 10;
}

myExports.variable = variable;

console.log(variable);
console.log(myExports.variable);

initialize();

console.log(variable);
console.log(myExports.variable);

But if you were to initialize the the variable with a reference type e.g., an object then module.exports.variable would reflect any change to the properties of your variable variable.

Example:

const myExports = {};

let object = {};

function initialize() {
  object.value = 10;
}

myExports.variable = object;

console.log(object);
console.log(myExports.variable);

initialize();

console.log(object);
console.log(myExports.variable);

Hope it make sense.


问:
Birthday Paradox count keeps growing in python
I need this code to output the total count of matching birthdays, but the count keeps growing and I don't know why. We should expect to see a total approx. half the amount of the simulations. I have it appending to a list at the moment to visualize the change in the count.

```<code>import random
birthmonth = []
birthday= []
def birthday_paradox():
    """

    """
    months31 = (1,3,5,7,8,10,12)
    months30 = (4,6,9,11)
    day31 = random.randint(1,31)
    day30 = random.randint(1,30)
    day29 = random.randint(1,29)
    month = random.randint(1,12)

    for i in months31:
        if month == i:
            birthmonth.append(month)
            birthday.append(day31)
    for i in months30:
        if month == i:
            birthmonth.append(month)
            birthday.append(day30)
    if month == 2:
        birthmonth.append(month)
        birthday.append(day29)

def frequency_of_matches(number_of_people:int = 23):
    """

    """
    count = 0
    for i in range(number_of_people):
        birthday_paradox()
    sorted_birthday_list = sorted(list(zip(birthmonth, birthday)))

    for i in range(len(sorted_birthday_list)):
        if sorted_birthday_list[i] == sorted_birthday_list[i - 1]:
            count += 1
    return count

def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total

simulations(25)
</code>```

Example output:

```<code>[1, 3, 7, 9, 13, 23, 28, 42, 51, 61, 70, 84, 97, 112, 124, 138, 153, 163, 178, 196, 213, 228, 244, 261, 277]
</code>```

答:
The root problem is that your birthmonth and birthday lists keep growing and growing and growing.  You never clear them out.  That's why your design -- modifying globals -- is a bad one.  The function should start fresh and RETURN its output.  Globals are evil.

Also, your method of choosing the random birthdays is loony.  Here is a replacement that only needs one random number, and only uses one global, which is a constant.

```<code>import random
import datetime

jan1 = datetime.datetime(2022,1,1)

def birthday_paradox():
    base = jan1 + datetime.timedelta(days=random.randint(0,364))
    return base.month,base.day

def frequency_of_matches(number_of_people:int = 23):
    birthdays = [birthday_paradox() for i in range(number_of_people)]
    birthdays.sort()

    count = 0
    for i in range(len(birthdays)-1):
        if birthdays[i] == birthdays[i+1]:
            count += 1
    return count

def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total

print(simulations(25))
</code>```

If you are really, really bothered by the lack of February 29 here, then change to:

```<code>    base = jan1 + datetime.timedelta(days=random.randint(0,365*4+1))
</code>```

Body:
I need this code to output the total count of matching birthdays, but the count keeps growing and I don't know why. We should expect to see a total approx. half the amount of the simulations. I have it appending to a list at the moment to visualize the change in the count.

import random
birthmonth = []
birthday= []
def birthday_paradox():
    """

    """
    months31 = (1,3,5,7,8,10,12)
    months30 = (4,6,9,11)
    day31 = random.randint(1,31)
    day30 = random.randint(1,30)
    day29 = random.randint(1,29)
    month = random.randint(1,12)

    for i in months31:
        if month == i:
            birthmonth.append(month)
            birthday.append(day31)
    for i in months30:
        if month == i:
            birthmonth.append(month)
            birthday.append(day30)
    if month == 2:
        birthmonth.append(month)
        birthday.append(day29)

def frequency_of_matches(number_of_people:int = 23):
    """

    """
    count = 0
    for i in range(number_of_people):
        birthday_paradox()
    sorted_birthday_list = sorted(list(zip(birthmonth, birthday)))

    for i in range(len(sorted_birthday_list)):
        if sorted_birthday_list[i] == sorted_birthday_list[i - 1]:
            count += 1
    return count

def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total

simulations(25)

Example output:

[1, 3, 7, 9, 13, 23, 28, 42, 51, 61, 70, 84, 97, 112, 124, 138, 153, 163, 178, 196, 213, 228, 244, 261, 277]

Body:
The root problem is that your birthmonth and birthday lists keep growing and growing and growing.  You never clear them out.  That's why your design -- modifying globals -- is a bad one.  The function should start fresh and RETURN its output.  Globals are evil.

Also, your method of choosing the random birthdays is loony.  Here is a replacement that only needs one random number, and only uses one global, which is a constant.

import random
import datetime

jan1 = datetime.datetime(2022,1,1)

def birthday_paradox():
    base = jan1 + datetime.timedelta(days=random.randint(0,364))
    return base.month,base.day

def frequency_of_matches(number_of_people:int = 23):
    birthdays = [birthday_paradox() for i in range(number_of_people)]
    birthdays.sort()

    count = 0
    for i in range(len(birthdays)-1):
        if birthdays[i] == birthdays[i+1]:
            count += 1
    return count

def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total

print(simulations(25))

If you are really, really bothered by the lack of February 29 here, then change to:

    base = jan1 + datetime.timedelta(days=random.randint(0,365*4+1))


问:
Why doesn't firebase admin messaging send notifications to all device token in multicast?
I know there are lot of questions around this question, and I promise I've checked quiet a number of them but non seems to give me an exact answer

I'm using firebase cloud function's admin messaging SDK to send push notifications to an array of device token I put together from my users collection.

The code:

```<code>  let deviceToken = [<device tokens>];
  let payload = {
    notification: {
      title: main_title,
      body: notf_body,
    },
    data: {
     <data object>
    },
  };
  await messaging
    .sendToDevice(deviceToken, payload)
    .then((response) => {
      console.log("Successfully sent message to::", response.successCount);
    })
    .catch((error) => {
      console.log("Error sending message:", error);
    });
} else {
  console.log("ARTICLE PUBLISHED BUT NOT BROADCASTED");
  return;
}
</code>```

seems to be working fine but the push notification is never sent to all the device token in the array...

Below is a log of the function triggered, where 49 device token are present in the array but only 32 notifications are successful

What could be the reason for this, as some clients have been complaining they aren't getting notification

答:
There are quite some reasons why sending a message to a token might fail. The specific reason for each token that failed is specified in the response.results that you get back.

The most common reasons are that tokens get outdated/expired over time, meaning they won't work anymore. In a well working app, you'll register new tokens for the those same devices, but failure to clean up the old tokens from your database will result in more and more failures over time.

For a good example of how to deal with these errors and clean up outdated tokens, see this code from the example of sending notifications in Cloud Functions:

```<code>// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
  const error = result.error;
  if (error) {
    functions.logger.error(
      'Failure sending notification to',
      tokens[index],
      error
    );
    // Cleanup the tokens who are not registered anymore.
    if (error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered') {
      tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
    }
  }
});
return Promise.all(tokensToRemove);
</code>```

Body:
I know there are lot of questions around this question, and I promise I've checked quiet a number of them but non seems to give me an exact answer

I'm using firebase cloud function's admin messaging SDK to send push notifications to an array of device token I put together from my users collection.

The code:

  let deviceToken = [<device tokens>];
  let payload = {
    notification: {
      title: main_title,
      body: notf_body,
    },
    data: {
     <data object>
    },
  };
  await messaging
    .sendToDevice(deviceToken, payload)
    .then((response) => {
      console.log("Successfully sent message to::", response.successCount);
    })
    .catch((error) => {
      console.log("Error sending message:", error);
    });
} else {
  console.log("ARTICLE PUBLISHED BUT NOT BROADCASTED");
  return;
}

seems to be working fine but the push notification is never sent to all the device token in the array...

Below is a log of the function triggered, where 49 device token are present in the array but only 32 notifications are successful

What could be the reason for this, as some clients have been complaining they aren't getting notification

Body:
There are quite some reasons why sending a message to a token might fail. The specific reason for each token that failed is specified in the response.results that you get back.

The most common reasons are that tokens get outdated/expired over time, meaning they won't work anymore. In a well working app, you'll register new tokens for the those same devices, but failure to clean up the old tokens from your database will result in more and more failures over time.

For a good example of how to deal with these errors and clean up outdated tokens, see this code from the example of sending notifications in Cloud Functions:

// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
  const error = result.error;
  if (error) {
    functions.logger.error(
      'Failure sending notification to',
      tokens[index],
      error
    );
    // Cleanup the tokens who are not registered anymore.
    if (error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered') {
      tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
    }
  }
});
return Promise.all(tokensToRemove);


问:
Python - How to unpack key with key,value pair?
Anyone can help and explain how to unpack items from key with many key,value pair?

```<code>{'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}
</code>```

I need transform 'result' to dictionary.

```<code># Print type 'dict'
print(type(result2))

#Print type 'list'
print(type(result2['result']))

output = []

# Here i get error

for key_value in result2['result']:
    key, value = key_value.split(': ', 1)
    if not output or key in output[-1]:
        output.append({})
    output[-1][key] = value

print(output)

"""
    key, value = key_value.split(': ', 1)
AttributeError: 'dict' object has no attribute 'split'
"""
</code>```

Thank you in advance

答:
As clearly result2['result'] is a list but that list contains the dict which you want.

So to get that simply unpack this list and get the frst element;

result2['result'][0]

Body:
Anyone can help and explain how to unpack items from key with many key,value pair?

{'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}

I need transform 'result' to dictionary.

# Print type 'dict'
print(type(result2))

#Print type 'list'
print(type(result2['result']))

output = []

# Here i get error

for key_value in result2['result']:
    key, value = key_value.split(': ', 1)
    if not output or key in output[-1]:
        output.append({})
    output[-1][key] = value

print(output)

"""
    key, value = key_value.split(': ', 1)
AttributeError: 'dict' object has no attribute 'split'
"""

Thank you in advance


问:
I can't seem to concatenate an API URL with a variable
I am fetching an exchange rates API. The API looks like this: https://v6.exchangerate-api.com/v6/Your-Api-Key/latest/AMD, where "Your-API-Key" is my personal key. If the API URL ends with USD or AMD, the API recognises the base currency as USD or AMD and then gives the exchange rate in other currencies, including the base currency.

For example:

HTML:

<select name="BaseCurrency" id="BaseCurrency">
    <option value="NGN">NGN</option>
    <option value="USD">USD</option>
    <option value="ALL">ALL</option>
</select>
```
<p>JavaScript code:</p>
<pre class="lang-js prettyprint-override"><code>async function fetchCurrencyData() {
    let baseCurrencyValue = document.getElementById("BaseCurrency").value;
    console.log(baseCurrencyValue) // logs selected HTML option value, say "NGN" or "USD", based on user selection.

    let result = await fetch(`https://v6.exchangerate-api.com/v6/My-Api-Key/latest/${baseCurrencyValue}`);
    let record = await result.json();
    console.log("Hey " + JSON.stringify(record.conversion_rates.baseCurrencyValue)); //This logs "Hey undefined" but when I replace baseCurrencyValue with an actual currency code, like USD, it prints out the correct rate"
</code>```

What can I do to make sure that concatenating the variable "baseCurrencyValue" at the end of the API, will work? Because I need to allow the user's choice to be the base currency

I have also tried concatenating with the plus sign:

let result = await fetch("https://v6.exchangerate-api.com/v6/My-Api-Key/latest/" + baseCurrencyValue);
```

But it isn't working either.

答:
You ensure that it will work by controlling what inputs you accept. Also I noticed that there is a CORS issue with this API, which can be fixed with corsAnywhere. Ideally you should be calling external APIs on your backend not your frontend.

<select name="BaseCurrency" id="base-currency">
    <option value="NGN">NGN</option>
    <option value="USD">USD</option>
    <option value="ALL">ALL</option>
</select>

<button onclick="fetchCurrencyData()">click</button>

```

Body:
I am fetching an exchange rates API. The API looks like this: https://v6.exchangerate-api.com/v6/Your-Api-Key/latest/AMD, where "Your-API-Key" is my personal key. If the API URL ends with USD or AMD, the API recognises the base currency as USD or AMD and then gives the exchange rate in other currencies, including the base currency.

For example:

HTML:

<select name="BaseCurrency" id="BaseCurrency">
    <option value="NGN">NGN</option>
    <option value="USD">USD</option>
    <option value="ALL">ALL</option>
</select>

JavaScript code:

async function fetchCurrencyData() {
    let baseCurrencyValue = document.getElementById("BaseCurrency").value;
    console.log(baseCurrencyValue) // logs selected HTML option value, say "NGN" or "USD", based on user selection.

    let result = await fetch(`https://v6.exchangerate-api.com/v6/My-Api-Key/latest/${baseCurrencyValue}`);
    let record = await result.json();
    console.log("Hey " + JSON.stringify(record.conversion_rates.baseCurrencyValue)); //This logs "Hey undefined" but when I replace baseCurrencyValue with an actual currency code, like USD, it prints out the correct rate"

What can I do to make sure that concatenating the variable "baseCurrencyValue" at the end of the API, will work? Because I need to allow the user's choice to be the base currency

I have also tried concatenating with the plus sign:

let result = await fetch("https://v6.exchangerate-api.com/v6/My-Api-Key/latest/" + baseCurrencyValue);

But it isn't working either.

Body:
You ensure that it will work by controlling what inputs you accept. Also I noticed that there is a CORS issue with this API, which can be fixed with corsAnywhere. Ideally you should be calling external APIs on your backend not your frontend.

<select name="BaseCurrency" id="base-currency">
    <option value="NGN">NGN</option>
    <option value="USD">USD</option>
    <option value="ALL">ALL</option>
</select>

<button onclick="fetchCurrencyData()">click</button>

<script>
    async function fetchCurrencyData() {
        const baseCurrencyValue = document.getElementById('base-currency').value;

        const result = await fetch(
            `https://cors-anywhere.herokuapp.com/https://v6.exchangerate-api.com/v6/APIKEYHERE/latest/${baseCurrencyValue}`
        );
        const { conversion_rates } = await result.json();

        console.log(conversion_rates);
    }
</script>


问:
Best way to create virtual registers in C++
I'm trying to create a barebones VM that can only execute x86 assembly code for a highschool project, and I figured to create all of the registers using structs. I have all of the instructions, opcodes, and operand logic implemented already, but I'm worried that this kind of botching of creating CPU registers won't be good in the long term as the project grows and I'm mostly worried if it's not the best way to implement virtual registers, not to mention it looks pretty ugly with all the repetitive code I made. If anybody could make it better or make it more efficient, that would be really helpful.</p>
```<code>#include <iostream>
#include <cstdlib>

// 64-bit registers
struct ULL_REGISTER_STRUCT {
    int64_t RAX; // accumulator
    int64_t RCX; // counter
    int64_t RDX; // data
    int64_t RBX; // base
    int64_t RSP; // stack pointer
    int64_t RBP; // stack base pointer
    int64_t RSI; // source index
    int64_t RDI; // destination index
} ULL_REGISTERS;

// 32-bit registers
struct UL_REGISTER_STRUCT {
    int32_t EAX;
    int32_t ECX;
    int32_t EDX;
    int32_t EBX;
    int32_t ESP;
    int32_t EBP;
    int32_t ESI;
    int32_t EDI;
} UL_REGISTERS;

// 16-bit
struct SHORT_REGISTER_STRUCT {
    int16_t AX;
    int16_t CX;
    int16_t DX;
    int16_t BX;
    int16_t SP;
    int16_t BP;
    int16_t SI;
    int16_t DI;
} SHORT_REGISTERS;

// 8-bit registers
struct CHAR_REGISTER_STRUCT {
    int8_t AH;
    int8_t AL;
    int8_t CH;
    int8_t CL;
    int8_t DH;
    int8_t DL;
    int8_t BH;
    int8_t BL;

    int8_t SPL;
    int8_t BPL;
    int8_t SIL;
    int8_t DIL;
} CHAR_REGISTERS;
</code>```

答:
I wrote a PDP11 emulator in c++ recently I did this

```<code>   uint16_t registers[8];
   uint16_t &PC = registers[0];
   uint16_t &R1 = registers[1];
   .....
</code>```

ie create an array of registers so I can save them as a block or whatever but create references with the well known names for each register

Body:
I'm trying to create a barebones VM that can only execute x86 assembly code for a highschool project, and I figured to create all of the registers using structs. I have all of the instructions, opcodes, and operand logic implemented already, but I'm worried that this kind of botching of creating CPU registers won't be good in the long term as the project grows and I'm mostly worried if it's not the best way to implement virtual registers, not to mention it looks pretty ugly with all the repetitive code I made. If anybody could make it better or make it more efficient, that would be really helpful.

#include <iostream>
#include <cstdlib>

// 64-bit registers
struct ULL_REGISTER_STRUCT {
    int64_t RAX; // accumulator
    int64_t RCX; // counter
    int64_t RDX; // data
    int64_t RBX; // base
    int64_t RSP; // stack pointer
    int64_t RBP; // stack base pointer
    int64_t RSI; // source index
    int64_t RDI; // destination index
} ULL_REGISTERS;

// 32-bit registers
struct UL_REGISTER_STRUCT {
    int32_t EAX;
    int32_t ECX;
    int32_t EDX;
    int32_t EBX;
    int32_t ESP;
    int32_t EBP;
    int32_t ESI;
    int32_t EDI;
} UL_REGISTERS;

// 16-bit
struct SHORT_REGISTER_STRUCT {
    int16_t AX;
    int16_t CX;
    int16_t DX;
    int16_t BX;
    int16_t SP;
    int16_t BP;
    int16_t SI;
    int16_t DI;
} SHORT_REGISTERS;

// 8-bit registers
struct CHAR_REGISTER_STRUCT {
    int8_t AH;
    int8_t AL;
    int8_t CH;
    int8_t CL;
    int8_t DH;
    int8_t DL;
    int8_t BH;
    int8_t BL;

    int8_t SPL;
    int8_t BPL;
    int8_t SIL;
    int8_t DIL;
} CHAR_REGISTERS;

Body:
I wrote a PDP11 emulator in c++ recently I did this

   uint16_t registers[8];
   uint16_t &PC = registers[0];
   uint16_t &R1 = registers[1];
   .....

ie create an array of registers so I can save them as a block or whatever but create references with the well known names for each register


问:
priority if numbers in heap in python 3
Can someone explain me what's wrong in this code:

```<code>import heapq
a = [[1, 2], [0, 4], [3]]
h = []
for index in range(len(a)):
    i = 0
    while i < len(a[index]):
        heapq.heappush(h, a[index][i])
        i += 1
print(h)
</code>```

I want to have smth like that: [0, 1, 2, 3, 4], but when I add 0 it's not becoming [0, 1, 2] but becoming [0, 2, 1].WHY? Thank you in advance!

答:
What you're observing is intended behavior. Generally speaking, the top n values of a heap are not necessarily the smallest n values in the heap. (If this were true, we'd be able to sort in linear time by heapifying a list. But, heapifying a list is a linear-time operation, and comparison-based sorting requires O(n log n) time.)

To extract the smallest n elements, use heappop() n times:

import heapq
a = [[1, 2], [0, 4], [3]]
h = []
for index in range(len(a)):
    i = 0
    while i < len(a[index]):
        heapq.heappush(h, a[index][i])
        i += 1

n = 3
for i in range(n):
    print(heapq.heappop(h)) # Prints 0, 1, 2
```

Title: priority if numbers in heap in python 3

Body:
Can someone explain me what's wrong in this code:

import heapq
a = [[1, 2], [0, 4], [3]]
h = []
for index in range(len(a)):
    i = 0
    while i < len(a[index]):
        heapq.heappush(h, a[index][i])
        i += 1
print(h)

I want to have smth like that: [0, 1, 2, 3, 4], but when I add 0 it's not becoming [0, 1, 2] but becoming [0, 2, 1].WHY? Thank you in advance!


问:
SQL Server 'FETCH FIRST 1 ROWS ONLY' Invalid usage
I am trying to convert a Db2 query to SQL Server, I came across a construct I am not familiar with: FETCH  FIRST 1 ROWS ONLY.

This is the query working on db2:

```<code>select * from products.series where state = 'xxx' order by id
FETCH FIRST 1 ROWS ONLY
</code>```

and the error I am getting on SQL Server:

```<code>Invalid usage of the option FIRST in the FETCH statement.
</code>```

I have tried replacing FIRST with NEXT which seems to be admitted in SQL Server, but with no success.

I am using SQL Sever 2014

答: SELECT TOP 1 * FROM (select * from products.series where state = 'xxx') as tmp ORDER BY id</p>

Body:
I am trying to convert a Db2 query to SQL Server, I came across a construct I am not familiar with: FETCH  FIRST 1 ROWS ONLY.

This is the query working on db2:

select * from products.series where state = 'xxx' order by id
FETCH FIRST 1 ROWS ONLY

and the error I am getting on SQL Server:

Invalid usage of the option FIRST in the FETCH statement.

I have tried replacing FIRST with NEXT which seems to be admitted in SQL Server, but with no success.

I am using SQL Sever 2014


问:
Failed to execute 'pushState' on 'History' error when using window.history.pushState function
I'm using window.history in JavascriptMVC application to enable back/forward/refresh functionality for each controller. Every time I load a new controller I'm using  window.history.pushState to add a new state to history. And then on back/refresh I'm using the saved state and reuse the data to build the controller again.

The whole idea works fine excepting one issue on specific scenario. I'm getting the following error:

Failed to execute 'pushState' on 'History': An object could not be
  cloned.

The same data is added without problem on other scenario. What can cause this error?
Thanks for the assistance.

答:
Try to pass the object in a queryParams:

```<code>this.router.navigate(['yourRoute'], { queryParams: objectToPass});
</code>```

That works for me.

Body:
Try to pass the object in a queryParams:

this.router.navigate(['yourRoute'], { queryParams: objectToPass});

That works for me.


答:
result2['result'] is a list of dicts.  To iterate over the list, you can do for result in result2['result']  To iterate over each resulting dict, you can do for key, value in result.items().

```<code>result2 = {'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}

output = [{}]
for result in result2['result']:
    for key, value in result.items():
        if key in output[-1]:
            output.append({})
        output[-1][key] = value

print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]
</code>```

This code goes to a lot of trouble to iterate through each dictionary and accumulate a list of new dictionaries for the apparent purpose of combining dictionaries with disjoint sets of keys, but for this particular input, or any other input where each dictionary in result has the same keys, or any input where there's only one dictionary, there's no point in iterating over the dictionaries at all.  You could just as easily do:

```<code>output = result2['result']
print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]
</code>```

to get the same exact output with none of the work.

Title: Python - How to unpack key with key,value pair?

Body:
result2['result'] is a list of dicts.  To iterate over the list, you can do for result in result2['result']  To iterate over each resulting dict, you can do for key, value in result.items().

result2 = {'jsonrpc': '2.0', 'result': [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}], 'id': '1'}

output = [{}]
for result in result2['result']:
    for key, value in result.items():
        if key in output[-1]:
            output.append({})
        output[-1][key] = value

print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]

This code goes to a lot of trouble to iterate through each dictionary and accumulate a list of new dictionaries for the apparent purpose of combining dictionaries with disjoint sets of keys, but for this particular input, or any other input where each dictionary in result has the same keys, or any input where there's only one dictionary, there's no point in iterating over the dictionaries at all.  You could just as easily do:

output = result2['result']
print(output)
# [{'userid': '8', 'clock': '1644715846', 'action': '3', 'resourceid': '0'}]

to get the same exact output with none of the work.


问:
Postgresql how to group the values in on column of a table and transpose the unique values of another column in the same table, and sum up the rows
I am new to SQL in general, hence this problem is a little tricky to me. I have a table like the example below:

Input Values:

And, I wish to get the following output:

Output Result:

Honestly, I have no idea how to begin to solve this problem. I would appreciate a hint and/or an example solution from anyone. Thank you in advance.

答:
You can perform conditional aggregation and then use a ROLLUP.

For example:

```<code>select
  velocity,
  sum(case when volume = 'VERY HIGH' then sales else 0 end) as very_high,
  sum(case when volume = 'HIGH' then sales else 0 end) as high,
  sum(case when volume = 'MEDIUM-HIGH' then sales else 0 end) as medium_high,
  sum(case when volume = 'LOW' then sales else 0 end) as low,
  sum(case when volume = 'VERY LOW' then sales else 0 end) as very_low,
  sum(sales) as total
from t
group by rollup (velocity)
order by velocity
</code>```

Body:
You can perform conditional aggregation and then use a ROLLUP.

For example:

select
  velocity,
  sum(case when volume = 'VERY HIGH' then sales else 0 end) as very_high,
  sum(case when volume = 'HIGH' then sales else 0 end) as high,
  sum(case when volume = 'MEDIUM-HIGH' then sales else 0 end) as medium_high,
  sum(case when volume = 'LOW' then sales else 0 end) as low,
  sum(case when volume = 'VERY LOW' then sales else 0 end) as very_low,
  sum(sales) as total
from t
group by rollup (velocity)
order by velocity


问:
How would you solve this tricky SQL problem?
Say you have a table layout like the following:

couses:

```<code>id (INT),
courseName (VARCHAR)
</code>```

instructors:

```<code>id (INT),
courseId(INT),
instructor(VARCHAR)
</code>```

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

```
    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee
```

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

答:
Yes, yes, business logic, etc.  It's a game, not your boss asking you to do it.

In T-SQL:

```<code> select
    id
     , courseName
     , case (select count(*) from instructors i where i.courseid=c.courseid)
         when 0 then 'No Instructor'
         when 1 then (select top 1 instructor from instructors where i.courseid=c.courseid)
         when 2 then (select top 1 instructor from instructors where i.courseid=c.courseid order by instructor desc)
         else 'Committee'
         end as instructor_1
     , case (select count(*) from instructors i where i.courseid=c.courseid)
         when 2 then (select top 1 instructor from instructors where i.courseid=c.courseid order by instructor asc)
         else ''
         end as instructor_2
 from courses c
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
Say you have a table layout like the following:

couses:

id (INT),
courseName (VARCHAR)

instructors:

id (INT),
courseId(INT),
instructor(VARCHAR)

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

Body:
Yes, yes, business logic, etc.  It's a game, not your boss asking you to do it.

In T-SQL:

 select
    id
     , courseName
     , case (select count(*) from instructors i where i.courseid=c.courseid)
         when 0 then 'No Instructor'
         when 1 then (select top 1 instructor from instructors where i.courseid=c.courseid)
         when 2 then (select top 1 instructor from instructors where i.courseid=c.courseid order by instructor desc)
         else 'Committee'
         end as instructor_1
     , case (select count(*) from instructors i where i.courseid=c.courseid)
         when 2 then (select top 1 instructor from instructors where i.courseid=c.courseid order by instructor asc)
         else ''
         end as instructor_2
 from courses c

OwnerDisplayName: Tom Ritter


问:
How does YUI tell web inspector / dev tools the type of an object?
So I recently noticed that when I console.log a YUI node and inspect its _node attribute, that object has fields like "childNodes: NodeList" where NodeList is just a JS object. How does YUI provide meta-information so that web inspector knows that this object is actually a NodeList?

It may be extremely useful for debugging to be able to provide meta type information for object blobs.

Thanks

答:
There is no meta-data.  NodeList is the name of the class, and debuggers can see what class every object belongs to.  In your example, somewhere a NodeList was created by calling

```<code>new NodeList();
</code>```

and the engine remembers that type information.

Body:
There is no meta-data.  NodeList is the name of the class, and debuggers can see what class every object belongs to.  In your example, somewhere a NodeList was created by calling

new NodeList();

and the engine remembers that type information.


问:
why does 'netsh wlan show profiles' return non-zero exit status 1
I read how to fix this error on the Internet and tried to figure it out myself, but it didn't work out, can you please help

```<code>import subprocess

def extract_wifi_password():
    profiles_data = subprocess.check_output('netsh wlan show profiles').decode('utf-8').split('\n')

    profiles = [i.split(':')[1].strip() for i in profiles_data if 'All User Profile' in i]

    for profile in profiles:
        profile_info = subprocess.check_output(f'netsh wlan show profile {profile} key=clear').decode('utf-8').split('\n')
        try:
            password = [i.split(':')[1].strip() for i in profile_info if 'Key Content' in i][0]
        except IndexError:
            password = None

        with open(file='wifi_password.ixi', mode='a', encoding='utf-8') as file:
            file.write(f'Profiles: {profile}\nPassword: {password}\n{"#" * 20}\n')
</code>```

and return subprocess.CalledProcessError: Command 'netsh wlan show profiles' returned non-zero exit status 1.

答:
You are not passing the arguments to subprocess.check_output correctly. You either need to pass shell=True, or you should pass a list or tuple of strings (e.g. ['netsh', 'wlan', 'show', 'profile']) instead of one long string.

The error you're getting is because there is no single command 'netsh wlan show profiles'. The program you want to run is netsh and the rest of the line is arguments to that command.

Body:
I read how to fix this error on the Internet and tried to figure it out myself, but it didn't work out, can you please help

import subprocess

def extract_wifi_password():
    profiles_data = subprocess.check_output('netsh wlan show profiles').decode('utf-8').split('\n')

    profiles = [i.split(':')[1].strip() for i in profiles_data if 'All User Profile' in i]

    for profile in profiles:
        profile_info = subprocess.check_output(f'netsh wlan show profile {profile} key=clear').decode('utf-8').split('\n')
        try:
            password = [i.split(':')[1].strip() for i in profile_info if 'Key Content' in i][0]
        except IndexError:
            password = None

        with open(file='wifi_password.ixi', mode='a', encoding='utf-8') as file:
            file.write(f'Profiles: {profile}\nPassword: {password}\n{"#" * 20}\n')

and return subprocess.CalledProcessError: Command 'netsh wlan show profiles' returned non-zero exit status 1.


问:
iPython Notebook/Jupyter autosave failed
I am working in iPython 3/Jupyter running multiple kernels and servers. As such, i often forget to personally save things as I jump around a lot. The autosave has failed for the past 3 hours.
 The error says: "Last Checkpoint: 3 hours ago Autosave Failed!
I try to manually File>>Save and Checkpoint, and nothing changes. Help!
Next to my Python 2 kernel name, there is a yellow box that say forbidden instead of edit. It goes away when i click on it. I don't know if that has anything to do with the failure to save, but it doesn't change once clicked.</p>

答:
I had a jupyter notebook server with multiple open notebooks and only one specific notebook displayed the out of memory error. The other could be saved just fine.

I could trace the error down to a large altair plot where I've used alt.data_transformers.disable_max_rows(). I remove the according plot by commenting out the cell and rexecuted it. After that I was able so save the notebook.

Relevant Source:

https://altair-viz.github.io/user_guide/faq.html#why-does-altair-lead-to-such-extremely-large-notebooks

https://altair-viz.github.io/user_guide/faq.html#maxrowserror-how-can-i-plot-large-datasets


问:
How to update an item in an array of an object
I have a list of people, each with an id. I have to add a tag to a newly created array for a person with a certain id. The json object 'students' already exists and I am updating it using its useState setStudents method but it seems to be returning an unidentified object back. My plan was as follows:

Map through the previousStudents

If the id matches (the person who I'm adding a tag to), then add the tag. The if statement to add a tag is there because the 'tags' property doesn't initially exist, so I make it on the first tag add

If the id doesn't match, just return that student

```<code>const updateStudent = (tag, id) => {
    setStudents((prevStudents) => {
      prevStudents.map((student) => {
        if (student.id !== id) return student;
        if (student.tags) {
          student["tags"].push(tag);
        } else {
          student["tags"] = [tag];
        }
        return student;
      });
    });
};
</code>```

Sorry if my explanation was confusing but tldr: I'm just trying to add an item to an array of a specified object and it doesn't seem to be working.

答:
A "cleaner" approach would be something like this:

```<code>const updateStudent = (tag, id) => {

  // form a new students object
  let newStudents = students.map(student => {
    if(student.id === id) {
      student.tags? student.tags.push(tag) : student.tags = [tag];
    }
    return student;
  });

  setStudents(newStudents); // set the newly formed object to state
}
</code>```

It is better to separate the update logic from setting the state

Body:
I have a list of people, each with an id. I have to add a tag to a newly created array for a person with a certain id. The json object 'students' already exists and I am updating it using its useState setStudents method but it seems to be returning an unidentified object back. My plan was as follows:

Map through the previousStudents

If the id matches (the person who I'm adding a tag to), then add the tag. The if statement to add a tag is there because the 'tags' property doesn't initially exist, so I make it on the first tag add

If the id doesn't match, just return that student

const updateStudent = (tag, id) => {
    setStudents((prevStudents) => {
      prevStudents.map((student) => {
        if (student.id !== id) return student;
        if (student.tags) {
          student["tags"].push(tag);
        } else {
          student["tags"] = [tag];
        }
        return student;
      });
    });
};

Sorry if my explanation was confusing but tldr: I'm just trying to add an item to an array of a specified object and it doesn't seem to be working.

Body:
A "cleaner" approach would be something like this:

const updateStudent = (tag, id) => {

  // form a new students object
  let newStudents = students.map(student => {
    if(student.id === id) {
      student.tags? student.tags.push(tag) : student.tags = [tag];
    }
    return student;
  });

  setStudents(newStudents); // set the newly formed object to state
}

It is better to separate the update logic from setting the state


问:
Is there anyway to update values in a JSON file after a certain interval of time?
Let's say I have a json file with multiple values as such:

```<code>{
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
</code>```

Is there any way I can update each separate value in the file after a certain interval of time? For example, I can change the Google value from 5 to 6 then 7 and so on each minute.

答:
With time.sleep() you can do this. time.sleep() delays your code for the amount of seconds that you specify, decimals are allowed. If you put it in a different thread, you can execute code whilst this is happening. This is some code for the threaded version, but you can remove threading by just calling updatedict()

```<code>import json
from time import sleep
import threading

values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
def updatedict():
    while True:
        global values
        #incrementing values
        for value in values:
            values[value] += 1
        #Writing file
        with open("values.json","w+") as f:
            f.write(json.dumps(values))
        #Sleeping 1 minute
        sleep(60)
#Starting new thread
threading.Thread(target=updatedict).start()
#Any code you wish to run at the same time as the above function
</code>```

If you intend to run the script multiple times each incrementing onto what is already there, replace the existing values variable assignment with

```<code>try:
    with open("values.json") as f:
        values = json.load(f)
#If the file is not found, regenerates values
except FileNotFoundError:
    values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
</code>```

Body:
Let's say I have a json file with multiple values as such:

{
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}

Is there any way I can update each separate value in the file after a certain interval of time? For example, I can change the Google value from 5 to 6 then 7 and so on each minute.

Body:
With time.sleep() you can do this. time.sleep() delays your code for the amount of seconds that you specify, decimals are allowed. If you put it in a different thread, you can execute code whilst this is happening. This is some code for the threaded version, but you can remove threading by just calling updatedict()

import json
from time import sleep
import threading

values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
def updatedict():
    while True:
        global values
        #incrementing values
        for value in values:
            values[value] += 1
        #Writing file
        with open("values.json","w+") as f:
            f.write(json.dumps(values))
        #Sleeping 1 minute
        sleep(60)
#Starting new thread
threading.Thread(target=updatedict).start()
#Any code you wish to run at the same time as the above function

If you intend to run the script multiple times each incrementing onto what is already there, replace the existing values variable assignment with

try:
    with open("values.json") as f:
        values = json.load(f)
#If the file is not found, regenerates values
except FileNotFoundError:
    values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}


问:
Get the variable value of assigned class
im learning to make an organizational chart using class

```<code>class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

abcde = employee("Elon Musk", "CEO",1000000)
print(employee.self) --> error
</code>```

Basically what im trying to do is to get the "abcde" value, to use it on my other function..

is there anyway to get the name assigned to the object? in this case "abcde"

Recreating this post to clarify what im trying to do:

I simplified the complete code that i have here, but basically what im trying to do here is getting the assigned class name, in this case "abcde".

i understand that self.name will get me "elon musk:
self.title will get me "CEO"

but how do i get the "abcde"?

why do i need the abcde?
because i need to append the abcde to a list called

direct_report_list= []

to append the "abcde" inside this list, which i will use for this:

```<code>def __str__(self):

           otheremp_list = []

           print(self.title,” – “, self.name)

           print(“Direct Reports:”)

           for emp in self.direct_reports_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

           print(“other employees:”)

           for emp in otheremp_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*
</code>```

i need the "abcde" value so i can add this value into my list, which i use for the "emp" in str

答:
override the __str__method and return a string & to get each value use object + dot + the data which you want to access

```<code>class employee:

    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

    def __str__(self):
        return self.name + "-" + self.title + "-"+ str(self.salary)

abcde = employee("Elon Musk", "CEO",1000000)
print(abcde)

#to get each value

print(abcde.name)
print(abcde.title)
print(abcde.salary)
</code>```

Output:

```<code>$ python3 print.py
Elon Musk-CEO-1000000
Elon Musk
CEO
1000000
</code>```

Body:
im learning to make an organizational chart using class

class employee:
    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

abcde = employee("Elon Musk", "CEO",1000000)
print(employee.self) --> error

Basically what im trying to do is to get the "abcde" value, to use it on my other function..

is there anyway to get the name assigned to the object? in this case "abcde"

Recreating this post to clarify what im trying to do:

I simplified the complete code that i have here, but basically what im trying to do here is getting the assigned class name, in this case "abcde".

i understand that self.name will get me "elon musk:
self.title will get me "CEO"

but how do i get the "abcde"?

why do i need the abcde?
because i need to append the abcde to a list called

direct_report_list= []

to append the "abcde" inside this list, which i will use for this:

def __str__(self):

           otheremp_list = []

           print(self.title,” – “, self.name)

           print(“Direct Reports:”)

           for emp in self.direct_reports_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

           print(“other employees:”)

           for emp in otheremp_list:

                          print(emp.title,” – “,emp.name)

                          otheremp_list.append(emp.direct_reports_list)*

i need the "abcde" value so i can add this value into my list, which i use for the "emp" in str

Body:
override the __str__method and return a string & to get each value use object + dot + the data which you want to access

class employee:

    def __init__(self, name , title, salary):
        self.name = name
        self.title = title
        self.salary = salary

    def __str__(self):
        return self.name + "-" + self.title + "-"+ str(self.salary)

abcde = employee("Elon Musk", "CEO",1000000)
print(abcde)

#to get each value

print(abcde.name)
print(abcde.title)
print(abcde.salary)

Output:

$ python3 print.py
Elon Musk-CEO-1000000
Elon Musk
CEO
1000000


问:
get positions of true within array of booleans

So in this table,  Each row of the table contains sales data for a product (car, train, or plane) from January through July. Suppose you enter a month and a product into the worksheet. Write a formula that gives the total sales of that product during the given month.
so, in this case, I tried to use array functions in excel 2016, I tried to use the exact function to get positions of "car" in the product column, like this  =exact("car", product)  and by using ctrl shift enter we get values of true and false, now we want to find a position of true values and sum up its corresponding sales in a concrete month,
I am trying to use offset function and match function to find the position of the month but it's hard to find the multiple positions of the car. how can we solve it?

答:
In K3, enter formula :

```<code>=SUMIF(A:A,K1,INDEX(1:1,MATCH(K2,1:1,0)))
</code>```

Body:
In K3, enter formula :

=SUMIF(A:A,K1,INDEX(1:1,MATCH(K2,1:1,0)))


问:
How to copy a value from one column to a new column if column A > column B?
I am looking to create a new column called true_water_on in the dataframe trial_A.

```<code>  study_ID       randomisation            water_on           water_off
1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00
2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00
3        7 2021-01-03 10:00:00                <NA>                <NA>
4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00
</code>```

The conditions to populate it are as follows

If "water_on" date and time precedes the time and date in "randomisation" then the randomisation data and time for that row is copied across into "true_water_on". This occurs for study_ID 6 and 8; as demonstrated by

```<code>trial_A %>% mutate(TD_ran_waterstart = water_on - randomisation, units="mins")
</code>```

If "water_on" date and time occurs after the time and date in
"randomisation" then the water_on data for that row is copied across
into "water_drug_on"

If there is no data and time recorded in "water_on" then NA is
marked in "true_water_on"

Data

```<code>trial_A <-
  data.frame(study_ID=c(5, 6, 7, 8),
             randomisation=as.POSIXlt(c("2021-01-01 11:00", "2021-01-02 10:00",
                                        "2021-01-03 10:00", "2021-01-04 10:00")),
             water_on=as.POSIXlt(c("2021-01-01 13:00", "2021-01-02 09:00", NA,
                                   "2021-01-04 09:45")),
             water_off=as.POSIXlt(c("2021-01-01 18:00", "2021-01-02 18:00", NA,
                                    "2021-01-04 11:00")))
</code>```

Body:
I am looking to create a new column called true_water_on in the dataframe trial_A.

  study_ID       randomisation            water_on           water_off
1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00
2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00
3        7 2021-01-03 10:00:00                <NA>                <NA>
4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00

The conditions to populate it are as follows

If "water_on" date and time precedes the time and date in "randomisation" then the randomisation data and time for that row is copied across into "true_water_on". This occurs for study_ID 6 and 8; as demonstrated by

trial_A %>% mutate(TD_ran_waterstart = water_on - randomisation, units="mins")

If "water_on" date and time occurs after the time and date in
"randomisation" then the water_on data for that row is copied across
into "water_drug_on"

If there is no data and time recorded in "water_on" then NA is
marked in "true_water_on"

Data

trial_A <-
  data.frame(study_ID=c(5, 6, 7, 8),
             randomisation=as.POSIXlt(c("2021-01-01 11:00", "2021-01-02 10:00",
                                        "2021-01-03 10:00", "2021-01-04 10:00")),
             water_on=as.POSIXlt(c("2021-01-01 13:00", "2021-01-02 09:00", NA,
                                   "2021-01-04 09:45")),
             water_off=as.POSIXlt(c("2021-01-01 18:00", "2021-01-02 18:00", NA,
                                    "2021-01-04 11:00")))

Body:
As @IRTFM suggests this looks like a simple application of ifelse or case_when in dplyr.

library(dplyr)

trial_A %>%
  mutate(true_water_on = case_when(water_on < randomisation ~ randomisation,
                                   water_on > randomisation ~ water_on))

#  study_ID       randomisation            water_on           water_off       true_water_on
#1        5 2021-01-01 11:00:00 2021-01-01 13:00:00 2021-01-01 18:00:00 2021-01-01 13:00:00
#2        6 2021-01-02 10:00:00 2021-01-02 09:00:00 2021-01-02 18:00:00 2021-01-02 10:00:00
#3        7 2021-01-03 10:00:00                <NA>                <NA>                <NA>
#4        8 2021-01-04 10:00:00 2021-01-04 09:45:00 2021-01-04 11:00:00 2021-01-04 10:00:00

In case_when if none of the conditions match it returns NA by default.


问:
Trying to center text vertically and horizontally next to an image
https://github.com/Yankysamurai/Personal-Website-P5

I am new to posting questions but I am trying to center my text "Welcome to my site" horizontally and vertically. I want it half the distance from the image and from the right margin. I tried display flex but it didn't work.

I just opened a git hub account so I hope you can see the code from the link.

Thank you.

答:
you can use the following ways to center elements in a block:

```<code>display: flex;
flex-direction: row;
justify-content: center
</code>```

or

```<code>display: flex;
flex-direction: column;
align-items: center
</code>```

Body:
you can use the following ways to center elements in a block:

display: flex;
flex-direction: row;
justify-content: center

or

display: flex;
flex-direction: column;
align-items: center