问:
LINQ query on entities with join returning items by category
I'm using Entity Framework core. I have the following entities:

```<code>public class Category {
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Product {
    public long Id { get; set; }
    public long CategoryId { get; set; }
    public string Name { get; set; }
}
</code>```

I'd like to get a grouping whereby my key is my Category and I have a list of Products. I'd like to do this running a single query against the DB.

```<code>var data = context.Categories
            .Join(
                Products,
                c => c.Id,
                p => p.CategoryId,
                (c, p) => new {
                   Category = c,
                   Product = p
               }
            )
            .ToList();
</code>```

This runs the query I want and seems to produce a list with an anonymous object that has a Category and Product. If I then do the following, it kind of does what I want:

```<code>var grouped = data.GroupBy(x => new { x.Category });
</code>```

The Key is fine, but the list of values seems to repeat the Categories. Is there a way to make it so I have a Key that's the Category and then the values is a list of Product objects? Would prefer method syntax, but at this point I can hopefully figure out query syntax if that's what somebody can get me.

答:
This is how I ended up solving it:</p>

```<code>var grouped = data
    .GroupBy(x => new { x.Category })
    .Select(x => new {
        Category = x.Key.Category,
        Products = x.ToList().Select(x => x.Product).ToList()
    });;
</code>```

Body:
I'm using Entity Framework core. I have the following entities:

public class Category {
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Product {
    public long Id { get; set; }
    public long CategoryId { get; set; }
    public string Name { get; set; }
}

I'd like to get a grouping whereby my key is my Category and I have a list of Products. I'd like to do this running a single query against the DB.

var data = context.Categories
            .Join(
                Products,
                c => c.Id,
                p => p.CategoryId,
                (c, p) => new {
                   Category = c,
                   Product = p
               }
            )
            .ToList();

This runs the query I want and seems to produce a list with an anonymous object that has a Category and Product. If I then do the following, it kind of does what I want:

var grouped = data.GroupBy(x => new { x.Category });

The Key is fine, but the list of values seems to repeat the Categories. Is there a way to make it so I have a Key that's the Category and then the values is a list of Product objects? Would prefer method syntax, but at this point I can hopefully figure out query syntax if that's what somebody can get me.

Body:
This is how I ended up solving it:

var grouped = data
    .GroupBy(x => new { x.Category })
    .Select(x => new {
        Category = x.Key.Category,
        Products = x.ToList().Select(x => x.Product).ToList()
    });;


来源: stackexchange

问:
Accessing data in SVHN dataset in python
I tried to extract data from tar.gz file which contains digitStruct.mat file.
I used the following code snippet:

```<code>train_dataset = h5py.File('./train/digitStruct.mat')
</code>```

I want to access the bbox and name details from this object itself.
for eg:

```<code>train_dataset[0]
</code>```

Should output something like:

```<code>{'boxes': [{'height': 219.0,
'label': 1.0,
'left': 246.0,
'top': 77.0,
'width': 81.0},
{'height': 219.0, 'label': 9.0, 'left': 323.0, 'top': 81.0, 'width': 96.0}],
 'filename': '1.png'}
</code>```

I searched for it and found the some help on this link:

h5py, access data in Datasets in SVHN

But the above link involves creating seperate functions get_box_data(index, hdf5_data) and get_name(index, hdf5_data) to retrieve value for the corresponding index.
However, I want access it directly from the variable name train_dataset[index].

答:
Ok, I think I found what I mentioned in the comments above.  It converts a SVHN HDF5 file in .mat v7.3 format into something simpler to work with. The file name is entered as dsFileName=. (I only had 6 test files to convert, so didn't add an input mechanism.) It takes a file named: yourfilename.mat and converts to yourfilename.h5. The second file is much easier to work with (and smaller and faster!). The new .h5 file has a dataset named digitStruct with the following records on each line:

name: String (file name, eg 1.png)

label: String with digit value (0-9)

left: image bounding box left

top: image bounding box top

width: image bounding box width

height: image bounding box height

Note: This calls code shared on github. URL and Attribution included in the source code below.

```<code>import h5py
import numpy as np
import os
import digitStruct
## Note digitStruct.py source found at:
## https://github.com/prijip/Py-Gsvhn-DigitStruct-Reader/blob/master/digitStruct.py

# Main
if __name__ == "__main__":

    dsFileName = 'Stanford/extra/digitStruct.mat'
    print ('Working on',os.path.split(dsFileName))

    print ('Create .h5 called',os.path.splitext(dsFileName)[0]+'.h5')
    h5f = h5py.File(os.path.splitext(dsFileName)[0]+'.h5', 'w')
    print ('Created',os.path.split(h5f.filename))

# Count number of images in digitStruct.mat file [/name] dataset
    mat_f = h5py.File(dsFileName)
    num_img = mat_f['/digitStruct/name'].size
    mat_f.close()

    ds_dtype = np.dtype ( [('name','S16'), ('label','S10'), ('left','f8'),
                            ('top','f8'), ('width','f8'), ('height','f8')] )
    ds_recarray = np.recarray ( (10,) , dtype=ds_dtype )
    ds_table = h5f.create_dataset('digitStruct', (2*num_img,), dtype=ds_dtype, maxshape=(None,) )

    idx_dtype = np.dtype ( [('name','S16'), ('first','i4'), ('length','i4')] )
##    idx_recarray = np.recarray ( (1,) , dtype=idx_dtype )
    idx_table = h5f.create_dataset('idx_digitStruct', (num_img,), dtype=idx_dtype, maxshape=(None,) )

    imgCounter = 0
    lblCounter = 0

    for dsObj in digitStruct.yieldNextDigitStruct(dsFileName):
        if (imgCounter % 1000 == 0) :
               print(dsObj.name)

        if (idx_table.shape[0] < imgCounter ) : # resize idx_table as needed
            idx_table.resize(idx_table.shape[0]+1000, axis=0)

        idx_table[imgCounter,'name'] = dsObj.name
        idx_table[imgCounter,'first'] = lblCounter
        idx_table[imgCounter,'length'] = len(dsObj.bboxList)

        raCounter = 0

        for bbox in dsObj.bboxList:

            ds_recarray[raCounter]['name'] = dsObj.name
            ds_recarray[raCounter]['label'] = bbox.label
            ds_recarray[raCounter]['left'] = bbox.left
            ds_recarray[raCounter]['top'] = bbox.top
            ds_recarray[raCounter]['width'] = bbox.width
            ds_recarray[raCounter]['height'] = bbox.height
            raCounter += 1
            lblCounter += 1

        if (ds_table.shape[0] < lblCounter ) :   # resize ds_table as needed
            ds_table.resize(ds_table.shape[0]+1000, axis=0)
        ds_table[lblCounter-raCounter:lblCounter] = ds_recarray[0:raCounter]

        imgCounter += 1

##        if imgCounter >= 2000:
##            break

    print ('Total images processed:', imgCounter )
    print ('Total labels processed:', lblCounter )

    ds_table.resize(lblCounter, axis=0)
    idx_table.resize(imgCounter, axis=0)

    h5f.close()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to extract data from tar.gz file which contains digitStruct.mat file.
I used the following code snippet:

train_dataset = h5py.File('./train/digitStruct.mat')

I want to access the bbox and name details from this object itself.
for eg:

train_dataset[0]

Should output something like:

{'boxes': [{'height': 219.0,
'label': 1.0,
'left': 246.0,
'top': 77.0,
'width': 81.0},
{'height': 219.0, 'label': 9.0, 'left': 323.0, 'top': 81.0, 'width': 96.0}],
 'filename': '1.png'}

I searched for it and found the some help on this link:

h5py, access data in Datasets in SVHN

But the above link involves creating seperate functions get_box_data(index, hdf5_data) and get_name(index, hdf5_data) to retrieve value for the corresponding index.
However, I want access it directly from the variable name train_dataset[index].

Body:
Ok, I think I found what I mentioned in the comments above.  It converts a SVHN HDF5 file in .mat v7.3 format into something simpler to work with. The file name is entered as dsFileName=. (I only had 6 test files to convert, so didn't add an input mechanism.) It takes a file named: yourfilename.mat and converts to yourfilename.h5. The second file is much easier to work with (and smaller and faster!). The new .h5 file has a dataset named digitStruct with the following records on each line:

name: String (file name, eg 1.png)

label: String with digit value (0-9)

left: image bounding box left

top: image bounding box top

width: image bounding box width

height: image bounding box height

Note: This calls code shared on github. URL and Attribution included in the source code below.

import h5py
import numpy as np
import os
import digitStruct
## Note digitStruct.py source found at:
## https://github.com/prijip/Py-Gsvhn-DigitStruct-Reader/blob/master/digitStruct.py

# Main
if __name__ == "__main__":

    dsFileName = 'Stanford/extra/digitStruct.mat'
    print ('Working on',os.path.split(dsFileName))

    print ('Create .h5 called',os.path.splitext(dsFileName)[0]+'.h5')
    h5f = h5py.File(os.path.splitext(dsFileName)[0]+'.h5', 'w')
    print ('Created',os.path.split(h5f.filename))

# Count number of images in digitStruct.mat file [/name] dataset
    mat_f = h5py.File(dsFileName)
    num_img = mat_f['/digitStruct/name'].size
    mat_f.close()

    ds_dtype = np.dtype ( [('name','S16'), ('label','S10'), ('left','f8'),
                            ('top','f8'), ('width','f8'), ('height','f8')] )
    ds_recarray = np.recarray ( (10,) , dtype=ds_dtype )
    ds_table = h5f.create_dataset('digitStruct', (2*num_img,), dtype=ds_dtype, maxshape=(None,) )

    idx_dtype = np.dtype ( [('name','S16'), ('first','i4'), ('length','i4')] )
##    idx_recarray = np.recarray ( (1,) , dtype=idx_dtype )
    idx_table = h5f.create_dataset('idx_digitStruct', (num_img,), dtype=idx_dtype, maxshape=(None,) )

    imgCounter = 0
    lblCounter = 0

    for dsObj in digitStruct.yieldNextDigitStruct(dsFileName):
        if (imgCounter % 1000 == 0) :
               print(dsObj.name)

        if (idx_table.shape[0] < imgCounter ) : # resize idx_table as needed
            idx_table.resize(idx_table.shape[0]+1000, axis=0)

        idx_table[imgCounter,'name'] = dsObj.name
        idx_table[imgCounter,'first'] = lblCounter
        idx_table[imgCounter,'length'] = len(dsObj.bboxList)

        raCounter = 0

        for bbox in dsObj.bboxList:

            ds_recarray[raCounter]['name'] = dsObj.name
            ds_recarray[raCounter]['label'] = bbox.label
            ds_recarray[raCounter]['left'] = bbox.left
            ds_recarray[raCounter]['top'] = bbox.top
            ds_recarray[raCounter]['width'] = bbox.width
            ds_recarray[raCounter]['height'] = bbox.height
            raCounter += 1
            lblCounter += 1

        if (ds_table.shape[0] < lblCounter ) :   # resize ds_table as needed
            ds_table.resize(ds_table.shape[0]+1000, axis=0)
        ds_table[lblCounter-raCounter:lblCounter] = ds_recarray[0:raCounter]

        imgCounter += 1

##        if imgCounter >= 2000:
##            break

    print ('Total images processed:', imgCounter )
    print ('Total labels processed:', lblCounter )

    ds_table.resize(lblCounter, axis=0)
    idx_table.resize(imgCounter, axis=0)

    h5f.close()


问:
Reasons not to build your own bug tracking system
Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.

The arguments I've heard in favous are usually along the lines of :

Wanting to 'eat our own dog food' in terms of some internally built web framework

Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way

Believing that it isn't difficult to build a bug tracking system

What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?

答:
The most basic argument for me would be the time loss. I doubt it could be completed in less than a month or two. Why spend the time when there are soooo many good bug tracking systems available? Give me an example of a feature that you have to tweak and is not readily available.

I think a good bug tracking system has to reflect your development process. A very custom development process is inherently bad for a company/team. Most agile practices favor Scrum or these kinds of things, and most bug tracking systems are in line with such suggestions and methods. Don't get too bureaucratic about this.

OwnerDisplayName: Matt Sheppard

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Constantin

OwnerDisplayName: Slavo

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Slavo


问:
How to access session variables from any class in ASP.NET?
I have created a class file in the App_Code folder in my application. I have a session variable

```<code>Session["loginId"]
</code>```

I want to access this session variables in my class, but when I am writing the following line then it gives error

```<code>Session["loginId"]
</code>```

Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)

答:
(Updated for completeness)

You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...

I always use a wrapper class around the ASP.NET session to simplify access to session variables:

```<code>public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}
</code>```

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

```<code>int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
</code>```

This approach has several advantages:

it saves you from a lot of type-casting

you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]

you can document your session items by adding XML doc comments on the properties of MySession

you can initialize your session variables with default values (e.g. assuring they are not null)

OwnerDisplayName: Prashant

Body:
I have created a class file in the App_Code folder in my application. I have a session variable

Session["loginId"]

I want to access this session variables in my class, but when I am writing the following line then it gives error

Session["loginId"]

Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)

LastEditorDisplayName: Martin

Body:
(Updated for completeness)

You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...

I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

it saves you from a lot of type-casting

you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]

you can document your session items by adding XML doc comments on the properties of MySession

you can initialize your session variables with default values (e.g. assuring they are not null)

OwnerDisplayName: Martin


问:
How to execute HTML code after user submit
I want the user to load Movie.swf size of their choice. I have two input boxes, one for width and one for the height. How can I execute the object with the size the user submitted?

I can't figure out how to make this work.

//Let the user set the size for Movie.swf
Width

<input type="text" id="objW">

Height

<input type="text" id="objH">

//Movie.swf will load with a new size from the input box
<input type="submit" value="Execute">

//Execute this line when submit
<object width="" height="" data="/Movie.swf"></object>
```

答:
You need to add javascript code for this part unless you are already using a framework. Also you should wrap the inputs inside a form tag and add an on submit eventlistener.

In current situation, following code should work:

const objW = document.getElementById('objW');
const objH = document.getElementById('objH');
const submitInput = document.querySelector('input[type=submit]');
const body = document.getElementsByTagName('body')[0];
submitInput.addEventListener('click', e => {
  e.preventDefault();

  /*if you want to display the object element after clicking input submit and replace all input fields*/
  body.innerHTML = `<object width="${objW.value}" height="${objH.value}" data="/Movie.swf"></object>`;

  /*or you can use following code if you always have object element in your html*/
  const object = document.getElementsByTagName('object')[0];
  object.setAttribute("height", objH.value);
  object.setAttribute("width", objW.value);

});
```


问:
revert GIT HEAD to older commit
I have realized that I have committed stuff into my branch that's bad and I want to revert to an earlier commit. I have confirmed that git checkout 8dd018c brings me to an earlier commit to which I want to revert HEAD to now, I  tried the following:

```<code>git checkout 8dd018c
git status
HEAD detached at 8dd018c
nothing to commit, working directory clean
git reset --hard  8dd018c
git push origin HEAD:<my_branch>
</code>```

but got:

```<code> ! [rejected]        HEAD -> my_branch (non-fast-forward)
error: failed to push some refs to 'https://github.com/my/repository.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

How do I do this correctly? I'm not the only one working on this repository so I think push -f is out of the question, is it?

答:
so I think push -f is out of the question, is it?

It doesn't matter whether it's out of the question. It is impossible to do what you're trying to do without using force, because you are asking the remote to throw away its references to all the commits after 8dd018c, and it will not do that willingly.

However, take comfort, because:

No one else depends on this branch; it's yours.

You can push --force-with-lease, which means, "Please do as I'm telling you to do, but only as long as it is safe" (safe in the sense that no one else has pushed to your branch, which, as it is yours, is pretty well guaranteed).

You could solve the whole problem with no force, just by giving up on this branch entirely. After all, it is only a name. So start a new branch with a different name at 8dd018c, and push that branch. The remote will happily let you do that. Of course, you would also like to delete the old branch, and again, that will require you to use force in one form or another.

You could solve the whole problem with no force, with a revert commit. Instead of removing commits, you add a new commit that makes your code go backwards to the same state it was when you were at 8dd018c. I think that's my favorite solution, actually. Sure, the bad code stays in the commits you already pushed, but who cares? People do make mistakes.

Basically, if you're going to push a branch to a shared remote, you're going to run into this sort of issue and you need to reconcile yourself to it. I personally am very fond of rewriting my branch's history before I push it, and that means I don't want to push it until I'm well and truly finished with it. If I'm concerned that my computer might be hit by a bus, I can make a backup, or I can even add a second remote and push the branch to that instead. Other folks are more cavalier about pushing their branch to the shared remote and changing its history with force. This is the kind of thing you should talk over with your team.

Title: revert GIT HEAD to older commit

Body:
I have realized that I have committed stuff into my branch that's bad and I want to revert to an earlier commit. I have confirmed that git checkout 8dd018c brings me to an earlier commit to which I want to revert HEAD to now, I  tried the following:

git checkout 8dd018c
git status
HEAD detached at 8dd018c
nothing to commit, working directory clean
git reset --hard  8dd018c
git push origin HEAD:<my_branch>

but got:

