问:
in elastic search, how can get document max value for nested field?
is My Mapping.

```<code>"script": {
    "type": "nested",
    "properties": {
        "name": {
            "type": "keyword"
        },
        "age": {
            "type": "integer"
        }
    }
}
</code>```

and sample document below

```<code>PUT /btest/_create/1
{
  "script": [
    {
      "name": "john",
      "age": 14
    }
  ]
}

PUT /btest/_create/2
{
  "script": [
    {
      "name": "tt",
      "age": 14
    },
    {
      "name": "jj",
      "age": 17
    },
    {
      "name": "tim",
      "age": 34
    }
  ]
}

PUT /btest/_create/3
{
  "script": [
    {
      "name": "john",
      "age": 42
    },
    {
      "name": "jj",
      "age": 12
    }
  ]
}
</code>```

and use max aggregation for get max ages :

```<code>GET /btest/_search
{
  "query": {
    "nested": {
      "path": "script",
      "query": {
        "match": {
          "script.name": "john"
        }
      }
    }
  },
  "aggs": {
    "age": {
      "nested": {
        "path": "script"
      },
      "aggs": {
        "script_age": {
          "filter": {
            "match": {
              "script.name": "john"
            }
          },
          "aggs": {
            "length": {
              "max": {
                "field": "script.age"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

but it returns all matched "script.name": "john".

i want to get document only max age john.

should I use aggregation to get this document?

or is there a way to use a query similar to max without aggregation for nested field?

答:
According to your requirement, you need to fetch only those documents that match with name john. This can be achieved in the query section using a nested query with match query.

Now, to get the document having max-age (with name john) you can perform top hits aggregation with sort on script.age field.

```<code>{
    "size": 0,
    "query": {
        "nested": {
            "path": "script",
            "query": {
                "match": {
                    "script.name": "john"
                }
            }
        }
    },
    "aggs": {
        "nested-agg": {
            "nested": {
                "path": "script"
            },
            "aggs": {
                "by_age": {
                    "top_hits": {
                        "sort": [
                            {
                                "script.age": {
                                    "order": "desc"
                                }
                            }
                        ],
                        "size": 1
                    }
                }
            }
        }
    }
}
</code>```

The search response will be

```<code>"aggregations": {
        "nested-agg": {
            "doc_count": 3,
            "by_age": {
                "hits": {
                    "total": {
                        "value": 3,
                        "relation": "eq"
                    },
                    "max_score": null,
                    "hits": [
                        {
                            "_index": "71081556",
                            "_type": "_doc",
                            "_id": "3",
                            "_nested": {
                                "field": "script",
                                "offset": 0
                            },
                            "_score": null,
                            "_source": {
                                "name": "john",
                                "age": 42
                            },
                            "sort": [
                                42
                            ]
                        }
                    ]
                }
            }
        }
    }
</code>```

Option 2

You can use sort with the nested query, to get the document having max age

```<code>{
    "size": 1,
    "sort": [
        {
            "script.age": {
                "order": "desc",
                "nested": {
                    "path": "script",
                    "filter": {
                        "term": {
                            "script.name": "john"
                        }
                    }
                }
            }
        }
    ]
}
</code>```

But in this case, the response contains the entire document, instead of only the matching document

```<code>"hits": [
            {
                "_index": "71081556",
                "_type": "_doc",
                "_id": "3",
                "_score": null,
                "_source": {
                    "script": [
                        {
                            "name": "john",
                            "age": 42
                        },
                        {
                            "name": "jj",
                            "age": 12
                        }
                    ]
                },
                "sort": [
                    42
                ]
            }
        ]