 ! [rejected]        HEAD -> my_branch (non-fast-forward)
error: failed to push some refs to 'https://github.com/my/repository.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

How do I do this correctly? I'm not the only one working on this repository so I think push -f is out of the question, is it?


问:
null is getting converted to "null" in Angular 5 HTTP get request
I am currently working on migrating our application from Angular 4 to Angular 5. In Angular 5 when we sending an object model as parameters and if one of the values has null then it is getting converted to "null" string. This is causing issues for us. The following is the way the parameters are being set:

```<code>options = {
                headers: header, params: Object.getOwnPropertyNames(jsonParamObject)
                    .reduce((p, key) => p.set(key, jsonParamObject[key]), new HttpParams())
            };
</code>```

In the above code we are using 'jsonParamObject' which is sent by the caller of this method. This object would have any number of values. So if the object has one of the value as null and when we are making an http request the value null is getting converted to "null" string. Could you please let me know how this can avoided or if there is any alternative.One of the alternatives would be to use "0" instead of null but that would require a lot of code changes in our application so I was looking for an easier/better approach.

答:
I ran into the same issue where i was trying to pass a string from the client side. it always got converted to "null" when i passed a null string.

Instead of passing the null string, i pass an empty string ("") which worked.

Body:
I am currently working on migrating our application from Angular 4 to Angular 5. In Angular 5 when we sending an object model as parameters and if one of the values has null then it is getting converted to "null" string. This is causing issues for us. The following is the way the parameters are being set:

options = {
                headers: header, params: Object.getOwnPropertyNames(jsonParamObject)
                    .reduce((p, key) => p.set(key, jsonParamObject[key]), new HttpParams())
            };

In the above code we are using 'jsonParamObject' which is sent by the caller of this method. This object would have any number of values. So if the object has one of the value as null and when we are making an http request the value null is getting converted to "null" string. Could you please let me know how this can avoided or if there is any alternative.One of the alternatives would be to use "0" instead of null but that would require a lot of code changes in our application so I was looking for an easier/better approach.


问:
discord.py get member instance from name#discriminator
I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)

I tried with:

```<code>@client.command()
async def mention(ctx):
    user : discord.Member = 'somename#1111'
    await ctx.send(f"{user.mention} hello!")
</code>```

But it doesn't work

答:
Although this method is valid, I'd recommend switching to saving user IDs instead of usernames + discriminators, as user IDs are constant, but users are able to change their names and discriminators.

@client.command()
async def mention(ctx):
    user = discord.utils.get(ctx.guild.members, name="somename", discriminator="1111")
    await ctx.send(f"{user.mention} hello!")
```

<p>And with the ID:</p>

<pre class="lang-py prettyprint-override"><code>@client.command()
async def mention(ctx):
    user = ctx.guild.get_member(112233445566778899) # replace user ID there
    try:
        await ctx.send(f"{user.mention} hello!")
    except:
        await ctx.send("Sorry, that user has left the server!")
</code>```

References:

utils.get()

User.discriminator

Guild.get_member()

Guild.get_member_named() - "Returns the first member found that matches the name provided."

Body:
I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)

I tried with:

@client.command()
async def mention(ctx):
    user : discord.Member = 'somename#1111'
    await ctx.send(f"{user.mention} hello!")

But it doesn't work

Body:
Although this method is valid, I'd recommend switching to saving user IDs instead of usernames + discriminators, as user IDs are constant, but users are able to change their names and discriminators.

@client.command()
async def mention(ctx):
    user = discord.utils.get(ctx.guild.members, name="somename", discriminator="1111")
    await ctx.send(f"{user.mention} hello!")

And with the ID:

@client.command()
async def mention(ctx):
    user = ctx.guild.get_member(112233445566778899) # replace user ID there
    try:
        await ctx.send(f"{user.mention} hello!")
    except:
        await ctx.send("Sorry, that user has left the server!")

References:

utils.get()

User.discriminator

Guild.get_member()

Guild.get_member_named() - "Returns the first member found that matches the name provided."


问:
passing a tuple as variable
I am passing a tuple by argument, i get the following error.
I searched on the internet and the working method was correct. Can someone have a look?

Person class

```<code>from datetime import datetime
from sqldata import Sqldata

class Person:
    def __init__(self, addr, client):
        self.addr = "192.12"
        self.client = "demorun"
        self.name = none

    def set_name(self, name):
        self.name = name
        values = (self.addr, self.name, str(datetime.now()))
        Sqldata.create_connclient(values)
</code>```

Sqldata class to write data to the database,

```<code>import sqlite3
from sqlite3 import Error
import os

fileDir = os.path.dirname(os.path.realpath(__file__))
filename = "dbConnClients.db"
db_file = os.path.join(fileDir,  "database\\" + filename)

class Sqldata:
    def __init__(self):
        self.conn = None
        try:
            self.conn = sqlite3.connect(db_file)
        except Error as e:
            print(e)

    def create_connclient(self, vdata):
        print(vdata)
        conn = self.conn
        sqlquery = ''' SELECT id FROM ConnClients WHERE name = ? '''
        cur = conn.cursor()
        cur.execute(sqlquery, vdata[1])
</code>```

Error:

```<code>File "...person.py", line 23, in set_name
    Sqldata.create_connclient(vdata)
TypeError: create_connclient() missing 1 required positional argument: 'vdata'
</code>```

答:
If you want to pass the two values in the tuple as the two arguments self and vdata, you should write it like this.

```<code>Sqldata.create_connclient(*values)
</code>```

The asterisk unpacks the tuple. However, please read justahuman's response, since I think they may have spotted a deeper issue.

Title: passing a tuple as variable

Body:
I am passing a tuple by argument, i get the following error.
I searched on the internet and the working method was correct. Can someone have a look?

Person class

from datetime import datetime
from sqldata import Sqldata

class Person:
    def __init__(self, addr, client):
        self.addr = "192.12"
        self.client = "demorun"
        self.name = none

    def set_name(self, name):
        self.name = name
        values = (self.addr, self.name, str(datetime.now()))
        Sqldata.create_connclient(values)

Sqldata class to write data to the database,

import sqlite3
from sqlite3 import Error
import os

fileDir = os.path.dirname(os.path.realpath(__file__))
filename = "dbConnClients.db"
db_file = os.path.join(fileDir,  "database\\" + filename)

class Sqldata:
    def __init__(self):
        self.conn = None
        try:
            self.conn = sqlite3.connect(db_file)
        except Error as e:
            print(e)

    def create_connclient(self, vdata):
        print(vdata)
        conn = self.conn
        sqlquery = ''' SELECT id FROM ConnClients WHERE name = ? '''
        cur = conn.cursor()
        cur.execute(sqlquery, vdata[1])

Error:

File "...person.py", line 23, in set_name
    Sqldata.create_connclient(vdata)
TypeError: create_connclient() missing 1 required positional argument: 'vdata'

Body:
If you want to pass the two values in the tuple as the two arguments self and vdata, you should write it like this.

Sqldata.create_connclient(*values)

The asterisk unpacks the tuple. However, please read justahuman's response, since I think they may have spotted a deeper issue.


问:
See if Dictionary Item is the last one in the dictionary
Given the code ..

```<code>var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});
</code>```

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

```<code>bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;
</code>```

but that did not work...

答: You could test if value ==  dictionary.Values.Last();</p>

Body:
Given the code ..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

but that did not work...


问:
Change font color based on variable wont work
I want the font color of the tekst in my table changed based on a value stored in my sql database. I have a variable that gets the color hex from an other sql table. It works for the background but it wont work for the font color.

This is what works.

<td bgcolor="#<?= $cat_color ?> "><?= $rij->cat_color ?>

This is what i tried

<td color="#<?= $cat_color ?> "><?= $rij->cat_color ?>

The color of the font i not changing. please help, besides this i have tried many things..

答:
color is not an allowed attribute of td. Use style="color:#cc0000" instead.

example:

```<code><td style="color:#<?= $cat_color ?>;">test 2</td>
</code>```

maybe you should consider to use a dynamic class name. but it depends of the general code context of your project.

Body:
color is not an allowed attribute of td. Use style="color:#cc0000" instead.

example:

<td style="color:#<?= $cat_color ?>;">test 2</td>

maybe you should consider to use a dynamic class name. but it depends of the general code context of your project.


问:
Symfony and doctrine issues
I did not use the sudo when installing doctrine in symfony
So this is what i got..

```<code>The "https://flex.symfony.com/aliases.json" file could not be downloaded: failed to open stream: Connection refused https://flex.symfony.com/aliases.json could not be fully loaded, package information was loaded from the local cache and may be out of date
to fix that i did this curl -XGET https://flex.symfony.com/aliases.json
</code>```

and then i installed composer require symfony/orm-pack composer require --dev symfony/maker-bundle

The problem is that it wont add any db config in the env file....
and when i do the composer require doctrine
i get this

```<code>Pontuss-MacBook-Air:cauldron_overflow Pontus$ composer require doctrine
Using version ^1.0 for symfony/orm-pack
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.4.*"
Nothing to install or update
Package zendframework/zend-code is abandoned, you should avoid using it. Use laminas/laminas-code instead.
Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.
Generating autoload files
34 packages you are using are looking for funding.
Use thecomposer fundcommand to find out more!
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [OK]
Executing script assets:install public [OK]
Executing script security-checker security:check [OK]
</code>```

So why wont it add the correct data to my env files?
Please any advice

答: I solved the issue by removing doctrine and reinstall the package :) and now the env file looks like it should :)</p>

Title: Symfony and doctrine issues

Body:
I did not use the sudo when installing doctrine in symfony
So this is what i got..

The "https://flex.symfony.com/aliases.json" file could not be downloaded: failed to open stream: Connection refused https://flex.symfony.com/aliases.json could not be fully loaded, package information was loaded from the local cache and may be out of date
to fix that i did this curl -XGET https://flex.symfony.com/aliases.json

and then i installed composer require symfony/orm-pack composer require --dev symfony/maker-bundle

The problem is that it wont add any db config in the env file....
and when i do the composer require doctrine
i get this

Pontuss-MacBook-Air:cauldron_overflow Pontus$ composer require doctrine
Using version ^1.0 for symfony/orm-pack
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.4.*"
Nothing to install or update
Package zendframework/zend-code is abandoned, you should avoid using it. Use laminas/laminas-code instead.
Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.
Generating autoload files
34 packages you are using are looking for funding.
Use thecomposer fundcommand to find out more!
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [OK]
Executing script assets:install public [OK]
Executing script security-checker security:check [OK]

So why wont it add the correct data to my env files?
Please any advice


问:
Group by Date and sum the count
I'm trying to figure out this issue but unable to solve it.
I have an array of objects below and what I am trying to do is to group it by date and sum the count.

var arr = [
  {CaptureTime: "2020-05-19 10:00:00.0", Division: "PC    ", Count: "1"},
{CaptureTime: "2020-06-01 18:00:00.0", Division: "CONGSO", Count: "1"},
{CaptureTime: "2020-05-14 20:00:00.0", Division: "CUA5  ", Count: "9"},
{CaptureTime: "2020-05-28 14:00:00.0", Division: "HR    ", Count: "9"},
{CaptureTime: "2020-05-19 11:00:00.0", Division: "SERK  ", Count: "20"},
{CaptureTime: "2020-05-22 17:00:00.0", Division: "WWCBS ", Count: "5"},
{CaptureTime: "2020-05-13 08:00:00.0", Division: "ECEADM", Count: "3"},
{CaptureTime: "2020-05-27 09:00:00.0", Division: "BRIDGE", Count: "1"},
{CaptureTime: "2020-05-14 09:00:00.0", Division: "WFI   ", Count: "1"},
{CaptureTime: "2020-06-01 13:00:00.0", Division: null, Count: "156"},
{CaptureTime: "2020-05-20 16:00:00.0", Division: "BRIDGE", Count: "2"},
{CaptureTime: "2020-05-22 14:00:00.0", Division: "TQM   ", Count: "9"},
{CaptureTime: "2020-05-22 17:00:00.0", Division: "PHC   ", Count: "3"}
];```
</div>
</div>
</p>
<p>The expected output would be like below:</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>var output = [
 {2020-05-13: 3},
 {2020-05-14: 10},
 {2020-05-19: 21},
 {2020-05-20: 2},
 {2020-05-22: 17},
 {2020-05-27: 1},
 {2020-05-28: 9},
 {2020-06-01: 157}
];</code>```

Thanks.

答:
If you want to take a shorter route, you could evaluate the use of lodash.

The implementation would be something like:

```<code>var array = [
  {CaptureTime: "2020-05-19 10:00:00.0", Division: "PC    ", Count: "1"},
  {CaptureTime: "2020-06-01 18:00:00.0", Division: "CONGSO", Count: "1"},
  {CaptureTime: "2020-05-14 20:00:00.0", Division: "CUA5  ", Count: "9"},
  {CaptureTime: "2020-05-28 14:00:00.0", Division: "HR    ", Count: "9"},
  {CaptureTime: "2020-05-19 11:00:00.0", Division: "SERK  ", Count: "20"},
  {CaptureTime: "2020-05-22 17:00:00.0", Division: "WWCBS ", Count: "5"},
  {CaptureTime: "2020-05-13 08:00:00.0", Division: "ECEADM", Count: "3"},
  {CaptureTime: "2020-05-27 09:00:00.0", Division: "BRIDGE", Count: "1"},
  {CaptureTime: "2020-05-14 09:00:00.0", Division: "WFI   ", Count: "1"},
  {CaptureTime: "2020-06-01 13:00:00.0", Division: null, Count: "156"},
  {CaptureTime: "2020-05-20 16:00:00.0", Division: "BRIDGE", Count: "2"},
  {CaptureTime: "2020-05-22 14:00:00.0", Division: "TQM   ", Count: "9"},
  {CaptureTime: "2020-05-22 17:00:00.0", Division: "PHC   ", Count: "3"}
];

const groupedByCaptureTime = lodash.groupBy(array, 'CaptureTime');
const countResult = lodash.sumBy(arr, 'Count');
</code>```