</code>```

Body:
is My Mapping.

"script": {
    "type": "nested",
    "properties": {
        "name": {
            "type": "keyword"
        },
        "age": {
            "type": "integer"
        }
    }
}

and sample document below

PUT /btest/_create/1
{
  "script": [
    {
      "name": "john",
      "age": 14
    }
  ]
}

PUT /btest/_create/2
{
  "script": [
    {
      "name": "tt",
      "age": 14
    },
    {
      "name": "jj",
      "age": 17
    },
    {
      "name": "tim",
      "age": 34
    }
  ]
}

PUT /btest/_create/3
{
  "script": [
    {
      "name": "john",
      "age": 42
    },
    {
      "name": "jj",
      "age": 12
    }
  ]
}

and use max aggregation for get max ages :

GET /btest/_search
{
  "query": {
    "nested": {
      "path": "script",
      "query": {
        "match": {
          "script.name": "john"
        }
      }
    }
  },
  "aggs": {
    "age": {
      "nested": {
        "path": "script"
      },
      "aggs": {
        "script_age": {
          "filter": {
            "match": {
              "script.name": "john"
            }
          },
          "aggs": {
            "length": {
              "max": {
                "field": "script.age"
              }
            }
          }
        }
      }
    }
  }
}

but it returns all matched "script.name": "john".

i want to get document only max age john.

should I use aggregation to get this document?

or is there a way to use a query similar to max without aggregation for nested field?

Body:
According to your requirement, you need to fetch only those documents that match with name john. This can be achieved in the query section using a nested query with match query.

Now, to get the document having max-age (with name john) you can perform top hits aggregation with sort on script.age field.

{
    "size": 0,
    "query": {
        "nested": {
            "path": "script",
            "query": {
                "match": {
                    "script.name": "john"
                }
            }
        }
    },
    "aggs": {
        "nested-agg": {
            "nested": {
                "path": "script"
            },
            "aggs": {
                "by_age": {
                    "top_hits": {
                        "sort": [
                            {
                                "script.age": {
                                    "order": "desc"
                                }
                            }
                        ],
                        "size": 1
                    }
                }
            }
        }
    }
}

The search response will be

"aggregations": {
        "nested-agg": {
            "doc_count": 3,
            "by_age": {
                "hits": {
                    "total": {
                        "value": 3,
                        "relation": "eq"
                    },
                    "max_score": null,
                    "hits": [
                        {
                            "_index": "71081556",
                            "_type": "_doc",
                            "_id": "3",
                            "_nested": {
                                "field": "script",
                                "offset": 0
                            },
                            "_score": null,
                            "_source": {
                                "name": "john",
                                "age": 42
                            },
                            "sort": [
                                42
                            ]
                        }
                    ]
                }
            }
        }
    }

Option 2

You can use sort with the nested query, to get the document having max age

{
    "size": 1,
    "sort": [
        {
            "script.age": {
                "order": "desc",
                "nested": {
                    "path": "script",
                    "filter": {
                        "term": {
                            "script.name": "john"
                        }
                    }
                }
            }
        }
    ]
}

But in this case, the response contains the entire document, instead of only the matching document

"hits": [
            {
                "_index": "71081556",
                "_type": "_doc",
                "_id": "3",
                "_score": null,
                "_source": {
                    "script": [
                        {
                            "name": "john",
                            "age": 42
                        },
                        {
                            "name": "jj",
                            "age": 12
                        }
                    ]
                },
                "sort": [
                    42
                ]
            }
        ]


来源: stackexchange

问:
Github pages - how to reuse html code on each page (like a nav bar)
I found many answers to this question, but it was often outdated or I failed to make it work.

I have a nav-bar and I want to call it on each pages so when I want to update it, I need to change only one instance of the nav bar and not multiple instances on many pages.

How can I do it please? I am using Github pages, maybe it matters somehow.

Thanks

答:
Github-pages uses Jekyll, which on its own uses Markdown and Liquid.

If I've understood you correctly,

You can achieve what you want by using include syntax in Liquid which is referenced here.

You can find more information about include in here and this blog post.

This project uses different scenarios of include.

Github-pages is a powerful static site generator and you can achieve a lot by using it, checkout this list.

ContentLicense: CC BY-SA 4.0


问:
Block indent jupyter notebook
Does anyone know how to get a command shortcut to work for block indenting and un-indenting in Jupyter notebooks?

In the Jupiter notebook command group there is a command “automatically indent selection”. When I put in a command mode control-/  for that command the notebook does block commenting.

I don’t see any other command that refers to indenting.

I can’t seem to figure this </p>

答:
In JupyterLab,ctrl+[ and ctrl+] work for indentation/deindentation.

These solutions also are guaranteed to work, whereas Tab and Shift+Tab can trigger actions like intellisense if your cursor is in the middle of a line.

Title: Block indent jupyter notebook


问:
JavaScript nested async function calls executed out of order
Some context: I'm trying to implement a functionality on a website that opens a panel on the left side, then inserts a form to edit some information that is currently being shown on the website. It is triggered by an on click event and based on where the user is on the website, a different form is loaded. To do this I hand over a data-action (add or edit) and data-target (thing that should be edited) down to the functions.

Now opening the panel and filling in the information is working, problem is I have to make several intermediate API calls (fetching the partial forms to insert into the side panel, loading data to fill the edit form with) and I'm getting the asynchronous calls mixed up as I'm doing this

A bunch of stuff happens to originalButtonElement and sidePanelContainer but I'll truncate that for brevity.

```<code>$(document).on('click', '.side-panel-open', async function() {
    console.log('opening panel')
    await openSidePanel(originalButtonElement, sidePanelContainer);
    console.log('opened panel')

async function openSidePanel(originalButtonElement, sidePanelContainer) {
    const sidePanelTarget = originalButtonElement.data('side-panel-target');
    const sidePanelAction = originalButtonElement.data('side-panel-action');
    const apiReturnPromise = $.ajax({
            ...
        }
    });
    await apiReturnPromise.done(async function (result) {
        ...
        console.log('loading panel')
        await loadSidePanelForm(originalButtonElement, sidePanelTarget, sidePanelAction)
        console.log('loaded panel');
        return Promise.resolve()
    .fail(async function () {
        throw new Error();
    });

async function loadSidePanelForm(originalButtonElement, target, action) {
    switch (target) {
        case 'editable-element-1':
            console.log('getting form');
            await loadSidePanelElementOneForm(originalButtonElement, action);
            console.log('got form');
            return Promise.resolve()
        default:
            throw new TypeError(`There is no form for ${target}!`);
    }
}

async function loadSidePanelElementOneForm(originalButtonElement, action) {
    const apiReturnPromise = $.ajax({
        ...
    };
    await apiReturnPromise.done(async function (result) {
        if (action === 'add') {
            ...
            await loadSidePanelElementOneAddForm(originalButtonElement, sidePanelContainer);
        }
        else if (action === 'edit') {
            ...
            console.log('loading edit form');
            await loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer);
            console.log('loaded edit form')
            return Promise.resolve()
        }
    }
    .fail(async function () {
        throw new Error();
    });

async function loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer) {
const apiReturnPromise = $.ajax({
        ...
    };
    await apiReturnPromise.done(async function (result) {
        ...
        return Promise.resolve()
    };
    .fail(async function () {
        throw new Error();
    });
}
</code>```

I learned that you can only resolve a promise if it returns something. I also understand that ajax already returns a promise and the .done function then resolves it if I understand it correctly, hence why I wrote it like that. However, the log messages are out of order, up until await 'loadSidePanelElementOneForm(originalButtonElement, action);' it appears to be fine.

```<code>opening panel
loading panel
getting form
opened panel
loading edit form
got form
loaded panel
loaded edit form
</code>```

I've been on this for a few hours and am at a loss, having tried several other options. What am I doing wrong? I'm not sure which part of the code fails to wait for the others.

答:
I also understand that ajax already returns a promise and the .done function then resolves it if I understand it correctly

No, .done() does not "resolve it". All it does is to install a fulfillment handler callback. The promise resolves on its own, when the ajax request completes, and will then call the fulfillment/rejection handlers.

Also, .done() doesn't allow chaining of actions like .then(), it simply returns the original promise which doesn't wait for the handlers. Don't use .done()/.fail(), they're basically deprecated for years.

Your code might have worked if you had just used .then() instead, but really you shouldn't use that either. You should just use await syntax instead:

```<code>$(document).on('click', '.side-panel-open', async function() {
    console.log('opening panel')
    await openSidePanel(originalButtonElement, sidePanelContainer);
    console.log('opened panel')
});

async function openSidePanel(originalButtonElement, sidePanelContainer) {
    const sidePanelTarget = originalButtonElement.data('side-panel-target');
    const sidePanelAction = originalButtonElement.data('side-panel-action');
    const apiReturnPromise = $.ajax({
        …
    });
    const result = await apiReturnPromise;
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    …
    console.log('loading panel')
    await loadSidePanelForm(originalButtonElement, sidePanelTarget, sidePanelAction)
    console.log('loaded panel');
}

async function loadSidePanelForm(originalButtonElement, target, action) {
    switch (target) {
        case 'editable-element-1':
            console.log('getting form');
            await loadSidePanelElementOneForm(originalButtonElement, action);
            console.log('got form');
            return;
        default:
            throw new TypeError(`There is no form for ${target}!`);
    }
}

async function loadSidePanelElementOneForm(originalButtonElement, action) {
    const result = await $.ajax({
//  ^^^^^^^^^^^^^^^^^^^^
        …
    });
    if (action === 'add') {
        …
        await loadSidePanelElementOneAddForm(originalButtonElement, sidePanelContainer);
    } else if (action === 'edit') {
        …
        console.log('loading edit form');
        await loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer);
        console.log('loaded edit form')
    }
}

async function loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer) {
    const result = await $.ajax({
//  ^^^^^^^^^^^^^^^^^^^^
        …
    });
    …
}
</code>```

Body:
Some context: I'm trying to implement a functionality on a website that opens a panel on the left side, then inserts a form to edit some information that is currently being shown on the website. It is triggered by an on click event and based on where the user is on the website, a different form is loaded. To do this I hand over a data-action (add or edit) and data-target (thing that should be edited) down to the functions.

Now opening the panel and filling in the information is working, problem is I have to make several intermediate API calls (fetching the partial forms to insert into the side panel, loading data to fill the edit form with) and I'm getting the asynchronous calls mixed up as I'm doing this

A bunch of stuff happens to originalButtonElement and sidePanelContainer but I'll truncate that for brevity.

$(document).on('click', '.side-panel-open', async function() {
    console.log('opening panel')
    await openSidePanel(originalButtonElement, sidePanelContainer);
    console.log('opened panel')

async function openSidePanel(originalButtonElement, sidePanelContainer) {
    const sidePanelTarget = originalButtonElement.data('side-panel-target');
    const sidePanelAction = originalButtonElement.data('side-panel-action');
    const apiReturnPromise = $.ajax({
            ...
        }
    });
    await apiReturnPromise.done(async function (result) {
        ...
        console.log('loading panel')
        await loadSidePanelForm(originalButtonElement, sidePanelTarget, sidePanelAction)
        console.log('loaded panel');
        return Promise.resolve()
    .fail(async function () {
        throw new Error();
    });

async function loadSidePanelForm(originalButtonElement, target, action) {
    switch (target) {
        case 'editable-element-1':
            console.log('getting form');
            await loadSidePanelElementOneForm(originalButtonElement, action);
            console.log('got form');
            return Promise.resolve()
        default:
            throw new TypeError(`There is no form for ${target}!`);
    }
}

async function loadSidePanelElementOneForm(originalButtonElement, action) {
    const apiReturnPromise = $.ajax({
        ...
    };
    await apiReturnPromise.done(async function (result) {
        if (action === 'add') {
            ...
            await loadSidePanelElementOneAddForm(originalButtonElement, sidePanelContainer);
        }
        else if (action === 'edit') {
            ...
            console.log('loading edit form');
            await loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer);
            console.log('loaded edit form')
            return Promise.resolve()
        }
    }
    .fail(async function () {
        throw new Error();
    });

async function loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer) {
const apiReturnPromise = $.ajax({
        ...
    };
    await apiReturnPromise.done(async function (result) {
        ...
        return Promise.resolve()
    };
    .fail(async function () {
        throw new Error();
    });
}

I learned that you can only resolve a promise if it returns something. I also understand that ajax already returns a promise and the .done function then resolves it if I understand it correctly, hence why I wrote it like that. However, the log messages are out of order, up until await 'loadSidePanelElementOneForm(originalButtonElement, action);' it appears to be fine.

opening panel
loading panel
getting form
opened panel
loading edit form
got form
loaded panel
loaded edit form

I've been on this for a few hours and am at a loss, having tried several other options. What am I doing wrong? I'm not sure which part of the code fails to wait for the others.

Body:
I also understand that ajax already returns a promise and the .done function then resolves it if I understand it correctly

No, .done() does not "resolve it". All it does is to install a fulfillment handler callback. The promise resolves on its own, when the ajax request completes, and will then call the fulfillment/rejection handlers.

Also, .done() doesn't allow chaining of actions like .then(), it simply returns the original promise which doesn't wait for the handlers. Don't use .done()/.fail(), they're basically deprecated for years.

Your code might have worked if you had just used .then() instead, but really you shouldn't use that either. You should just use await syntax instead:

$(document).on('click', '.side-panel-open', async function() {
    console.log('opening panel')
    await openSidePanel(originalButtonElement, sidePanelContainer);
    console.log('opened panel')
});

async function openSidePanel(originalButtonElement, sidePanelContainer) {
    const sidePanelTarget = originalButtonElement.data('side-panel-target');
    const sidePanelAction = originalButtonElement.data('side-panel-action');
    const apiReturnPromise = $.ajax({
        …
    });
    const result = await apiReturnPromise;
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    …
    console.log('loading panel')
    await loadSidePanelForm(originalButtonElement, sidePanelTarget, sidePanelAction)
    console.log('loaded panel');
}

async function loadSidePanelForm(originalButtonElement, target, action) {
    switch (target) {
        case 'editable-element-1':
            console.log('getting form');
            await loadSidePanelElementOneForm(originalButtonElement, action);
            console.log('got form');
            return;
        default:
            throw new TypeError(`There is no form for ${target}!`);
    }
}

async function loadSidePanelElementOneForm(originalButtonElement, action) {
    const result = await $.ajax({
//  ^^^^^^^^^^^^^^^^^^^^
        …
    });
    if (action === 'add') {
        …
        await loadSidePanelElementOneAddForm(originalButtonElement, sidePanelContainer);
    } else if (action === 'edit') {
        …
        console.log('loading edit form');
        await loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer);
        console.log('loaded edit form')
    }
}

async function loadSidePanelElementOneEditForm(originalButtonElement, sidePanelContainer) {
    const result = await $.ajax({
//  ^^^^^^^^^^^^^^^^^^^^
        …
    });
    …
}


问:
Javascript: Calling Object Properties Multiple Times
I have an object:

```<code>var object = {
    string1 : 'hello',
    string2 : 'world'
}
</code>```

And If I want to call the string2 property of the object is it slower to call it multiple times like:

```<code>...object.string2...
...object.string2...
</code>```

or it would be faster to create a reference for it what holds the value of the parameter like:

```<code>var string2 = object.string2;
...string2...
...string2...
</code>```

The reason why I think that the second one could be faster, because I think right now that the first one always scans the whole object to grab the value.

答:
In you case this does not matter . But for big object with big prototype chunks - you right.
But you may win in speed but loose in functionality because var a = obje.property coping by value - not by reference and if obj.property will be change dynamically that variable a will have old value of obj.property </p>

ContentLicense: CC BY-SA 3.0

Body:
I have an object:

var object = {
    string1 : 'hello',
    string2 : 'world'
}

And If I want to call the string2 property of the object is it slower to call it multiple times like:

...object.string2...
...object.string2...

or it would be faster to create a reference for it what holds the value of the parameter like:

var string2 = object.string2;
...string2...
...string2...

The reason why I think that the second one could be faster, because I think right now that the first one always scans the whole object to grab the value.


问:
How to apply condition in boolean field in django rest framework?
I am working on a blog type website.

where students will ask question and teacher will answer it.

I put two user role
Teacher and student

```<code>class User(AbstractBaseUser, PermissionsMixin):
    USER_TYPE = (
        ('None', 'None'),
        ('Student', 'Student'),
        ('Teacher', 'Teacher'),
    )
    user_type = models.CharField(choices=USER_TYPE, default='Student', max_length=50)
</code>```

This is the user model where the role is defined.

Post model for submitting the question and Comment model for answering it.

In the Post model I put on field is_answered and as default put it False

```<code>class add_question(models.Model):
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
    is_answered = models.BooleanField(default=False)
</code>```

And the answer model [which is comment one] is referred to as the foreign key of the question

```<code>class submit_answer(models.Model):
    question_id = models.ForeignKey(
        add_question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
</code>```

Both question and answer model contains created_by field and ForeignKey of User and answer model contains another ForeignKey of question.

so I need when the teacher role will put a comment the is_answered Field in add_question model should turn as true.
as student also can comment on his/er question so I need on condition to apply.

I am using serializer as I need API of this

So, should I modify on my views.py or serializers.py and how should I do that!

It would be great help if someone guide me how to do it?

Thanks and let me know if any other information needed.

答:
The best practice would be adding such codition in save() method of models.Model. You should name your Model classes differently, like Question and Answer, because after creating, if you want to edit or something, it would be weird if you have to search for submit_answer, right? And as @wjh18 said, use CamelCase in classes.

Also question_id is usually bad idea, better think of question, because it will lead directly to the whole object, not its id.

```<code>class Answer(models.Model):
    question = models.ForeignKey(Question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.created_by.user_type == 'Teacher' and not self.question.is_answered:
            self.question.is_answered = True
            self.question.save()
        super().save(*args, **kwargs)
</code>```

Body:
I am working on a blog type website.

where students will ask question and teacher will answer it.

I put two user role
Teacher and student

class User(AbstractBaseUser, PermissionsMixin):
    USER_TYPE = (
        ('None', 'None'),
        ('Student', 'Student'),
        ('Teacher', 'Teacher'),
    )
    user_type = models.CharField(choices=USER_TYPE, default='Student', max_length=50)

This is the user model where the role is defined.

Post model for submitting the question and Comment model for answering it.

In the Post model I put on field is_answered and as default put it False

class add_question(models.Model):
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
    is_answered = models.BooleanField(default=False)

And the answer model [which is comment one] is referred to as the foreign key of the question

class submit_answer(models.Model):
    question_id = models.ForeignKey(
        add_question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

Both question and answer model contains created_by field and ForeignKey of User and answer model contains another ForeignKey of question.

so I need when the teacher role will put a comment the is_answered Field in add_question model should turn as true.
as student also can comment on his/er question so I need on condition to apply.

I am using serializer as I need API of this

So, should I modify on my views.py or serializers.py and how should I do that!

It would be great help if someone guide me how to do it?

Thanks and let me know if any other information needed.

Body:
The best practice would be adding such codition in save() method of models.Model. You should name your Model classes differently, like Question and Answer, because after creating, if you want to edit or something, it would be weird if you have to search for submit_answer, right? And as @wjh18 said, use CamelCase in classes.

Also question_id is usually bad idea, better think of question, because it will lead directly to the whole object, not its id.

class Answer(models.Model):
    question = models.ForeignKey(Question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.created_by.user_type == 'Teacher' and not self.question.is_answered:
            self.question.is_answered = True
            self.question.save()
        super().save(*args, **kwargs)


问:
Typedef in C, but a different way
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32
```
<p>I was expecting this to work too:</p>
<pre class="lang-c prettyprint-override"><code>struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);
</code>```

Is it just not possible to do it or I am missing something?

答:
struct myStr {...}; doesn't define myStr as a type in C (unlike in C++).  It defines struct myStr as a type.
If you want myStr to be a typedef for the defined struct myStr type, you need to say that

```<code>typedef struct myStr myStr;
</code>```

If you always want such a typedef, you can create a macro for it:

```<code>#define TYPEDEFED_STRUCT(NAME) typedef struct NAME NAME; struct NAME
TYPEDEFED_STRUCT(myStr){ ... }
</code>```

This behavior is due to how C separates normal and tag namespaces.

As a consequence of that, you can have both a function named
e.g., stat and a structure tagged stat (struct stat) and they don't conflict.
(Unix has a function named stat whose prototype is int stat(char const*, struct stat*);).

Interestingly since standardization, the tag namespace is shared between struct tags, union tags, and enum tags, so once you have struct stat, then even though you can have int stat();, defining a union stat or an enum stat would create conflicts with the struct stat (as theres's only one namespace for structs, unions, and enums).

Title: Typedef in C, but a different way

Body:
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32

I was expecting this to work too:

struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);

Is it just not possible to do it or I am missing something?

Body:
struct myStr {...}; doesn't define myStr as a type in C (unlike in C++).  It defines struct myStr as a type.
If you want myStr to be a typedef for the defined struct myStr type, you need to say that

typedef struct myStr myStr;

If you always want such a typedef, you can create a macro for it:

#define TYPEDEFED_STRUCT(NAME) typedef struct NAME NAME; struct NAME
TYPEDEFED_STRUCT(myStr){ ... }

This behavior is due to how C separates normal and tag namespaces.

As a consequence of that, you can have both a function named
e.g., stat and a structure tagged stat (struct stat) and they don't conflict.
(Unix has a function named stat whose prototype is int stat(char const*, struct stat*);).

Interestingly since standardization, the tag namespace is shared between struct tags, union tags, and enum tags, so once you have struct stat, then even though you can have int stat();, defining a union stat or an enum stat would create conflicts with the struct stat (as theres's only one namespace for structs, unions, and enums).


问:
Laravel 8 - POST JSON using foreach - API
previously, I have created a function to send data and it worked. but the data input method is only one by one.

and I think it's not efficient, then I try to send data in the form of json which will later be saved into the database.

this data uses 2 unique ids which are associated with 2 other tables.

this is my previous code.

```<code>$validator = Validator::make($request->all(),[
             'nama_event'=>'required',
             'nama_lengkap' => 'required|string',
             'kehadiran'=>'boolean'
          ]);

if($validator->fails()){
    return $this->error('Gagal', 500, [$validator->errors()]);
}

$event = Event::where('nama',$request->nama_event)->get();
$anggota = Anggota::where('nama_lengkap',$request->nama_lengkap)->get();

$presensi = Presensi::create([
    'event_id' => $event[0]->id,
    'anggota_id' => $anggota[0]->id,
    'kehadiran' => $request->kehadiran,
]);
</code>```

and this is my current code

```<code>$result = [];
$datas = $request->data;
foreach ($datas['data'] as $data) {
    $event = Event::where('nama',$data['nama_event'])->get();
    $anggota = Anggota::where('nama_lengkap',$data['nama_lengkap'])->get();
    $result[] = [
        'event_id'  => $event[0]->id,
        'anggota_id' => $anggota[0]->id,
        'kehadiran' => $data['kehadiran'],
    ];
}

$presensi = Presensi::insert($result);
</code>```

but i got an error like this.

```<code>"message": "Trying to access array offset on value of type null",
"exception": "ErrorException",
</code>```

this is the JSON format I use

```<code>{
"data": {
    "data": [
      {
        "nama_event": "event 1",
        "nama_lengkap": "user 1",
        "kehadiran": true
      },
      {
        "nama_event": "event 1",
        "nama_lengkap": "user 2",
        "kehadiran": false
      }
    ]
  }
}
</code>```

and, also I confuse how to deal with validator if using array.
does anyone know what's wrong with my code?

答:
I replicated issue that you are facing and i hope that this helps.

There is no need to use get() and return collectoin and then access 0th element. Use first() that is returing single model instead. So you should try something like :

```<code>$result = [];
    $datas = $request->data;
    foreach ($datas->data as $data) {
        $event = Event::where('nama',$data->nama_event)->first();
        $anggota = Anggota::where('nama_lengkap',$data->nama_lengkap)->first();
        $kehadiran = $data->kehadiran;
        $result[] =[
            'event_id'  => $event->id,
            'anggota_id' => $anggota->id,
            'kehadiran' => $kehadiran,
        ];
    }

$presensi = Presensi::insert($result);
</code>```

Body:
previously, I have created a function to send data and it worked. but the data input method is only one by one.

and I think it's not efficient, then I try to send data in the form of json which will later be saved into the database.

this data uses 2 unique ids which are associated with 2 other tables.

this is my previous code.

$validator = Validator::make($request->all(),[
             'nama_event'=>'required',
             'nama_lengkap' => 'required|string',
             'kehadiran'=>'boolean'
          ]);

if($validator->fails()){
    return $this->error('Gagal', 500, [$validator->errors()]);
}

$event = Event::where('nama',$request->nama_event)->get();
$anggota = Anggota::where('nama_lengkap',$request->nama_lengkap)->get();

$presensi = Presensi::create([
    'event_id' => $event[0]->id,
    'anggota_id' => $anggota[0]->id,
    'kehadiran' => $request->kehadiran,
]);

and this is my current code

$result = [];
$datas = $request->data;
foreach ($datas['data'] as $data) {
    $event = Event::where('nama',$data['nama_event'])->get();
    $anggota = Anggota::where('nama_lengkap',$data['nama_lengkap'])->get();
    $result[] = [
        'event_id'  => $event[0]->id,
        'anggota_id' => $anggota[0]->id,
        'kehadiran' => $data['kehadiran'],
    ];
}

$presensi = Presensi::insert($result);

but i got an error like this.

"message": "Trying to access array offset on value of type null",
"exception": "ErrorException",

this is the JSON format I use

{
"data": {
    "data": [
      {
        "nama_event": "event 1",
        "nama_lengkap": "user 1",
        "kehadiran": true
      },
      {
        "nama_event": "event 1",
        "nama_lengkap": "user 2",
        "kehadiran": false
      }
    ]
  }
}

and, also I confuse how to deal with validator if using array.
does anyone know what's wrong with my code?

Body:
I replicated issue that you are facing and i hope that this helps.

There is no need to use get() and return collectoin and then access 0th element. Use first() that is returing single model instead. So you should try something like :

$result = [];
    $datas = $request->data;
    foreach ($datas->data as $data) {
        $event = Event::where('nama',$data->nama_event)->first();
        $anggota = Anggota::where('nama_lengkap',$data->nama_lengkap)->first();
        $kehadiran = $data->kehadiran;
        $result[] =[
            'event_id'  => $event->id,
            'anggota_id' => $anggota->id,
            'kehadiran' => $kehadiran,
        ];
    }

$presensi = Presensi::insert($result);


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

couses:

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

instructors:

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

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

For instance your output would look something like this

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

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

答:
Not the best query in the world, but in all it's ugliness, I kind of like it.  Specifically, I like the fact that you don't have to deal with multiple case statements, which can be a pain if you have many fields on which you have to apply the case to:</p>

```<code>--- Single instructor case.
select
    c.id as courseId, i.instructor as instructor1, null as instructor2
from
    courses as c inner join instructors as i on i.courseId = c.id
where
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) = 1
union
--- Committee case.
select
    c.id as courseId, "committee" as instructor1, null as instructor2
from
    courses as c inner join instructors as i on i.courseId = c.id
where
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) > 2
union
--- Two instructor case.
select
    c.id as courseId, i1.instructor as instructor1,
    i2.instructor as instructor2
from
    courses as c, instructor as i1, instructor as i2
where
    --- Course ids must match.
    c.id = i1.courseId and c.id = i2.courseId and

    --- Instructor ids do not match.
    i1.id <> i2.id and

    --- There are only two instructors.
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) > 2
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

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

couses:

id (INT),
courseName (VARCHAR)

instructors:

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

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

For instance your output would look something like this

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

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

Body:
Not the best query in the world, but in all it's ugliness, I kind of like it.  Specifically, I like the fact that you don't have to deal with multiple case statements, which can be a pain if you have many fields on which you have to apply the case to:

--- Single instructor case.
select
    c.id as courseId, i.instructor as instructor1, null as instructor2
from
    courses as c inner join instructors as i on i.courseId = c.id
where
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) = 1
union
--- Committee case.
select
    c.id as courseId, "committee" as instructor1, null as instructor2
from
    courses as c inner join instructors as i on i.courseId = c.id
where
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) > 2
union
--- Two instructor case.
select
    c.id as courseId, i1.instructor as instructor1,
    i2.instructor as instructor2
from
    courses as c, instructor as i1, instructor as i2
where
    --- Course ids must match.
    c.id = i1.courseId and c.id = i2.courseId and

    --- Instructor ids do not match.
    i1.id <> i2.id and

    --- There are only two instructors.
    (
        select
            count(instructor)
        from
            instructors as i2
        where
            i2.courseId = c.id
    ) > 2

OwnerDisplayName: casperOne


问:
How to cancel a UIWebView?
I'm modally presenting a UIViewController with a UIWebView as its view. How do I dismiss the UIWebView when the user hits a cancel button on it?

One idea I have is to have the cancel button link to http://cancel and then check in

```<code>- (void)webViewDidStartLoad:(UIWebView *)webView
</code>```

If webView.request.URL.host isEqualToString:@"cancel", then dismiss the view controller.

Does the host have to have a dot in it, e.g., "cancel.com"?

答:
You're on the right path, but you're approach is slightly off. You don't need or want this to be an HTTP URL. Make your URL cancel:.

```<code><a href="cancel:">Thing to click</a>
</code>```

Then implement webView:shouldStartLoadWithRequest:navigationType: in your web view delegate. Something like this (untested):

```<code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([request.URL.scheme isEqualToString:@"cancel"]) {
        [self dismissModalViewControllerAnimated:YES];
        return NO;
    }
    return YES;
}
</code>```

Title: How to cancel a UIWebView?

Body:
I'm modally presenting a UIViewController with a UIWebView as its view. How do I dismiss the UIWebView when the user hits a cancel button on it?

One idea I have is to have the cancel button link to http://cancel and then check in

- (void)webViewDidStartLoad:(UIWebView *)webView

If webView.request.URL.host isEqualToString:@"cancel", then dismiss the view controller.

Does the host have to have a dot in it, e.g., "cancel.com"?

Body:
You're on the right path, but you're approach is slightly off. You don't need or want this to be an HTTP URL. Make your URL cancel:.

<a href="cancel:">Thing to click</a>

Then implement webView:shouldStartLoadWithRequest:navigationType: in your web view delegate. Something like this (untested):

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([request.URL.scheme isEqualToString:@"cancel"]) {
        [self dismissModalViewControllerAnimated:YES];
        return NO;
    }
    return YES;
}


问:
Why does my RigidBody Z direction not move? Unity
So i'm using this code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            rb.velocity = new Vector3(0, 5, 0);
        }

        if (Input.GetKey("up"))
        {
            Debug.Log("pressed");
            rb.velocity = new Vector3(0, 0, 5);

        }
    }
}
</code>```

Fairly simple, when I pres space the player jumps. When I press the up key, I get a log in the console but the player doesnt move at all. I'm stumped, been debugging for a while now.

Anybody that knows why?

Following this tutorial by the way: https://youtu.be/54qz4SyQWZM?list=PLrnPJCHvNZuB5ATsJZLKX3AW4V9XaIV9b&t=2265

Edit: Here are my object settings https://gyazo.com/3ec3a192b401f6335547beb84e07d8fb

答:
Fixed it! Had to disable "Apply Root Motion" on my player object animator.

https://gyazo.com/401c5f12b5bb4cf5aab1f0d94990353b

Body:
So i'm using this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            rb.velocity = new Vector3(0, 5, 0);
        }

        if (Input.GetKey("up"))
        {
            Debug.Log("pressed");
            rb.velocity = new Vector3(0, 0, 5);

        }
    }
}

Fairly simple, when I pres space the player jumps. When I press the up key, I get a log in the console but the player doesnt move at all. I'm stumped, been debugging for a while now.

Anybody that knows why?

Following this tutorial by the way: https://youtu.be/54qz4SyQWZM?list=PLrnPJCHvNZuB5ATsJZLKX3AW4V9XaIV9b&t=2265

Edit: Here are my object settings https://gyazo.com/3ec3a192b401f6335547beb84e07d8fb


问:
Can't change color of a "Leading Icon" of a ListTile in Flutter
I have a Drawer with a ListView, inside that I have the ListTiles. In every ListTile there is a leading element, the Icon. I want to change the color of all Icons inside ListTiles from my ThemeData. I tried however it doesn't work.

Here is my current code (the class only):

```<code>class _UniversalConverter extends State<UniversalConverter> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.blue),
        ),
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Universal Converter"),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('Home'),
                  leading: const Icon(Icons.home),
                  onTap: () {},
                ),
                ListTile(
                  title: const Text('Angle'),
                  leading: const Icon(Icons.block),
                  onTap: () {},
                ),
              ],
            ),
          ),
        ));
  }
}
</code>```

As you can see I have the iconTheme: const IconThemeData(color: Colors.blue), but it doesn't do anything.

Any help would be appreciated,
Thanks!

答:
Icon itself having a property called color. Consider below code snippet.

```<code>ListTile(
title: Text('Hi'),
leading: Icon(Icons.block,
color : Colors.orange,
),
onTap: () {
// To do
</code>```

},
),

Body:
I have a Drawer with a ListView, inside that I have the ListTiles. In every ListTile there is a leading element, the Icon. I want to change the color of all Icons inside ListTiles from my ThemeData. I tried however it doesn't work.

Here is my current code (the class only):

class _UniversalConverter extends State<UniversalConverter> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.blue),
        ),
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Universal Converter"),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('Home'),
                  leading: const Icon(Icons.home),
                  onTap: () {},
                ),
                ListTile(
                  title: const Text('Angle'),
                  leading: const Icon(Icons.block),
                  onTap: () {},
                ),
              ],
            ),
          ),
        ));
  }
}

As you can see I have the iconTheme: const IconThemeData(color: Colors.blue), but it doesn't do anything.

Any help would be appreciated,
Thanks!

Body:
Icon itself having a property called color. Consider below code snippet.

ListTile(
title: Text('Hi'),
leading: Icon(Icons.block,
color : Colors.orange,
),
onTap: () {
// To do

},
),


问:
Combine duplicates inside a list of dicts
How do I combine the values of the duplicates keys of the dictionary inside of this list?

lst = [{'CR Dashboard Group': 'Secure Servers', 'InstanceList': ['i-02424438d45214e92']},
{'CR Dashboard Group': 'IPA Servers', 'InstanceList': ['i-077ac3525e56a8c5f']},
{'CR Dashboard Group': 'Secure Servers', 'InstanceList': ['i-0d8c63982972b52bc']}]
```
<p>Desired outcome is:</p>
<pre class="lang-py prettyprint-override"><code>lst = [
{'Crossroads Dashboard Group': 'Secure Servers', 'InstanceList': ['i-02401438d45214e92', 'i-0d8c63992972b52bc']},
{'Crossroads Dashboard Group': 'IPA Servers', 'InstanceList': ['i-077ac3525ee8a8c5f']}]
</code>```

答:
First, collect into a dict of which uses (consistently ordered) tuples to store hashable data. Then, convert that to the desired representation.

```<code>from collections import defaultdict

def combine(ds):
    instances = defaultdict(list)

    for d in ds:
        key = tuple((k, d[k]) for k in sorted(d.keys()) if k != "InstanceList")
        instances[key].extend(d["InstanceList"])

    return [{**dict(k), "InstanceList": v} for k, v in instances.items()]
</code>```

Test:

```<code>ds = [
    {"server": "A", "InstanceList": ["A1", "A2"]},
    {"server": "A", "InstanceList": ["A3", "A4"]},
    {"server": "B", "InstanceList": ["B1", "B2"]},
]

>>> combine(ds)
[
    {'server': 'A', 'InstanceList': ['A1', 'A2', 'A3', 'A4']},
    {'server': 'B', 'InstanceList': ['B1', 'B2']},
]
</code>```

Body:
How do I combine the values of the duplicates keys of the dictionary inside of this list?

lst = [{'CR Dashboard Group': 'Secure Servers', 'InstanceList': ['i-02424438d45214e92']},
{'CR Dashboard Group': 'IPA Servers', 'InstanceList': ['i-077ac3525e56a8c5f']},
{'CR Dashboard Group': 'Secure Servers', 'InstanceList': ['i-0d8c63982972b52bc']}]

Desired outcome is:

lst = [
{'Crossroads Dashboard Group': 'Secure Servers', 'InstanceList': ['i-02401438d45214e92', 'i-0d8c63992972b52bc']},
{'Crossroads Dashboard Group': 'IPA Servers', 'InstanceList': ['i-077ac3525ee8a8c5f']}]

Body:
First, collect into a dict of which uses (consistently ordered) tuples to store hashable data. Then, convert that to the desired representation.

from collections import defaultdict

def combine(ds):
    instances = defaultdict(list)

    for d in ds:
        key = tuple((k, d[k]) for k in sorted(d.keys()) if k != "InstanceList")
        instances[key].extend(d["InstanceList"])

    return [{**dict(k), "InstanceList": v} for k, v in instances.items()]

Test:

ds = [
    {"server": "A", "InstanceList": ["A1", "A2"]},
    {"server": "A", "InstanceList": ["A3", "A4"]},
    {"server": "B", "InstanceList": ["B1", "B2"]},
]

>>> combine(ds)
[
    {'server': 'A', 'InstanceList': ['A1', 'A2', 'A3', 'A4']},
    {'server': 'B', 'InstanceList': ['B1', 'B2']},
]


问:
Running npm command within Visual Studio Code
Is there anyway of executing the npm command within Visual Studio Code (using f1 into >) on Windows(10) to install packages to my folder I'm working in?

I have npm installed and I keep having to install npm packages from cmd

答: I restarted my machine, after checking the path in environment variable. it worked for me.</p>


问:
I made a Student registration program using arraylist in Java and had problems in arranging the result in descending order by Percentage
When I run the option to sort the results, the first 2 are in correct form but the remaining are just the copy of the 2nd detail. The other functions run fairly smoothly, the only problem I am facing is with the sort() function. I have given it much thoughts to no avail.

import java.util.ArrayList;
import java.util.Scanner;

class Test {

    public static int totaln=0;
    public static ArrayList<String> fname;
    public static ArrayList<String> lname;
    public static ArrayList<String> dob;
    public static ArrayList<String> gender;
    public static ArrayList<Integer> standard;
    public static ArrayList<Integer> rollno;
    public static ArrayList<Float> maths;
    public static ArrayList<Float> science;
    public static ArrayList<Float> social;
    public static ArrayList<Float> eng;
    public static ArrayList<Float> percentage ;

     public static void entry() {

        int num;

        Scanner sc=new Scanner(System.in);
         fname= new ArrayList<>();
         lname= new ArrayList<>();
         dob= new ArrayList<>();
         gender= new ArrayList<>();
         standard= new ArrayList<>();
         rollno= new ArrayList<>();
         maths =new ArrayList<>();
         science = new ArrayList<>();
         social = new ArrayList<>();
         eng = new ArrayList<>();
         percentage = new ArrayList<>();

        System.out.print("Enter the number of students: ");
        num = sc.nextInt();
        if(num==0 || num<0){
            System.out.println("Invalid Entry.");
        }
           else {
                for (int i = 0; i < num; i++) {
                    System.out.println();
                    System.out.println("Student: " +(i+1));
                    System.out.print("Enter the standard: ");
                    standard.add(sc.nextInt());
                    System.out.print("Enter the first name: ");
                    fname.add(sc.next());
                    System.out.print("Enter the last name: ");
                    lname.add(sc.next());
                    System.out.print("Enter the roll no: ");
                    rollno.add(sc.nextInt());
                    System.out.print("Enter the date of birth: ");
                    dob.add(sc.next());
                    System.out.print("Enter the gender: ");
                    gender.add(sc.next());
                    System.out.print("Enter the marks in Maths: ");
                    maths.add(sc.nextFloat());
                    System.out.print("Enter the marks in Science: ");
                    science.add(sc.nextFloat());
                    System.out.print("Enter the marks in Social: ");
                    social.add(sc.nextFloat());
                    System.out.print("Enter the marks in English: ");
                    eng.add(sc.nextFloat());
                    percentage.add((maths.get(i)+ science.get(i)+ social.get(i)+ eng.get(i))/4);
                }
                totaln+=num;

            }

    }
    public static void display(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Student Details");
            for (int i=0;i<totaln;i++){
                System.out.println();
                System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                System.out.println("Standard: "+standard.get(i));
                System.out.println("Roll no: " +rollno.get(i));
                System.out.println("Date of birth: " +dob.get(i));
                System.out.println("Gender: " +gender.get(i));
                System.out.println("Percentage: " +percentage.get(i));
            }

        }

    }
    public static void search(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Enter the roll no of the student to search: ");
            roll = sc.nextInt();
            int s=0;

            for(int i=0;i<totaln;i++){
                if(roll==rollno.get(i)){
                    s=s+1;
                    System.out.println();
                    System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                    System.out.println("Standard: "+standard.get(i));
                    System.out.println("Roll no: " +rollno.get(i));
                    System.out.println("Maths: "+maths.get(i));
                    System.out.println("Science: "+science.get(i));
                    System.out.println("Social: "+social.get(i));
                    System.out.println("English: "+eng.get(i));
                    System.out.println("Percentage: " +percentage.get(i));

                }

            }
            if(s>0) {
                System.out.println("Invalid entry. ");
            }
        }

    }
    public static void sort(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int c= percentage.size();
            for (int i=0; i<c-1; i++)
            {
                int pos = i;
                for (int j=i+1; j<c; j++)
                {
                    if (percentage.get(j) > percentage.get(pos))
                    {
                        pos = j;
                    }
                }
                float t1 = percentage.get(pos);
                percentage.add(pos, percentage.get(i)) ;
                percentage.add(i,t1);

                String f = fname.get(pos);
                fname.add(pos,fname.get(i));
                fname.add(i,f);

                String l = lname.get(pos);
                lname.add(pos,lname.get(i));
                lname.add(i,l);
            }
            System.out.println("The required order: ");

            for (int i=0;i<3;i++){
                System.out.println("Rank: " +(i+1));
                System.out.println("Percentage: "+percentage.get(i));
                System.out.println("Name: " +fname.get(i)+" "+lname.get(i));
            }

        }
    }

    public static void delete(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int choice;
            System.out.println("Enter 1 to delete all record:");
            System.out.println("Enter 2 to delete the record of a student");
            choice= sc.nextInt();
            if(choice==1){
                totaln=0;
                System.out.println("All the records have been deleted.");

            }
            else if(choice==2){
                System.out.println();
                System.out.println("Enter the roll no of the student you miss delete the record of: ");
                roll = sc.nextInt();

                for(int i=0;i<totaln;i++){
                    if(roll==rollno.get(i)){
                        for(int j=i;j<totaln;j++){
                            standard.remove(j);
                            fname.remove(j);
                            lname.remove(j);
                            rollno.remove(j);
                            dob.remove(j);
                            gender.remove(j);
                            percentage.remove(j);
                        }
                        totaln--;
                        System.out.println("The record has been deleted.");

                    }
                }

            }
            else {
                System.out.println("Invalid input.");
            }

        }

    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int value;
        char ch;
        do {
            System.out.println("Enter 1 to enter data.");
            System.out.println("Enter 2 to show data.");
            System.out.println("Enter 3 to search data.");
            System.out.println("Enter 4 to view the result in descending order: ");
            System.out.println("Enter 5 to delete data.");
            System.out.println("Enter 6 to exit.");
            System.out.println();
            System.out.print("Enter the value: ");
            value=sc.nextInt();
            switch(value){
                case 1:
                    entry();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    search();
                    break;
                case 4:
                    sort();
                    break;
                case 5:
                    delete();
                    break;
                case 6:
                    break;
                default:
                    System.out.println("Invalid input.");
                    break;
            }
            System.out.println("Do you want to continue(y/n): ");
            ch=sc.next().charAt(0);
        }while(ch=='y' || ch=='Y');
    }
}
```

答:
This is not a very good solution, you shouldn't use that many ArrayLists. Try creating a new Student Class, that has all the fields that you want, like first and last name, Birthday, gender, etc.

Then you could go through that process without using that many ArrayLists and just use student.setAge(sc.next())

Instead of having this many lists you would just have 1 list with all the student objects in it. You also don't need the totaln variable since you can use arraylist.length

Here is an example Student class

```<code>public class Student {

    private String fName;
    private String lName;
    private int age;

    public Student() {}

    public Student(String fName, String lName, int age) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
</code>```

Body:
This is not a very good solution, you shouldn't use that many ArrayLists. Try creating a new Student Class, that has all the fields that you want, like first and last name, Birthday, gender, etc.

Then you could go through that process without using that many ArrayLists and just use student.setAge(sc.next())

Instead of having this many lists you would just have 1 list with all the student objects in it. You also don't need the totaln variable since you can use arraylist.length

Here is an example Student class

public class Student {

    private String fName;
    private String lName;
    private int age;

    public Student() {}

    public Student(String fName, String lName, int age) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}


问:
GitHub Action use file of other branch?
The GitHub Action below performs two steps:

long.py fetches the data from an API and saves it but the data rarely changes

quick.py processes the saved data generated by long.py

name: build

on:
  workflow_dispatch:
  schedule:
    - cron: '0 2 * * *'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v2
        with:
          python-version: '3.x'
          cache: 'pip'
      - run: |
            pip install -r requirements.crawl.txt
            python py/long.py
            python py/quick.py

      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@4.1.5
        with:
          branch: gh-pages
          folder: dist
```

I do not want to overuse the API in long.py, but I want to execute quick.py on every push, so I want to create another action with a push trigger that only performs quick.py.
However that won't work because the resulting file from long.py is not existing on the master branch but it lives on the gh-pages branch.
What is the easiest way to provide quick.py with the last saved state of long.py from the gh-pages branch?

答:
Easiest way is to use caching:

https://github.com/actions/cache

You can use hash of your file as a key.

Title: GitHub Action use file of other branch?

Body:
The GitHub Action below performs two steps:

long.py fetches the data from an API and saves it but the data rarely changes

quick.py processes the saved data generated by long.py

name: build

on:
  workflow_dispatch:
  schedule:
    - cron: '0 2 * * *'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v2
        with:
          python-version: '3.x'
          cache: 'pip'
      - run: |
            pip install -r requirements.crawl.txt
            python py/long.py
            python py/quick.py

      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@4.1.5
        with:
          branch: gh-pages
          folder: dist

I do not want to overuse the API in long.py, but I want to execute quick.py on every push, so I want to create another action with a push trigger that only performs quick.py.
However that won't work because the resulting file from long.py is not existing on the master branch but it lives on the gh-pages branch.
What is the easiest way to provide quick.py with the last saved state of long.py from the gh-pages branch?


问:
The keydown function isn’t working for me
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.</p>
```<code> Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub
</code>```

答: Try changing the name of "Input" argument variable. Input is a VB command.

Body:
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.

 Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub


问:
how to get upcoming time in from the list of time?
I am building a website using create-react-app and I need to get the upcoming time from the list as compared to the current time.
my time list is

```<code>  let times = [
    {
      time: "05:33",
    },
    {
      time: "12:20",
    },
    {
      time: "15:23",
    },
    {
      time: "17:46",
    },
    {
      time: "19:08",
    },
  ];

</code>```

I have tried many solutions but all in vain, one solution that is also unsuccessful is

```<code>  const compareTime = moment().format("hh:mm");
  time7.map((item, i) => {
    console.log(
      Date.parse(
        `01/01/2011 ${format(parse(item.time, "HH:mm", new Date()), "hh:mm")}45`
      ) > Date.parse(`01/01/2011 ${compareTime}:10`)
    );
  });
</code>```

I am super stuck in this and trying to solve this problem for almost a week I need a proper solution to get the upcoming time from the list any kind of help will be appreciated.

答:
```<code>let currentTime = new Date();
currentTime = currentTime.getHours().toString().padStart(2, '0')
+ currentTime.getMinutes().toString().padStart(2, '0');
let futureTimes = times.filter((obj) => {
    return obj.time > currentTime;
})
.sort((a, b) => {
    return a.time < b.time ? -1 : a.time > b.time;
});

let nextTime = futureTimes.length ? future times[0] : null;
</code>```

I probably need to double check it and tweak, but coding on my mobile is a little tough.

Simpler solution:

```<code>let currentTime = new Date();
currentTime = currentTime.getHours().toString().padStart(2, '0')
+ currentTime.getMinutes().toString().padStart(2, '0');
let nextTime = times
.sort((a, b) => {
    return a.time < b.time ? -1 : a.time > b.time;
})
.find((obj) => {
    return obj.time > currentTime;
});
</code>```

Body:
I am building a website using create-react-app and I need to get the upcoming time from the list as compared to the current time.
my time list is

  let times = [
    {
      time: "05:33",
    },
    {
      time: "12:20",
    },
    {
      time: "15:23",
    },
    {
      time: "17:46",
    },
    {
      time: "19:08",
    },
  ];

I have tried many solutions but all in vain, one solution that is also unsuccessful is

  const compareTime = moment().format("hh:mm");
  time7.map((item, i) => {
    console.log(
      Date.parse(
        `01/01/2011 ${format(parse(item.time, "HH:mm", new Date()), "hh:mm")}45`
      ) > Date.parse(`01/01/2011 ${compareTime}:10`)
    );
  });

I am super stuck in this and trying to solve this problem for almost a week I need a proper solution to get the upcoming time from the list any kind of help will be appreciated.

Body:
let currentTime = new Date();
currentTime = currentTime.getHours().toString().padStart(2, '0')
+ currentTime.getMinutes().toString().padStart(2, '0');
let futureTimes = times.filter((obj) => {
    return obj.time > currentTime;
})
.sort((a, b) => {
    return a.time < b.time ? -1 : a.time > b.time;
});

let nextTime = futureTimes.length ? future times[0] : null;

I probably need to double check it and tweak, but coding on my mobile is a little tough.

Simpler solution:

let currentTime = new Date();
currentTime = currentTime.getHours().toString().padStart(2, '0')
+ currentTime.getMinutes().toString().padStart(2, '0');
let nextTime = times
.sort((a, b) => {
    return a.time < b.time ? -1 : a.time > b.time;
})
.find((obj) => {
    return obj.time > currentTime;
});


问:
Multiple lists inside a list nested for certain conditions
I am solving a problem from hackerrank that requires collections.ordereddict() to be used. In the program, I am supposed to take a bunch of input and store it in the ordereddict, sum the values of the duplicate items and represent it in order.
So for the first part, I wrote the following code which probably isn't the problem here..

```<code>ordi = OrderedDict()
N = int(input())
for i in range(N):
    item_info = input().split()
    if (len(item_info)>2):
        item_name = str(item_info[0]+" "+item_info[1])
        price = item_info[-1]
    else:
        item_name= str(item_info[0])
        price = item_info[-1]
    if item_name not in ordi:
        ordi[item_name]= price
    else:
        ordi[item_name]=[ordi[item_name]]
        ordi[item_name].append(price)
# print(ordi)

Test input given by hackerrank is:

9
BANANA FRIES 12
POTATO CHIPS 30
APPLE JUICE 10
CANDY 5
APPLE JUICE 10
CANDY 5
CANDY 5
CANDY 5
POTATO CHIPS 30
</code>```

the next part of the code loops through the dictionary and is supposed to give the output sum in order

```<code>for keys, values in ordi.items():
    total = 0
    if isinstance(values, list):
        print(f"this is what's inside {keys} value ",values)
        int_vals = list(map(int, values))
        total = sum(int_vals)
        print(keys, total)
    else:
        print(keys,values)
</code>```

This works for input that has two worded strings but doesn't work for one-worded strings i.e. Candy in this case. Now to debug what's inside of the value of candy key I printed it's values:

```<code>OUTPUT:
BANANA FRIES 12
this is what's inside POTATO CHIPS value  ['30', '30']
POTATO CHIPS 60
this is what's inside APPLE JUICE value  ['10', '10']
APPLE JUICE 20
this is what's inside CANDY value  [[['5', '5'], '5'], '5']
</code>```

As you can see, inside of the candy value, there is lists of lists inside of a list which is uncalled for, I can't understand what am I doing wrong.

答:
Here is a working solution:

```<code>ordi = OrderedDict()

N = int(input())
for i in range(N):
    item_info = input().split()

    item_name = " ".join(item_info[:-1])
    price = int(item_info[-1])

    if item_name not in ordi.keys():
        ordi[item_name] = price
    else:
        ordi[item_name] += price

print(ordi)
</code>```

Output:

```<code>OrderedDict([('BANANA FRIES', 12), ('POTATO CHIPS', 60), ('APPLE JUICE', 20), ('CANDY', 20)])
</code>```

I submit it in hackerrank and it passed the tests, I don't exactly know what was the problem with your code, but I think it has something to do with the way you handled adding the values to the dict,
this part:

```<code>    if item_name not in ordi:
        ordi[item_name]= price
    else:
        ordi[item_name]=[ordi[item_name]]
        ordi[item_name].append(price)
</code>```

I hope my solution will help you learn something new

if you want your code to work just do this:

```<code>    if item_name not in ordi.keys():
        ordi[item_name] = list(price)
    else:
        ordi[item_name].append(price)
</code>```

The problem was with this part: [ordi[item_name]] if the item was a list you warped it in another list, and since the "CANDY" key had the most inputs he was problematic, not because the key was one word.
When I enter custom input with a lot of POTATO CHIPS this is what I get:

```<code>this is what's inside BANANA FRIES value  ['12', '12']
BANANA FRIES 24
this is what's inside POTATO CHIPS value  [[['30', '30'], '30'], '30']
</code>```

Body:
I am solving a problem from hackerrank that requires collections.ordereddict() to be used. In the program, I am supposed to take a bunch of input and store it in the ordereddict, sum the values of the duplicate items and represent it in order.
So for the first part, I wrote the following code which probably isn't the problem here..

ordi = OrderedDict()
N = int(input())
for i in range(N):
    item_info = input().split()
    if (len(item_info)>2):
        item_name = str(item_info[0]+" "+item_info[1])
        price = item_info[-1]
    else:
        item_name= str(item_info[0])
        price = item_info[-1]
    if item_name not in ordi:
        ordi[item_name]= price
    else:
        ordi[item_name]=[ordi[item_name]]
        ordi[item_name].append(price)
# print(ordi)

Test input given by hackerrank is:

9
BANANA FRIES 12
POTATO CHIPS 30
APPLE JUICE 10
CANDY 5
APPLE JUICE 10
CANDY 5
CANDY 5
CANDY 5
POTATO CHIPS 30

the next part of the code loops through the dictionary and is supposed to give the output sum in order

for keys, values in ordi.items():
    total = 0
    if isinstance(values, list):
        print(f"this is what's inside {keys} value ",values)
        int_vals = list(map(int, values))
        total = sum(int_vals)
        print(keys, total)
    else:
        print(keys,values)

This works for input that has two worded strings but doesn't work for one-worded strings i.e. Candy in this case. Now to debug what's inside of the value of candy key I printed it's values:

OUTPUT:
BANANA FRIES 12
this is what's inside POTATO CHIPS value  ['30', '30']
POTATO CHIPS 60
this is what's inside APPLE JUICE value  ['10', '10']
APPLE JUICE 20
this is what's inside CANDY value  [[['5', '5'], '5'], '5']

As you can see, inside of the candy value, there is lists of lists inside of a list which is uncalled for, I can't understand what am I doing wrong.

Body:
Here is a working solution:

ordi = OrderedDict()

N = int(input())
for i in range(N):
    item_info = input().split()

    item_name = " ".join(item_info[:-1])
    price = int(item_info[-1])

    if item_name not in ordi.keys():
        ordi[item_name] = price
    else:
        ordi[item_name] += price

print(ordi)

Output:

OrderedDict([('BANANA FRIES', 12), ('POTATO CHIPS', 60), ('APPLE JUICE', 20), ('CANDY', 20)])

I submit it in hackerrank and it passed the tests, I don't exactly know what was the problem with your code, but I think it has something to do with the way you handled adding the values to the dict,
this part:

    if item_name not in ordi:
        ordi[item_name]= price
    else:
        ordi[item_name]=[ordi[item_name]]
        ordi[item_name].append(price)

I hope my solution will help you learn something new

if you want your code to work just do this:

    if item_name not in ordi.keys():
        ordi[item_name] = list(price)
    else:
        ordi[item_name].append(price)

The problem was with this part: [ordi[item_name]] if the item was a list you warped it in another list, and since the "CANDY" key had the most inputs he was problematic, not because the key was one word.
When I enter custom input with a lot of POTATO CHIPS this is what I get:

this is what's inside BANANA FRIES value  ['12', '12']
BANANA FRIES 24
this is what's inside POTATO CHIPS value  [[['30', '30'], '30'], '30']


问:
Group by using agg and count
I have the following group by in pandas

```<code>   df = df.groupby("pred_text1").agg({
        "rouge_score":"first","pred_text1":"first",
        "input_text":"first", "target_text":"first", "prefix":"first"})
</code>```

I want to have another columns which counts the number in each group (repetition of each pred_text)

I know that using transform('count') after groupby can add such a new column, but I still need agg function too.

答:
```<code>import pandas as pd
df = pd.DataFrame({'Group': ['G1', 'G1', 'G2', 'G3', 'G2', 'G1'], 'ValueLabel': [0, 1, 1, 1, 0, 2]})
</code>```

You can do this in a few steps:
First aggregate.

```<code>df = df.groupby('Group').agg({'ValueLabel': ['first', 'count']})
</code>```

The new columns are a pd.MultiIndex type which we will flatten. After that we can create a mapping of the names to the labels we want and rename the columns.

```<code>df.columns = df.columns.to_flat_index()
mapper = {label: new_label for label, new_label in zip \
         (pd.MultiIndex.from_product([['ValueLabel'], \
         ['first', 'count']]), ['ValueFirstLabel', 'ValueCountLabel'])}
df.rename(mapper, axis=1, inplace=True)
</code>```

Title: Group by using agg and count

Body:
I have the following group by in pandas

   df = df.groupby("pred_text1").agg({
        "rouge_score":"first","pred_text1":"first",
        "input_text":"first", "target_text":"first", "prefix":"first"})

I want to have another columns which counts the number in each group (repetition of each pred_text)

I know that using transform('count') after groupby can add such a new column, but I still need agg function too.

Body:
import pandas as pd
df = pd.DataFrame({'Group': ['G1', 'G1', 'G2', 'G3', 'G2', 'G1'], 'ValueLabel': [0, 1, 1, 1, 0, 2]})

You can do this in a few steps:
First aggregate.

df = df.groupby('Group').agg({'ValueLabel': ['first', 'count']})

The new columns are a pd.MultiIndex type which we will flatten. After that we can create a mapping of the names to the labels we want and rename the columns.

df.columns = df.columns.to_flat_index()
mapper = {label: new_label for label, new_label in zip \
         (pd.MultiIndex.from_product([['ValueLabel'], \
         ['first', 'count']]), ['ValueFirstLabel', 'ValueCountLabel'])}
df.rename(mapper, axis=1, inplace=True)


问:
Database design for comments and replies
I want to create two tables one with comments and another with replies, with a one to many relationship between them. But what if they can also reply to replies, how should it be changed then? This is what I have for the one to many, but I don't know how it should look if there can also be replies for a reply.

```<code>    Comments:
•   Id
•   Title
•   Text

    Replies:
•   Id
•   Title
•   Text
•   Comment id
</code>```

Thanks in advance.

答:
I have done the same for comment and comment replies. i have created same table and added parent_id column and managed with object association.

Below is the comment Entity:

public class Comment {

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "message")
private String message;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
        CascadeType.REFRESH})
@JoinColumn(name ="user_id")
private User user;

@OneToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
        CascadeType.REFRESH})
@JoinColumn(name="parent_id")
private List<Comment> replies;

public Comment(String message) {
    this.message = message;
}

public void addCommentReplies(Comment comment) {
    if(replies == null) {
        replies = new ArrayList<>();
    }
    replies.add(comment);
}
</code>```

}

Here is adding existing comment reference as parent_id and adding new commments  :

```<code>session.beginTransaction();

        int postId=1; // today is my birthday
        Post post = session.get(Post.class, postId);
        //add likes to the post

        Comment parentComment = session.get(Comment.class, 1);

        Comment replie1 = new Comment("First replied to comment - 1");

        Comment replie2 = new Comment("second replies to the comment - 2");

        int userId = 3;
        User user = session.get(User.class, userId);
        replie1.setUser(user);
        replie2.setUser(user);
        replie1.setPost(post);
        replie2.setPost(post);
        parentComment.addCommentReplies(replie1);
        parentComment.addCommentReplies(replie2);

        session.save(replie1);
        session.save(replie2);

        System.out.println("comment added successful..");

        session.getTransaction().commit();
</code>```

Body:
I want to create two tables one with comments and another with replies, with a one to many relationship between them. But what if they can also reply to replies, how should it be changed then? This is what I have for the one to many, but I don't know how it should look if there can also be replies for a reply.

    Comments:
•   Id
•   Title
•   Text

    Replies:
•   Id
•   Title
•   Text
•   Comment id

Thanks in advance.

Body:
I have done the same for comment and comment replies. i have created same table and added parent_id column and managed with object association.

Below is the comment Entity:

public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "message")
private String message;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
        CascadeType.REFRESH})