I hope this has helped you.

Title: Group by Date and sum the count

Body:
I'm trying to figure out this issue but unable to solve it.
I have an array of objects below and what I am trying to do is to group it by date and sum the count.

var arr = [
  {CaptureTime: "2020-05-19 10:00:00.0", Division: "PC    ", Count: "1"},
{CaptureTime: "2020-06-01 18:00:00.0", Division: "CONGSO", Count: "1"},
{CaptureTime: "2020-05-14 20:00:00.0", Division: "CUA5  ", Count: "9"},
{CaptureTime: "2020-05-28 14:00:00.0", Division: "HR    ", Count: "9"},
{CaptureTime: "2020-05-19 11:00:00.0", Division: "SERK  ", Count: "20"},
{CaptureTime: "2020-05-22 17:00:00.0", Division: "WWCBS ", Count: "5"},
{CaptureTime: "2020-05-13 08:00:00.0", Division: "ECEADM", Count: "3"},
{CaptureTime: "2020-05-27 09:00:00.0", Division: "BRIDGE", Count: "1"},
{CaptureTime: "2020-05-14 09:00:00.0", Division: "WFI   ", Count: "1"},
{CaptureTime: "2020-06-01 13:00:00.0", Division: null, Count: "156"},
{CaptureTime: "2020-05-20 16:00:00.0", Division: "BRIDGE", Count: "2"},
{CaptureTime: "2020-05-22 14:00:00.0", Division: "TQM   ", Count: "9"},
{CaptureTime: "2020-05-22 17:00:00.0", Division: "PHC   ", Count: "3"}
];

The expected output would be like below:

var output = [
 {2020-05-13: 3},
 {2020-05-14: 10},
 {2020-05-19: 21},
 {2020-05-20: 2},
 {2020-05-22: 17},
 {2020-05-27: 1},
 {2020-05-28: 9},
 {2020-06-01: 157}
];

Thanks.

Body:
If you want to take a shorter route, you could evaluate the use of lodash.

The implementation would be something like:

var array = [
  {CaptureTime: "2020-05-19 10:00:00.0", Division: "PC    ", Count: "1"},
  {CaptureTime: "2020-06-01 18:00:00.0", Division: "CONGSO", Count: "1"},
  {CaptureTime: "2020-05-14 20:00:00.0", Division: "CUA5  ", Count: "9"},
  {CaptureTime: "2020-05-28 14:00:00.0", Division: "HR    ", Count: "9"},
  {CaptureTime: "2020-05-19 11:00:00.0", Division: "SERK  ", Count: "20"},
  {CaptureTime: "2020-05-22 17:00:00.0", Division: "WWCBS ", Count: "5"},
  {CaptureTime: "2020-05-13 08:00:00.0", Division: "ECEADM", Count: "3"},
  {CaptureTime: "2020-05-27 09:00:00.0", Division: "BRIDGE", Count: "1"},
  {CaptureTime: "2020-05-14 09:00:00.0", Division: "WFI   ", Count: "1"},
  {CaptureTime: "2020-06-01 13:00:00.0", Division: null, Count: "156"},
  {CaptureTime: "2020-05-20 16:00:00.0", Division: "BRIDGE", Count: "2"},
  {CaptureTime: "2020-05-22 14:00:00.0", Division: "TQM   ", Count: "9"},
  {CaptureTime: "2020-05-22 17:00:00.0", Division: "PHC   ", Count: "3"}
];

const groupedByCaptureTime = lodash.groupBy(array, 'CaptureTime');
const countResult = lodash.sumBy(arr, 'Count');

I hope this has helped you.


问:
Adding validation using mediatR pipeline behaviour
As part of pipeline behavior, tried to set validation while creating customer

```<code>    public class ValidationBehavoir<TRequest, TResponse> : IPipelineBehavior<TRequest, TRequest>
        where TRequest : IRequest<TResponse>
    {

        private readonly IEnumerable<IValidator<TRequest>> _validators;

        public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
        {
            _validators = validators;
        }
        public async Task<TRequest> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TRequest> next)
        {

            var context = new ValidationContext(request);
            var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

            if(failures.Any())
            {
                throw new ValidationException(failures);
            }

            return await next();
        }
    }
</code>```

Here are the services added while setting DI

```<code>            services.AddMediatR(typeof(Program));
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));
            services.AddMediatR(typeof(CreateCustomerCommand).GetTypeInfo().Assembly);
            services.AddMediatR(typeof(GetCustomersQuery).GetTypeInfo().Assembly);

But still, getting below error?
System.ArgumentException: Implementation type 'CustomerApis.PipelineBehaviors.ValidationBehavoir`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]' can't be converted to service type 'MediatR.IPipelineBehavior`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]'
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite..ctor(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
</code>```

Can someone please help me here?

答:
There may be some information missing from your side (the specific validators for each entity for example) However, I would move the services.AddTransient line below the others or I would try this instead of the lines you have:</p>

```<code>services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));
</code>```

Body:
As part of pipeline behavior, tried to set validation while creating customer

    public class ValidationBehavoir<TRequest, TResponse> : IPipelineBehavior<TRequest, TRequest>
        where TRequest : IRequest<TResponse>
    {

        private readonly IEnumerable<IValidator<TRequest>> _validators;

        public ValidationBehavoir(IEnumerable<IValidator<TRequest>> validators)
        {
            _validators = validators;
        }
        public async Task<TRequest> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TRequest> next)
        {

            var context = new ValidationContext(request);
            var failures = _validators.Select(x => x.Validate(context)).SelectMany(x => x.Errors).ToList();

            if(failures.Any())
            {
                throw new ValidationException(failures);
            }

            return await next();
        }
    }

Here are the services added while setting DI

            services.AddMediatR(typeof(Program));
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));
            services.AddMediatR(typeof(CreateCustomerCommand).GetTypeInfo().Assembly);
            services.AddMediatR(typeof(GetCustomersQuery).GetTypeInfo().Assembly);

But still, getting below error?
System.ArgumentException: Implementation type 'CustomerApis.PipelineBehaviors.ValidationBehavoir`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]' can't be converted to service type 'MediatR.IPipelineBehavior`2[Customers.Service.Command.CreateCustomerCommand,Customers.Domain.Entities.Customer]'
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite..ctor(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)

Can someone please help me here?

Body:
There may be some information missing from your side (the specific validators for each entity for example) However, I would move the services.AddTransient line below the others or I would try this instead of the lines you have:

services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavoir<,>));


问:
How do you remove a model from mongoose?
I don't mean remove a document or documents. I mean remove the model entirely so that mongoose is no longer aware of it. After declaring a model I can't figure out how to make mongoose forget that model so that it could be recreated.

```<code>mongoose.model('Book', bookSchema);
mongoose.model('Book', bookSchema);
</code>```

Currently the above throws an exception.

OverwriteModelError: Cannot overwrite 'Book' model once compiled.

I'd like to be able do something like this...

```<code>mongoose.model('Book', bookSchema);
mongoose.removeModel('Book');
mongoose.model('Book', bookSchema);
</code>```

...and not get any errors. Any ideas?

答:
This is actually a better way to get rid of models, schemas and collections in mongoose

mongoose.connections.forEach(connection => {
  const modelNames = Object.keys(connection.models)

  modelNames.forEach(modelName => {
    delete connection.models[modelName]
  })

  const collectionNames = Object.keys(connection.collections)
  collectionNames.forEach(collectionName => {
    delete connection.collections[collectionName]
  })
})

const modelSchemaNames = Object.keys(mongoose.modelSchemas)
modelSchemaNames.forEach(modelSchemaName => {
  delete mongoose.modelSchemas[modelSchemaName]
})
```

Reference: https://github.com/Automattic/mongoose/issues/2874#issuecomment-388588452

Body:
I don't mean remove a document or documents. I mean remove the model entirely so that mongoose is no longer aware of it. After declaring a model I can't figure out how to make mongoose forget that model so that it could be recreated.

mongoose.model('Book', bookSchema);
mongoose.model('Book', bookSchema);

Currently the above throws an exception.

OverwriteModelError: Cannot overwrite 'Book' model once compiled.

I'd like to be able do something like this...

mongoose.model('Book', bookSchema);
mongoose.removeModel('Book');
mongoose.model('Book', bookSchema);

...and not get any errors. Any ideas?

Body:
This is actually a better way to get rid of models, schemas and collections in mongoose

mongoose.connections.forEach(connection => {
  const modelNames = Object.keys(connection.models)

  modelNames.forEach(modelName => {
    delete connection.models[modelName]
  })

  const collectionNames = Object.keys(connection.collections)
  collectionNames.forEach(collectionName => {
    delete connection.collections[collectionName]
  })
})

const modelSchemaNames = Object.keys(mongoose.modelSchemas)
modelSchemaNames.forEach(modelSchemaName => {
  delete mongoose.modelSchemas[modelSchemaName]
})

Reference: https://github.com/Automattic/mongoose/issues/2874#issuecomment-388588452


问:
align-content not centering the div
I want to center the black div using the align-content center, but it is not getting centered.

.container{
    background-color:red;
    width:100%;
    height:300px;

    flex-wrap: wrap;
    align-content:center;
}

.flex{
    display: flex;
    width:30%;
    height:30px;
    background-color:black;
}
```

```

```

https://ibb.co/fXGb6j2

答:
You assigned the rules wrong. .container needs to have display: flex; not the child of the container. And it has to be justify-content: center; not align-content: center;.

justify-content: center; causes the horizontal center

align-items: center; causes the vertical center

.container {
  display: flex;
  width: 100%;
  height: 300px;
  justify-content: center;
  align-items: center;
  background-color: red;
}