@JoinColumn(name ="user_id")
private User user;

@OneToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,
        CascadeType.REFRESH})
@JoinColumn(name="parent_id")
private List<Comment> replies;

public Comment(String message) {
    this.message = message;
}

public void addCommentReplies(Comment comment) {
    if(replies == null) {
        replies = new ArrayList<>();
    }
    replies.add(comment);
}

}

Here is adding existing comment reference as parent_id and adding new commments  :

session.beginTransaction();

        int postId=1; // today is my birthday
        Post post = session.get(Post.class, postId);
        //add likes to the post

        Comment parentComment = session.get(Comment.class, 1);

        Comment replie1 = new Comment("First replied to comment - 1");

        Comment replie2 = new Comment("second replies to the comment - 2");

        int userId = 3;
        User user = session.get(User.class, userId);
        replie1.setUser(user);
        replie2.setUser(user);
        replie1.setPost(post);
        replie2.setPost(post);
        parentComment.addCommentReplies(replie1);
        parentComment.addCommentReplies(replie2);

        session.save(replie1);
        session.save(replie2);

        System.out.println("comment added successful..");

        session.getTransaction().commit();


问:
How to convert binary array to decimal in C
I am trying to convert a binary array to decimal
Here is what i have to convert, binTodec[8] = {1,1,1,1,0,0,1,1}