.flex {
  width: 30%;
  height: 100px;
  background-color: black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="flex">I am centered!</div>
</div></code>```

Title: align-content not centering the div

Body:
I want to center the black div using the align-content center, but it is not getting centered.

.container{
    background-color:red;
    width:100%;
    height:300px;

    flex-wrap: wrap;
    align-content:center;
}

.flex{
    display: flex;
    width:30%;
    height:30px;
    background-color:black;
}

https://ibb.co/fXGb6j2

Body:
You assigned the rules wrong. .container needs to have display: flex; not the child of the container. And it has to be justify-content: center; not align-content: center;.

justify-content: center; causes the horizontal center

align-items: center; causes the vertical center

.container {
  display: flex;
  width: 100%;
  height: 300px;
  justify-content: center;
  align-items: center;
  background-color: red;
}

.flex {
  width: 30%;
  height: 100px;
  background-color: black;
  color: white;
}

<div class="container">
  <div class="flex">I am centered!</div>
</div>


问:
React native interval state not updating
interval function in state change not working help me please.

state not change

```<code>function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);

_stropeText = () => {
  if (marker == 0){
   setMarker(marker => 1);
  } else {
   setMarker(marker => 0);
  }
}

React.useEffect(() => {
    setLoading(true);
    const unsubscribe = navigation.addListener('focus', () => {
      setInterval(_stropeText, 500);
    });
    return () => {  };
  }, [navigation]);
}
</code>```

https://snack.expo.io/Hbedd4HVh

答:
You have a closure on marker value, add it to useEffect dependency array, or use a reference with useRef hook.

Also, you passing a callback to useState, it makes functional updates, which is not the case here.

```<code>function Home({ route, navigation }) {
  const [marker, setMarker] = useState(0);

  React.useEffect(() => {
    setLoading(true);
    const _stropeText = () => {
      if (marker === 0) {
        setMarker(1);
      } else {
        setMarker(0);
      }
    };
    const unsubscribe = navigation.addListener("focus", () => {
      setInterval(_stropeText, 500);
    });
    return () => {
      /*remove listener*/
    };
  }, [navigation, marker]);
}
</code>```

Body:
interval function in state change not working help me please.

state not change

function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);

_stropeText = () => {
  if (marker == 0){
   setMarker(marker => 1);
  } else {
   setMarker(marker => 0);
  }
}

React.useEffect(() => {
    setLoading(true);
    const unsubscribe = navigation.addListener('focus', () => {
      setInterval(_stropeText, 500);
    });
    return () => {  };
  }, [navigation]);
}

https://snack.expo.io/Hbedd4HVh

Body:
You have a closure on marker value, add it to useEffect dependency array, or use a reference with useRef hook.

Also, you passing a callback to useState, it makes functional updates, which is not the case here.

function Home({ route, navigation }) {
  const [marker, setMarker] = useState(0);

  React.useEffect(() => {
    setLoading(true);
    const _stropeText = () => {
      if (marker === 0) {
        setMarker(1);
      } else {
        setMarker(0);
      }
    };
    const unsubscribe = navigation.addListener("focus", () => {
      setInterval(_stropeText, 500);
    });
    return () => {
      /*remove listener*/
    };
  }, [navigation, marker]);
}


问:
Optimising c++ arrays and vectors
Im trying to opptimise this peice of code as its a small section of a longer code for speed rather than memory. How best would I do that. I was thinking to use set the v_vtx vector to be able to just to define the chitemp array.

```<code>double chitemp[nvert1][2];
for (int i=0;i<nvert1;i++){
  chitemp[i][1]=v_vtx[i];
  chitemp[i][0]=chi2->at(v_vtx[i]);
}
for (int k = 0; k < nvert1; k++){
  for( int p = k+1; p < nvert1; p++){
  if( chitemp[k][0] > chitemp[p][0]){
    swap(chitemp[k][0], chitemp[p][0]);
    swap(chitemp[k][1], chitemp[p][1]);
  }
 }
}
</code>```

edit:

Im trying to sort chi2 (double) into order and know which v_vtx (int) links to the chi2 value

答:
You could instead store your values as pairs (using std::array is optional, but offers a richer interface than an inbuilt array):

```<code>std::array<std::pair<double>, nvert1> chitemp;
for (size_t i = 0; i < nvert1; ++i) {
    chitemp[i].second = v_vtx[i];
    chitemp[i].first = chi2->at(v_vtx[i]);
}
</code>```

Then, use...

```<code>std::sort(chitemp.begin(), chitemp.end());
</code>```

...instead of your (inefficient) home-grown bubble-sort.

Title: Optimising c++ arrays and vectors

Body:
Im trying to opptimise this peice of code as its a small section of a longer code for speed rather than memory. How best would I do that. I was thinking to use set the v_vtx vector to be able to just to define the chitemp array.

double chitemp[nvert1][2];
for (int i=0;i<nvert1;i++){
  chitemp[i][1]=v_vtx[i];
  chitemp[i][0]=chi2->at(v_vtx[i]);
}
for (int k = 0; k < nvert1; k++){
  for( int p = k+1; p < nvert1; p++){
  if( chitemp[k][0] > chitemp[p][0]){
    swap(chitemp[k][0], chitemp[p][0]);
    swap(chitemp[k][1], chitemp[p][1]);
  }
 }
}

edit:

Im trying to sort chi2 (double) into order and know which v_vtx (int) links to the chi2 value

Body:
You could instead store your values as pairs (using std::array is optional, but offers a richer interface than an inbuilt array):

std::array<std::pair<double>, nvert1> chitemp;
for (size_t i = 0; i < nvert1; ++i) {
    chitemp[i].second = v_vtx[i];
    chitemp[i].first = chi2->at(v_vtx[i]);
}

Then, use...

std::sort(chitemp.begin(), chitemp.end());

...instead of your (inefficient) home-grown bubble-sort.


问:
How do I dynamically index a record with known types in TypeScript?
I am trying to dynamically index a record with a known type using a string which can possibly be typed too, below is all the relevant code including the error which shows up inside my reduce (acc[val]), I am having troubles understanding the error so I do not know how to fix it

interface CommandsPingDescription {
  type: string;
  props: never;
}
interface LocalizationMap {
  "commands.ping.description": CommandsPingDescription;
}
```

<pre class="lang-js prettyprint-override"><code>import base from "../locale/base.json";
import en from "../locale/en.json";

type Language = keyof typeof languages;

const languages: Record<"en", typeof base> = { en };

export const setLanguage = <T extends Language>(lang: T) => {
  return <
    K extends keyof LocalizationMap,
    V extends LocalizationMap[K]["props"]
  >(
    key: K,
    ...placeholders: V[]
  ) => {
    let translation = key
      .split(".")
      .reduce((acc, val) => acc[val], languages[lang]);
</code>```

```<code>(parameter) acc: Record<"en", {
    commands: {
        ping: {
            description: string;
        };
    };
}>[T]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ commands: { ping: { description: string; }; }; }'.
  No index signature with a parameter of type 'string' was found on type '{ commands: { ping: { description: string; }; }; }'.
</code>```

Playground link: https://www.typescriptlang.org/play/#code/MYewdgzgLgBARgQwgUxgXhgbwFAzzUAW0ITABMIAuLXfOgBwEswBzanOz-M5CYAJ0b0ojcNQBE42lwC+0mHLnZQkWMjDoadIiXJUtXGE1bt5hmDz6DhosBPEBuM-jl1F2bFACe9VABlSFgBXBBZUDABrZC8QADMYb184mAAbQJCwiCdlcGhU9NDeagAlZFB+MgAecXVxABoEn2RkxBQAPk1MGHUFbOQAD3oQflgVPJQoANYM8JhKgBVu-qh1Chgp4MK2gAo0kxh5gEp0Do58fmQoIP4NSuc8AGkllb0YKJj4vxBgBBTGAC8ECJwABZBD0Or3GAANWeqwg62+vwBQNsYPoAG0HgBdDHiej8ED0CDibHyHZQ97UB6Q8wAOgZ9DSwGQAAsQCkePx9NCMWS6Mc0KcoSlLgl+KQIGlgRpItEoXQ6RAmYwoNtxHTxIcFfg6RcyEEWdttghgMAGgA3X6Cjqm4AYq0pbENPabTIY13Yw5ONzYJTMFb8WKm1AAYRAxFIFAACswWAARXgCIQygyJZDUaCCVg+oyE4nUMDIC3IfhOOQB0vBlmIn5-QEy9EGcQ6KMQOnGFh0yzJmzgcTUcORvSx1iJqwp2zloA

答:
It seems like the meat of your code is here:

const key = "commands.ping.description";
const en = {
    commands: {
        ping: {
            description: "";
        }
    }
}
let translation = key
    .split(".")
    .reduce((acc, val) => acc[val], en);
```

<p>and what you want TypeScript to do is to figure out the type of <code>acc[val]</code> where
<code>val</code> is a substring of <code>key</code>. That's not going to happen; it's well beyond the limitations of string literal types, and for good reason.</p>

<p>What I recommend you do is loosen your types to something like this:</p>

<pre class="lang-js prettyprint-override"><code>const key = "commands.ping.description";
interface RecursiveRecord<T> {
    [key: string]: T | RecursiveRecord<T>;
}
const en: RecursiveRecord<string> = {
    commands: {
        ping: {
            description: "hello";
        }
    }
}

// go through the properties from key.split(".")
// and assign the string at the end to translation
let record = en;
let translation: string = "";
for (const substr of key.split(".")) {
    const oneLevelDeeper = record[substr];
    if (typeof oneLevelDeeper === "string") {
        translation = oneLevelDeeper
        break;
    } else {
        record = oneLevelDeeper;
    }
}
console.log(translation); // "hello"
</code>```

Body:
I am trying to dynamically index a record with a known type using a string which can possibly be typed too, below is all the relevant code including the error which shows up inside my reduce (acc[val]), I am having troubles understanding the error so I do not know how to fix it

interface CommandsPingDescription {
  type: string;
  props: never;
}
interface LocalizationMap {
  "commands.ping.description": CommandsPingDescription;
}

import base from "../locale/base.json";
import en from "../locale/en.json";

type Language = keyof typeof languages;

const languages: Record<"en", typeof base> = { en };

export const setLanguage = <T extends Language>(lang: T) => {
  return <
    K extends keyof LocalizationMap,
    V extends LocalizationMap[K]["props"]
  >(
    key: K,
    ...placeholders: V[]
  ) => {
    let translation = key
      .split(".")
      .reduce((acc, val) => acc[val], languages[lang]);

(parameter) acc: Record<"en", {
    commands: {
        ping: {
            description: string;
        };
    };
}>[T]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ commands: { ping: { description: string; }; }; }'.
  No index signature with a parameter of type 'string' was found on type '{ commands: { ping: { description: string; }; }; }'.

Playground link: <a href="https://www.typescriptlang.org/play/#code/MYewdgzgLgBARgQwgUxgXhgbwFAzzUAW0ITABMIAuLXfOgBwEswBzanOz-M5CYAJ0b0ojcNQBE42lwC+0mHLnZQkWMjDoadIiXJUtXGE1bt5hmDz6DhosBPEBuM-jl1F2bFACe9VABlSFgBXBBZUDABrZC8QADMYb184mAAbQJCwiCdlcGhU9NDeagAlZFB+MgAecXVxABoEn2RkxBQAPk1MGHUFbOQAD3oQflgVPJQoANYM8JhKgBVu-qh1Chgp4MK2gAo0kxh5gEp0Do58fmQoIP4NSuc8AGkllb0YKJj4vxBgBBTGAC8ECJwABZBD0Or3GAANWeqwg62+vwBQNsYPoAG0HgBdDHiej8ED0CDibHyHZQ97UB6Q8wAOgZ9DSwGQAAsQCkePx9NCMWS6Mc0KcoSlLgl+KQIGlgRpItEoXQ6RAmYwoNtxHTxIcFfg6RcyEEWdttghgMAGgA3X6Cjqm4AYq0pbENPabTIY13Yw5ONzYJTMFb8WKm1AAYRAxFIFAACswWAARXgCIQygyJZDUaCCVg+oyE4nUMDIC3IfhOOQB0vBlmIn5-QEy9EGcQ6KMQOnGFh0yzJmzgcTUcORvSx1iJqwp2zloA" rel="nofollow noreferrer">https://www.typescriptlang.org/play/#code/MYewdgzgLgBARgQwgUxgXhgbwFAzzUAW0ITABMIAuLXfOgBwEswBzanOz-M5CYAJ0b0ojcNQBE42lwC+0mHLnZQkWMjDoadIiXJUtXGE1bt5hmDz6DhosBPEBuM-jl1F2bFACe9VABlSFgBXBBZUDABrZC8QADMYb184mAAbQJCwiCdlcGhU9NDeagAlZFB+MgAecXVxABoEn2RkxBQAPk1MGHUFbOQAD3oQflgVPJQoANYM8JhKgBVu-qh1Chgp4MK2gAo0kxh5gEp0Do58fmQoIP4NSuc8AGkllb0YKJj4vxBgBBTGAC8ECJwABZBD0Or3GAANWeqwg62+vwBQNsYPoAG0HgBdDHiej8ED0CDibHyHZQ97UB6Q8wAOgZ9DSwGQAAsQCkePx9NCMWS6Mc0KcoSlLgl+KQIGlgRpItEoXQ6RAmYwoNtxHTxIcFfg6RcyEEWdttghgMAGgA3X6Cjqm4AYq0pbENPabTIY13Yw5ONzYJTMFb8WKm1AAYRAxFIFAACswWAARXgCIQygyJZDUaCCVg+oyE4nUMDIC3IfhOOQB0vBlmIn5-QEy9EGcQ6KMQOnGFh0yzJmzgcTUcORvSx1iJqwp2zloA

Body:
It seems like the meat of your code is here:

const key = "commands.ping.description";
const en = {
    commands: {
        ping: {
            description: "";
        }
    }
}
let translation = key
    .split(".")
    .reduce((acc, val) => acc[val], en);

and what you want TypeScript to do is to figure out the type of acc[val] where
val is a substring of key. That's not going to happen; it's well beyond the limitations of string literal types, and for good reason.

What I recommend you do is loosen your types to something like this:

const key = "commands.ping.description";
interface RecursiveRecord<T> {
    [key: string]: T | RecursiveRecord<T>;
}
const en: RecursiveRecord<string> = {
    commands: {
        ping: {
            description: "hello";
        }
    }
}

// go through the properties from key.split(".")
// and assign the string at the end to translation
let record = en;
let translation: string = "";
for (const substr of key.split(".")) {
    const oneLevelDeeper = record[substr];
    if (typeof oneLevelDeeper === "string") {
        translation = oneLevelDeeper
        break;
    } else {
        record = oneLevelDeeper;
    }
}
console.log(translation); // "hello"


问:
Most efficient way in Python to iterate over a large file (10GB+)
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

```<code>    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1
</code>```

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

答: Have you tried mincemeat.py? It is a Python implementation of the MapReduce distributed computing framework. I'm not sure if you'll have performance gain since I've not yet processed 10GB of data before using it, though you might explore this framework.</p>

Body:
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)


问:
CSV file to JSON using python
I am currently trying to convert a csv with 4 different fields to a json body for making an api call. The current csv looks like this:

```<code>firstname, lastname, email, login
Jake, Smith, jake.smith@example.com, jake.smith@example.com
John, Appleseed, john.appleseed@example.com, john.appleseed@example.com
</code>```

I would like the json to look like this

```<code>{"profile": {"firstName": "Jake", "lastName": "Smith", "email": "jake.smith@example.com", "login": "jake.smith@example.com"}}
</code>```

```<code>{"profile": {"firstName": "John", "lastName": "Appleseed", "email": "john.appleseed@example.com", "login": "john.appleseed@example.com"}}
</code>```

答:
Try this, not the best solution but works:

```<code>df = pd.read_csv('test.csv')
for i in range(0, df.shape[0]):
    json_data = df.loc[[i]].to_json(orient='records')
    json_data = json_data.strip('[]')
    x = json.loads(json_data)
    j = {'profile': x}
    print(json.dumps(j))
</code>```

Output:

```<code>{"profile": {"firstname": "Jake", "lastname": "Smith", "email": "jake.smith@example.com", "login": " ake.smith@example.com"}}
{"profile": {"firstname": "John", "lastname": "Appleseed", "email": "john.appleseed@example.com", "login": "john.appleseed@example.com"}}
</code>```

Title: CSV file to JSON using python

Body:
I am currently trying to convert a csv with 4 different fields to a json body for making an api call. The current csv looks like this:

firstname, lastname, email, login
Jake, Smith, jake.smith@example.com, jake.smith@example.com
John, Appleseed, john.appleseed@example.com, john.appleseed@example.com

I would like the json to look like this

{"profile": {"firstName": "Jake", "lastName": "Smith", "email": "jake.smith@example.com", "login": "jake.smith@example.com"}}

{"profile": {"firstName": "John", "lastName": "Appleseed", "email": "john.appleseed@example.com", "login": "john.appleseed@example.com"}}

Body:
Try this, not the best solution but works:

df = pd.read_csv('test.csv')
for i in range(0, df.shape[0]):
    json_data = df.loc[[i]].to_json(orient='records')
    json_data = json_data.strip('[]')
    x = json.loads(json_data)
    j = {'profile': x}
    print(json.dumps(j))

Output:

{"profile": {"firstname": "Jake", "lastname": "Smith", "email": "jake.smith@example.com", "login": " ake.smith@example.com"}}
{"profile": {"firstname": "John", "lastname": "Appleseed", "email": "john.appleseed@example.com", "login": "john.appleseed@example.com"}}


问:
stored procedure ( inner join from same table)
i have a table WEATHER_STATION.Precipitacao like this

```<code>value | date | station with various values  for example :

valor_observado  |    data_observacao    | estacao
14                   2020-01-18              X
15                   2020-01-19              X
16                   2020-01-20              X
1                    2020-01-18              Y
2                    2020-01-19              Y
3                    2020-01-20              Y
</code>```

i want to make a stored procedure with a date as input  , that give me the highest value, the date and the station .
In this example , the result with a input of '2020-01-18'  will be

```<code>data_observacao | valor_observado | estacao
  2020-01-18           14            X
</code>```

I make a stored procedure like this but it didn't work (nothing appears) :

```<code>CREATE PROC PRECIPITACAO_MAXIMA_DATA @data date  AS
select data_observacao=@data , maximo_precipitacao,estacao
from WEATHER_STATION.Precipitacao
inner join
(select data_observacao= @data ,max(valor_observado) as maximo_precipitacao
from WEATHER_STATION.Precipitacao) a
on a.data_observacao = WEATHER_STATION.Precipitacao.data_observacao AND a.maximo_precipitacao = valor_observado
GO
</code>```

the result is this:

```<code>data_observacao | valor_observado | estacao

</code>```

答:
I am assuming that you are using SQL Server based on the syntax.

You can do what you want with:

```<code>select top (1) p.*
from WEATHER_STATION.Precipitacao p
where data_observacao = @data
order by valor_observado desc;
</code>```

In most other databases, you can use limit or fetch first 1 row only.

Body:
i have a table WEATHER_STATION.Precipitacao like this

value | date | station with various values  for example :

valor_observado  |    data_observacao    | estacao
14                   2020-01-18              X
15                   2020-01-19              X
16                   2020-01-20              X
1                    2020-01-18              Y
2                    2020-01-19              Y
3                    2020-01-20              Y

i want to make a stored procedure with a date as input  , that give me the highest value, the date and the station .
In this example , the result with a input of '2020-01-18'  will be

data_observacao | valor_observado | estacao
  2020-01-18           14            X

I make a stored procedure like this but it didn't work (nothing appears) :

CREATE PROC PRECIPITACAO_MAXIMA_DATA @data date  AS
select data_observacao=@data , maximo_precipitacao,estacao
from WEATHER_STATION.Precipitacao
inner join
(select data_observacao= @data ,max(valor_observado) as maximo_precipitacao
from WEATHER_STATION.Precipitacao) a
on a.data_observacao = WEATHER_STATION.Precipitacao.data_observacao AND a.maximo_precipitacao = valor_observado
GO

the result is this:

data_observacao | valor_observado | estacao

Body:
I am assuming that you are using SQL Server based on the syntax.

You can do what you want with:

select top (1) p.*
from WEATHER_STATION.Precipitacao p
where data_observacao = @data
order by valor_observado desc;

In most other databases, you can use limit or fetch first 1 row only.


问:
Update an entity in Messenger Handler (Symfony)
I'm trying to move my heavy treatment to Messenger.

It works but I would like to show a percentage of progress to my users.
I created a DownloadTask entity and I try to update it during the process but it doesn't work. My entity is not updated in the database.

Do you have any ideas?

I'm still learning, so I hope my code won't hurt your eyes too much.

<?php

namespace App\MessageHandler;

use App\Message\GetSellerList;
use App\Repository\DownloadTaskRepository;
use App\Service\EbayDL;
use Doctrine\DBAL\ConnectionException;
use Doctrine\ORM\EntityManagerInterface;
use DTS\eBaySDK\Trading\Types\GetSellerListResponseType;
use GuzzleHttp\Promise;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class GetSellerListHandler implements MessageHandlerInterface
{
    /**
     * @var EbayDL
     */
    private $ebayDL;
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var \App\Entity\DownloadTask
     */
    private $task;
    /**
     * @var DownloadTaskRepository
     */
    private $downloadTaskRepository;

    public function __construct(EbayDL $ebayDL, EntityManagerInterface $entityManager, DownloadTaskRepository $downloadTaskRepository, LoggerInterface $logger)
    {
        $this->ebayDL                 = $ebayDL;
        $this->entityManager          = $entityManager;
        $this->logger                 = $logger;
        $this->downloadTaskRepository = $downloadTaskRepository;
    }

    /**
     * @throws ConnectionException
     * @throws \Exception
     * @throws \Throwable
     */
    public function __invoke(GetSellerList $getSellerList): void
    {
        $task = $this->downloadTaskRepository->find($getSellerList->getDownloadTaskId());

        $this->clearDatabase();
        $listingInfos = $this->ebayDL->getInformation();

        $totalNumberOfPages = $listingInfos['totalNumberOfPages'];

        $promises = (function () use ($totalNumberOfPages) {
            for ($page = 1; $page <= $totalNumberOfPages; ++$page) {
                yield $this->ebayDL->getProductsByPageAsync($page);
            }
        })();

        $eachPromise = new Promise\EachPromise($promises, [
            'concurrency' => 6,
            'fulfilled'   => function (GetSellerListResponseType $response): void {
                $products = $this->ebayDL->parseSellerListResponse($response);
                foreach ($products as $product) {
                    try {
                        $this->entityManager->persist($product);
                        $this->entityManager->flush();
                    } catch (\Exception $e) {
                        $this->logger->error('Failed to store a product');
                        $this->logger->error($e->getMessage());
                        if (!$this->entityManager->isOpen()) {
                            // https://stackoverflow.com/questions/14258591/the-entitymanager-is-closed
                            $this->entityManager = $this->entityManager->create(
                                $this->entityManager->getConnection(),
                                $this->entityManager->getConfiguration()
                            );
                        }
                    }
                }
            },
        ]);

        $eachPromise->promise()->wait();

        $this->task
            ->setProgress(100)
            ->setCompletedAt(new \DateTime('NOW'));

        $this->entityManager->flush();
    }

    /**
     * @throws ConnectionException
     * @throws \Doctrine\DBAL\DBALException
     */
    private function clearDatabase(): void
    {
        $connection = $this->entityManager->getConnection();
        $connection->beginTransaction();

        try {
            $connection->query('SET FOREIGN_KEY_CHECKS=0');
            $connection->query('DELETE FROM product');
            $connection->query('SET FOREIGN_KEY_CHECKS=1');
            $connection->commit();
        } catch (\Exception $exception) {
            $connection->rollback();
        }
    }
}
```

答:
Should

```<code>$task =  $this->downloadTaskRepository->find($getSellerList->getDownloadTaskId());
</code>```

be

```<code>$this->task =  $this->downloadTaskRepository->find($getSellerList->getDownloadTaskId());
</code>```

?

Body:
Should

$task =  $this->downloadTaskRepository->find($getSellerList->getDownloadTaskId());

be

$this->task =  $this->downloadTaskRepository->find($getSellerList->getDownloadTaskId());

?


问:
Oracle 10: Using HEXTORAW to fill in blob data
We have a table in Oracle with a BLOB column that needs to be filled with a small amount of arbitrary byte data--we will never put in more than 4000 bytes of data.

I am working with an existing C++ OCI-based infrastructure that makes it extremely difficult to use bind variables in certain contexts, so I need to populate this BLOB column using only a simple query. (We are working to modernize it but that's not an option today,)

We had some luck with a query like this:

```<code>UPDATE MyTable
   SET blobData = HEXTORAW('0EC1D7FA6B411DA5814...lots of hex data...0EC1D7FA6B411DA5814')
 WHERE ID = 123;
</code>```

At first, this was working great. However, recently we encountered a case where we need to put in more than 2000 bytes of data. At this point, we hit an Oracle error, ORA-01704: string literal too long because the string being passed to HEXTORAW was over 4000 characters. I tried splitting up the string and then concatenating with ||, but this didn't dodge the error.

So, I need a way to update this column and fill it with more than 2000 bytes' worth of data using a simple query. Is it possible?

(I know if I had bind variables at my disposal it would be trivial--and in fact other apps which interact with this table use that exact technique--but unfortunately I am not in a position to refactor the DB guts here. Just need to get data into the table.)

EDIT:

One promising approach that didn't work was concatenating RAWs:

```<code>UTL_RAW.CONCAT(HEXTORAW('...'), HEXTORAW('...'), HEXTORAW('...'))
</code>```

This dodges the string-length limit, but it appears that Oracle also has a matching internal 2000 byte limit on the length of a RAW. So I can't populate the blob with a RAW. Maybe there is a function that concatenates multiple RAWs into a BLOB.

答:
Here is my solution for concatenating multiple RAWs into single BLOB using helper table type and stored function:

```<code>create or replace type raws as table of raw(2000);

create or replace function concat_raws(parts in raws) return blob
is
    temp blob;
begin
    if parts is null or parts.count = 0 then
       return null;
    end if;
    dbms_lob.createtemporary(temp, false, dbms_lob.CALL);
    for i in parts.first .. parts.last
    loop
        dbms_lob.append(temp, to_blob(parts(i)));
    end loop;
    return temp;
end;

-- usage example:
select concat_raws(raws(hextoraw('CAFE'), hextoraw('BABE'))) from dual;
</code>```

This approach is also handy for automated sql generation as shown in my other answer to Inline BLOB / BINARY data types in SQL / JDBC.

See also multiple BLOBs concatenation in How to concatenate BLOB fields (Oracle)?

Body:
We have a table in Oracle with a BLOB column that needs to be filled with a small amount of arbitrary byte data--we will never put in more than 4000 bytes of data.

I am working with an existing C++ OCI-based infrastructure that makes it extremely difficult to use bind variables in certain contexts, so I need to populate this BLOB column using only a simple query. (We are working to modernize it but that's not an option today,)

We had some luck with a query like this:

UPDATE MyTable
   SET blobData = HEXTORAW('0EC1D7FA6B411DA5814...lots of hex data...0EC1D7FA6B411DA5814')
 WHERE ID = 123;

At first, this was working great. However, recently we encountered a case where we need to put in more than 2000 bytes of data. At this point, we hit an Oracle error, ORA-01704: string literal too long because the string being passed to HEXTORAW was over 4000 characters. I tried splitting up the string and then concatenating with ||, but this didn't dodge the error.

So, I need a way to update this column and fill it with more than 2000 bytes' worth of data using a simple query. Is it possible?

(I know if I had bind variables at my disposal it would be trivial--and in fact other apps which interact with this table use that exact technique--but unfortunately I am not in a position to refactor the DB guts here. Just need to get data into the table.)

EDIT:

One promising approach that didn't work was concatenating RAWs:

UTL_RAW.CONCAT(HEXTORAW('...'), HEXTORAW('...'), HEXTORAW('...'))

This dodges the string-length limit, but it appears that Oracle also has a matching internal 2000 byte limit on the length of a RAW. So I can't populate the blob with a RAW. Maybe there is a function that concatenates multiple RAWs into a BLOB.

Body:
Here is my solution for concatenating multiple RAWs into single BLOB using helper table type and stored function:

create or replace type raws as table of raw(2000);

create or replace function concat_raws(parts in raws) return blob
is
    temp blob;
begin
    if parts is null or parts.count = 0 then
       return null;
    end if;
    dbms_lob.createtemporary(temp, false, dbms_lob.CALL);
    for i in parts.first .. parts.last
    loop
        dbms_lob.append(temp, to_blob(parts(i)));
    end loop;
    return temp;
end;

-- usage example:
select concat_raws(raws(hextoraw('CAFE'), hextoraw('BABE'))) from dual;

This approach is also handy for automated sql generation as shown in my other answer to Inline BLOB / BINARY data types in SQL / JDBC.

See also multiple BLOBs concatenation in How to concatenate BLOB fields (Oracle)?


答:
Consider using a row-limiting query:

```<code>create proc precipitacao_maxima_data
    @data date
as
    select top (1) t.*
    from weather_station.precipitacao t
    where data_observacao = @data
    order by valor_observacao desc;
</code>```

This simply selects all rows whose data_observacao matches the given @data parameter, sorts them by descending valor_observacao, and retains the first row only.

Title: stored procedure ( inner join from same table)

Body:
Consider using a row-limiting query:

create proc precipitacao_maxima_data
    @data date
as
    select top (1) t.*
    from weather_station.precipitacao t
    where data_observacao = @data
    order by valor_observacao desc;

This simply selects all rows whose data_observacao matches the given @data parameter, sorts them by descending valor_observacao, and retains the first row only.


问:
Pytorch Multiclass Logistic Regression Type Errors
I'm new to ML and even more naive with Pytorch. Here's the problem. (I've skipped certain parts like the random_split() which seem to work just fine)

I've to predict wine quality (red) which from the dataset is the last column with 6 classes

That's what my dataset looks like

The link to the dataset (winequality-red.csv)

```<code>features = df.drop(['quality'], axis = 1)
targets = df.iloc[:, -1] # theres 6 classes

dataset = TensorDataset(torch.Tensor(np.array(features)).float(), torch.Tensor(targets).float())
# here's where I think the error might be, but I might be wrong

batch_size = 8
# Dataloader

train_loader = DataLoader(train_ds, batch_size, shuffle = True)
val_loader = DataLoader(val_ds, batch_size)
test_ds = DataLoader(test_ds, batch_size)

input_size = len(df.columns) - 1
output_size = 6
threshold = .5

class WineModel(nn.Module):

  def __init__(self):
    super().__init__()
    self.linear = nn.Linear(input_size, output_size)

  def forward(self, xb):
    out = self.linear(xb)
    return out

model = WineModel()
n_iters = 2000
num_epochs = n_iters / (len(train_ds) / batch_size)
num_epochs = int(num_epochs)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2)

# the part below returns the error on running
iter = 0
for epoch in range(num_epochs):
  for i, (x, y) in enumerate(train_loader):
    optimizer.zero_grad()
    outputs = model(x)
    loss = criterion(outputs, y)
    loss.backward()
    optimizer.step()
</code>```

RuntimeError: expected scalar type Long but found Float

Hopefully that is sufficient info

答:
The targets for nn.CrossEntropyLoss are given as the class indices, which are required to be integers, to be precise they need to be of type torch.long, which is equivalent to torch.int64.

You converted the targets to floats, but you should convert them to longs:

dataset = TensorDataset(torch.Tensor(np.array(features)).float(), torch.Tensor(targets).long())
```

<p>Since the targets are the indices of the classes, they must be in range <em>[0, num_classes - 1]</em>. As you have 6 classes that would be in range [0, 5]. Having a quick look at your data, the quality uses values in range [3, 8]. Even though you have 6 classes, the values cannot be used directly as the classes. If you list the classes as <code>classes = [3, 4, 5, 6, 7, 8]</code>, you can see that the first class is 3, <code>classes[0] == 3</code>, up to the last class being <code>classes[5] == 8</code>.</p>

<p>You need to replace the class values with the indices, just like you would for named classes (e.g. if you had the classes <em>dog</em> and <em>cat</em>, <em>dog</em> would be 0 and <em>cat</em> would be 1), but you can avoid having to look them up, since the values are simply shifted by 3, i.e. <code>index = classes[index] - 3</code>. Therefore you can subtract 3 from the entire target tensor:</p>

<pre class="lang-py prettyprint-override"><code>torch.Tensor(targets).long() - 3
</code>```

Body:
I'm new to ML and even more naive with Pytorch. Here's the problem. (I've skipped certain parts like the random_split() which seem to work just fine)

I've to predict wine quality (red) which from the dataset is the last column with 6 classes

That's what my dataset looks like

The link to the dataset (winequality-red.csv)

features = df.drop(['quality'], axis = 1)
targets = df.iloc[:, -1] # theres 6 classes

dataset = TensorDataset(torch.Tensor(np.array(features)).float(), torch.Tensor(targets).float())
# here's where I think the error might be, but I might be wrong

batch_size = 8
# Dataloader

train_loader = DataLoader(train_ds, batch_size, shuffle = True)
val_loader = DataLoader(val_ds, batch_size)
test_ds = DataLoader(test_ds, batch_size)

input_size = len(df.columns) - 1
output_size = 6
threshold = .5

class WineModel(nn.Module):

  def __init__(self):
    super().__init__()
    self.linear = nn.Linear(input_size, output_size)

  def forward(self, xb):
    out = self.linear(xb)
    return out

model = WineModel()
n_iters = 2000
num_epochs = n_iters / (len(train_ds) / batch_size)
num_epochs = int(num_epochs)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2)

# the part below returns the error on running
iter = 0
for epoch in range(num_epochs):
  for i, (x, y) in enumerate(train_loader):
    optimizer.zero_grad()
    outputs = model(x)
    loss = criterion(outputs, y)
    loss.backward()
    optimizer.step()

RuntimeError: expected scalar type Long but found Float

Hopefully that is sufficient info

Body:
The targets for nn.CrossEntropyLoss are given as the class indices, which are required to be integers, to be precise they need to be of type torch.long, which is equivalent to torch.int64.

You converted the targets to floats, but you should convert them to longs:

dataset = TensorDataset(torch.Tensor(np.array(features)).float(), torch.Tensor(targets).long())

Since the targets are the indices of the classes, they must be in range [0, num_classes - 1]. As you have 6 classes that would be in range [0, 5]. Having a quick look at your data, the quality uses values in range [3, 8]. Even though you have 6 classes, the values cannot be used directly as the classes. If you list the classes as classes = [3, 4, 5, 6, 7, 8], you can see that the first class is 3, classes[0] == 3, up to the last class being classes[5] == 8.

You need to replace the class values with the indices, just like you would for named classes (e.g. if you had the classes dog and cat, dog would be 0 and cat would be 1), but you can avoid having to look them up, since the values are simply shifted by 3, i.e. index = classes[index] - 3. Therefore you can subtract 3 from the entire target tensor:

torch.Tensor(targets).long() - 3


问:
I want to replace a date value per employee
I have this file in excel. I need to do the transformation on it. For a particular Personnum and for a particular date, I want to check if the ENDREASON is out or missedOut. If it is missedOut then the date ENDDTM of the previous entry. i.e the last out entry will be considered as the StartDTM for missedOut value. Is there any way I can code it in python or SQL? Any way I can do it in Databricks?

答:
Since there is no column called out I think we will have to use a rank function and then play around with the query. I have not tested the query something similar to below should work .Please do focus on the rank function which I am using and adding 1 to the second query.</p>

```<code>CREATE TABLE foo1
(
    APPLYDATE datetime,
    STARTDTM datetime,
    ENDDTM datetime,
    PERSONNUM int,
    STARTREASON varchar(100),
    ENDREASON varchar(100)
)

select getdate()

INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 06:30:47.223','2020-04-23 10:10:47.223',204901477,'newshift','out')
INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 21:45:47.223','2020-04-23 21:45:47.223',204901477,'newshift','missedout')
INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 10:10:47.223','2020-04-23 12:15:47.223',204901477,'newshift','out')

INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 06:30:47.223','2020-04-24 10:10:47.223',204901478,'newshift','out')
INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 21:45:47.223','2020-04-24 21:45:47.223',204901478,'newshift','missedout')
INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 10:10:47.223','2020-04-24 12:15:47.223',204901478,'newshift','out')

SELECT
    aa.PERSONNUM,
    ENDDTM = CASE
                WHEN aa.ENDREASON = 'missedout' THEN bb.ENDDTM
                ELSE aa.ENDDTM
             END
FROM
    (SELECT
         ROW_NUMBER() OVER (PARTITION BY PERSONNUM ORDER BY PERSONNUM) AS id1,
         *
     FROM
         foo1) aa
JOIN
    (SELECT
         ROW_NUMBER() OVER (PARTITION BY PERSONNUM ORDER BY PERSONNUM) + 1  AS id2,
         *
     FROM
         foo1) bb ON aa.id1 = bb.id2
</code>```

Body:
Since there is no column called out I think we will have to use a rank function and then play around with the query. I have not tested the query something similar to below should work .Please do focus on the rank function which I am using and adding 1 to the second query.

CREATE TABLE foo1
(
    APPLYDATE datetime,
    STARTDTM datetime,
    ENDDTM datetime,
    PERSONNUM int,
    STARTREASON varchar(100),
    ENDREASON varchar(100)
)

select getdate()

INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 06:30:47.223','2020-04-23 10:10:47.223',204901477,'newshift','out')
INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 21:45:47.223','2020-04-23 21:45:47.223',204901477,'newshift','missedout')
INSERT INTO foo1
VALUES ('2020-04-23 00:00:00.000','2020-04-23 10:10:47.223','2020-04-23 12:15:47.223',204901477,'newshift','out')

INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 06:30:47.223','2020-04-24 10:10:47.223',204901478,'newshift','out')
INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 21:45:47.223','2020-04-24 21:45:47.223',204901478,'newshift','missedout')
INSERT INTO foo1
VALUES ('2020-04-24 00:00:00.000','2020-04-24 10:10:47.223','2020-04-24 12:15:47.223',204901478,'newshift','out')

SELECT
    aa.PERSONNUM,
    ENDDTM = CASE
                WHEN aa.ENDREASON = 'missedout' THEN bb.ENDDTM
                ELSE aa.ENDDTM
             END
FROM
    (SELECT
         ROW_NUMBER() OVER (PARTITION BY PERSONNUM ORDER BY PERSONNUM) AS id1,
         *
     FROM
         foo1) aa
JOIN
    (SELECT
         ROW_NUMBER() OVER (PARTITION BY PERSONNUM ORDER BY PERSONNUM) + 1  AS id2,
         *
     FROM
         foo1) bb ON aa.id1 = bb.id2


问:
sqlite3 & PHP results empty: object(SQLite3Result)#3 (0) { }
Im starting to use sqlite3 but I'am unable to get some results.
My database is called database.sqlite3

Inside SQLite command prompt and doing 'SELECT * FROM table'; . works fine. But im having problems with php.

```<code>$db = new SQLite3('db/database.sqlite3');
$result = $db->query('SELECT * FROM table');
var_dump( $result );
</code>```

The result of this code is : object(SQLite3Result)#3 (0) { }

What is worng here?

Thank you.

PD: $result->fetchArray(SQLITE3_ASSOC) works but only gives me one record... why???

答:
So just in case someone is in the same trouble. SQLITE does not work like that. You must walk through a loop to get every row. Then you can create your data array.

Something like this.

```<code>$db = new SQLite3('db/database.sqlite3');

$result = $db->query('SELECT * FROM table');

while( $row = $result->fetchArray() ){

  echo $row['name'];

}
</code>```

Body:
Im starting to use sqlite3 but I'am unable to get some results.
My database is called database.sqlite3

Inside SQLite command prompt and doing 'SELECT * FROM table'; . works fine. But im having problems with php.

$db = new SQLite3('db/database.sqlite3');
$result = $db->query('SELECT * FROM table');
var_dump( $result );

The result of this code is : object(SQLite3Result)#3 (0) { }

What is worng here?

Thank you.

PD: $result->fetchArray(SQLITE3_ASSOC) works but only gives me one record... why???

Body:
So just in case someone is in the same trouble. SQLITE does not work like that. You must walk through a loop to get every row. Then you can create your data array.

Something like this.

$db = new SQLite3('db/database.sqlite3');

$result = $db->query('SELECT * FROM table');

while( $row = $result->fetchArray() ){

  echo $row['name'];

}