I have started with
for(int i=0; i<8; i++)

Is there anybody that can help me

答:
```<code>unsigned toUnsigned(const int *arr, size_t size)
{
    unsigned result = 0;

    if(arr && size)
    {
        while(size--)
        {
            result *= 2;
            result += !!*arr++;
        }
    }
    return result;
}
</code>```


问:
MySQL REGEXP matching positive numbers
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

```<code>REGEXP '[^-,][0-9]+'
</code>```

but this pulls -886 as 88 matches the regexp

答:
^\b\d+\b$
will give you positive integers.

^[^-]\d+((,([^-]\d+))?)+$
will give you only the lists where all the values are positive integers

For a list with any positive integer (but all valid integers negative or positive) I thinks this will check out:
^((-\d+,)?)+[^-]\d+((,([^-]\d+))?|(,-\d+)?)+$

Here's a great site for Regular Expressions:
http://gskinner.com/RegExr/

I use it all the time for testing live.

Title: MySQL REGEXP matching positive numbers

Body:
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

REGEXP '[^-,][0-9]+'

but this pulls -886 as 88 matches the regexp


问:
Prisma Query doesn't log using all methods
I'm trying to debug what is wrong with a query as it doesn't return any results.

I'm trying the query logger using the following snippet, but no joy

const { PrismaClient } = require('@prisma/client')

const prisma = new PrismaClient({
    log: [
        {
            emit: "event",
            level: "query",
        },
    ],
});

prisma.$on("query", async (e) => {
    console.log(`${e.query} ${e.params}`)
});

module.exports = prisma
```
<p>I'm using express, but this should relate to this.</p>
<p>NODE_ENV=development</p>
<p>I have also tried this package: prisma-query-log
but also it doesn't work. What am I missing</p>
<p>This is the query:</p>
```const query = {
       skip: offset,
       take: limit,
    };
const filteredProperties = prisma.property.findMany(
        query
    )
```

答:
To actually start the query you need to await or call then after the query because prisma queries are lazy:

```<code>const filteredProperties = await prisma.property.findMany(query)
// or like that
prisma.property.findMany(query).then(filteredProperties => ...)
</code>```

Body:
I'm trying to debug what is wrong with a query as it doesn't return any results.

I'm trying the query logger using the following snippet, but no joy

const { PrismaClient } = require('@prisma/client')

const prisma = new PrismaClient({
    log: [
        {
            emit: "event",
            level: "query",
        },
    ],
});

prisma.$on("query", async (e) => {
    console.log(`${e.query} ${e.params}`)
});

module.exports = prisma

I'm using express, but this should relate to this.

NODE_ENV=development

I have also tried this package: prisma-query-log
but also it doesn't work. What am I missing

This is the query:

const query = {
       skip: offset,
       take: limit,
    };
const filteredProperties = prisma.property.findMany(
        query
    )

Body:
To actually start the query you need to await or call then after the query because prisma queries are lazy:

const filteredProperties = await prisma.property.findMany(query)
// or like that
prisma.property.findMany(query).then(filteredProperties => ...)