问:
Element with that ID already exists in the database
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

```<code>//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }
</code>```

Problem.java Entity class

```<code>@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

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

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
</code>```

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.

答:
Without looking at the Problem Entity it is a bit hard to understand the ID situation.

Just some advice. Take a look at: objectdb and Spring Guide and check the part about @Id annotation and how to use it. Also, keep in mind that without looking at your DB, having the DB already filled with that primary keys is a possibility. I would suggest you add a method to clear the DB after each run or to use H2 in memory.

Body:
I am working on a practice Spring Boot project that lists/adds/updates/deletes math problems from a mysql database. I am using Spring Boot with JPA to do the database operations. In my case, the db already has the problems and the button 'listproblems' returns all the buttons to a table. I can edit/delete without a problem. But when it comes to adding a new problem, I don't know how to add the new entry to the database. At this point, I don't know what to share but here is the current addProblem method:

//This is in the ProblemController.java on the server side application

@PostMapping("/post")
    public void addProduct(@RequestParam("cont") String pcont) {

        // Get a valid pid first
        Iterable<Problem> problist = probRepository.findAll();
        int min = 100000;
        int max = 0;
        int gap = 0;

        for (Problem myprod : problist) {
            if (myprod.getPid() < min) {
                min = myprod.getPid();
            }
            if (myprod.getPid() > max) {
                max = myprod.getPid();
            }
        }

        for (int i = min + 1; i < max; i++) {
            if (!probRepository.existsById(i)) {
                gap = i;
                break;
            }
        }

        if (gap == 0) {
            gap = max + 1;
        }

        System.out.println("max: " + max);

        max = max + 1;

        Problem prob = new Problem();
        prob.setPid(max);
        prob.setContent(pcont);
        probRepository.save(prob);
    }

Problem.java Entity class

@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer pid;

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

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

This function is basically iterating through the items to find the maximum index, then incrementing the index by 1 to get the next index. But It still doesn't work.

Please let me know if you want to see anything in particular to help me understand this.


来源: stackexchange

问:
How to split array in chunks of set size by value in javascript?
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
```

<p>I need to split that into parts like below:</p>

<pre class="lang-js prettyprint-override"><code>IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]
</code>```

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

```<code>var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});
</code>```

Output I get is below, it work to create only initial array than it don't do anything:

```<code> [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]
</code>```

答: Lodash already has a chunk function written for exactly this: Lodash Chunk Docs

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

I need to split that into parts like below:

IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});

Output I get is below, it work to create only initial array than it don't do anything:

 [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]


问:
Detect multiple strings in one df from strings in another df and, if detected, return the strings detected
I'm learning to use R, so please bear with me.

I have a dataset of google play store apps (master_tib). Each row is a play store app. There's a column titled description that contains text on what the app does.

```<code>master_tib

App     Description
App1    Reduce your depression and anxiety
App2    Help your depression
App3    This app helps with Anxiety
App4    Dog walker app 3000
</code>```

I also have a df of tags (master_tags) that contains words of importance I've predefined. There is a single column titled tag and each row contains a single tag.

```<code>master_tag

Tag
Depression
Anxiety
Stress
Mood
</code>```

My goal is to tag apps from the master_tib df with the tags in master_tags df based on the presence of the tag in the description. It will then print the tags in a new column.
The final result would be a master_tib df that looks like this:

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
App2    Help your depression                   depression
App3    This app helps with anxiety            anxiety
App4    Dog walker app 3000                    FALSE
</code>```

Below is what I've done so far using a combination of str_detect and mapply:

```<code># define function to use in mapply

detect_tag <- function(description, tag){
  if(str_detect(description, tag, FALSE)) {
    return (tag)
  } else {
    return (FALSE)
  }
}

index <-  mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)

master_tib[index,]
</code>```

Unfortunately, only the first tag is being passed through.

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression
</code>```

Instead of the desired:

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
</code>```

I haven't gotten as far as printing the results into a new column. Would love to hear anyone's insight or thoughts and apologize in advance for my poor R skills.

答:
You can combine the words from  master_tag using str_c and use str_extract_all to get all the words that match the pattern.

```<code>library(stringr)
master_tib$Tag <- sapply(str_extract_all(tolower(master_tib$Description),
              str_c('\\b', tolower(master_tag$Tag), '\\b', collapse = "|")),
              function(x) toString(unique(x)))
master_tib$Tag
#[1] "depression, anxiety" "depression"          "anxiety"             ""
</code>```

data

```<code>master_tag <- structure(list(Tag = c("Depression", "Anxiety", "Stress", "Mood"
)), class = "data.frame", row.names = c(NA, -4L))

master_tib <- structure(list(App = c("App1  ", "App2  ", "App3  ", "App4  "
), Description = c("Reduce your depression and anxiety", "Help your depression",
"This app helps with Anxiety", "Dog walker app 3000")), row.names = c(NA,
-4L), class = "data.frame")
</code>```

Body:
I'm learning to use R, so please bear with me.

I have a dataset of google play store apps (master_tib). Each row is a play store app. There's a column titled description that contains text on what the app does.

master_tib

App     Description
App1    Reduce your depression and anxiety
App2    Help your depression
App3    This app helps with Anxiety
App4    Dog walker app 3000

I also have a df of tags (master_tags) that contains words of importance I've predefined. There is a single column titled tag and each row contains a single tag.

master_tag

Tag
Depression
Anxiety
Stress
Mood

My goal is to tag apps from the master_tib df with the tags in master_tags df based on the presence of the tag in the description. It will then print the tags in a new column.
The final result would be a master_tib df that looks like this:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
App2    Help your depression                   depression
App3    This app helps with anxiety            anxiety
App4    Dog walker app 3000                    FALSE

Below is what I've done so far using a combination of str_detect and mapply:

# define function to use in mapply

detect_tag <- function(description, tag){
  if(str_detect(description, tag, FALSE)) {
    return (tag)
  } else {
    return (FALSE)
  }
}

index <-  mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)

master_tib[index,]

Unfortunately, only the first tag is being passed through.

App     Description                            Tag
App1    Reduce your depression and anxiety     depression

Instead of the desired:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety

I haven't gotten as far as printing the results into a new column. Would love to hear anyone's insight or thoughts and apologize in advance for my poor R skills.

Body:
You can combine the words from  master_tag using str_c and use str_extract_all to get all the words that match the pattern.

library(stringr)
master_tib$Tag <- sapply(str_extract_all(tolower(master_tib$Description),
              str_c('\\b', tolower(master_tag$Tag), '\\b', collapse = "|")),
              function(x) toString(unique(x)))
master_tib$Tag
#[1] "depression, anxiety" "depression"          "anxiety"             ""

data

master_tag <- structure(list(Tag = c("Depression", "Anxiety", "Stress", "Mood"
)), class = "data.frame", row.names = c(NA, -4L))

master_tib <- structure(list(App = c("App1  ", "App2  ", "App3  ", "App4  "
), Description = c("Reduce your depression and anxiety", "Help your depression",
"This app helps with Anxiety", "Dog walker app 3000")), row.names = c(NA,
-4L), class = "data.frame")


问:
Get the Default Gateway
I'm writing a program that shows the user their IP address, Subnet mask and Default gateway. I can get the first two, but for the last one, this is what I turned up:

```<code>GatewayIPAddressInformationCollection gwc =
    System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;
</code>```

That, of course, returns a collection of GatewayIPAddressInformation. So, if a computer has multiple gateways, how can I determine which is the default gateway?

In practice, I've only ever seen this collection contain a single entry, but since it's implemented as a collection, it stands to reason that some computers contain multiple gateways, none of which are marked as "Default". So is there a way to determine the default or is it all just guesswork?

答:
(Just after posting I noticed an earlier answer that mentioned the idea of using traceroute. I probably wouldn't have responded if I'd seen that. But I have included complete/compact code.)

Here's a different approach that finds the default gateway by using a traceroute type method. Ping an address on the internet (or other network you want to get to) with a TTL of 1, and let ping tell you what the first hop IP address was. That ought to be the gateway you're looking for.

I suppose this could go wrong if the gateway was configured not to reply to pings, but I don't think I've ever heard of a network set up that way.

Note: This routine kind-of even works if you pass it an IPV6 address. The potential issue is that it seems to return an IPV6 address with Global scope, rather than Link-Local scope. I don't have enough experience using IPV6 to know if that's good or bad. But I do know that the Windows ipconfig command displays the Link-Local IPV6 addresses of the interface gateway.

using System.Net
using System.Net.NetworkInformation

// ping internet address with ttl=1 and return address of host where ttl expired
public static IPAddress FindDefaultGateway(IPAddress netaddr = null)
{
    // user can provide an ip address that exists on the network they want to connect to,
    // or this routine will default to 1.1.1.1 (IP of a popular internet dns provider)
    if (netaddr is null)
        netaddr = IPAddress.Parse("1.1.1.1");

    PingReply reply = default;
    using var ping = new Ping();
    var options = new PingOptions(1, true); // ttl=1, dont fragment=true
    try {
        // I arbitrarily used a 200ms timeout; tune as you see fit.
        reply = ping.Send(netaddr, 200, new byte[0], options);
    }
    catch (PingException) {
        System.Diagnostics.Debug.WriteLine("Gateway not available");
        return default;
    }
    if (reply.Status != IPStatus.TtlExpired) {
        System.Diagnostics.Debug.WriteLine("Gateway not available");
        return default;
    }
    return reply.Address;
}
```

ContentLicense: CC BY-SA 3.0

Title: Get the Default Gateway

Body:
I'm writing a program that shows the user their IP address, Subnet mask and Default gateway. I can get the first two, but for the last one, this is what I turned up:

GatewayIPAddressInformationCollection gwc =
    System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;

That, of course, returns a collection of GatewayIPAddressInformation. So, if a computer has multiple gateways, how can I determine which is the default gateway?

In practice, I've only ever seen this collection contain a single entry, but since it's implemented as a collection, it stands to reason that some computers contain multiple gateways, none of which are marked as "Default". So is there a way to determine the default or is it all just guesswork?


问:
Error: Cannot add direct child without default aggregation defined for control sap.f.cards.Header
I'm trying to add the custom data aggregation to a card control header. I've tried a lot of things but nothing seems to work, I'm always getting the same error:

Cannot add direct child without default aggregation defined for control sap.f.cards.Header

I also tried attaching the aggregation through the controller an it worked fine but I need it in my XML view.

This is my code:

<mvc:View controllerName="Dashboard2.Dashboard2.controller.View2" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
   xmlns:f="sap.f" xmlns:w="sap.ui.integration.widgets" xmlns:card="sap.f.cards" xmlns:layout="sap.ui.layout"
   xmlns:core="sap.ui.core.customData" xmlns:viz.feeds="sap.viz.ui5.controls.common.feeds" xmlns:viz.data="sap.viz.ui5.data"
   xmlns:viz="sap.viz.ui5.controls">
   <ScrollContainer height="100%" width="100%" vertical="true">
      <f:GridContainer snapToRow="false" id="containerid">
         <f:layout>
            <f:GridContainerSettings rowSize="84px" columnSize="84px" gap="6px"/>
         </f:layout>
         <f:layoutXS>
            <f:GridContainerSettings rowSize="70px" columnSize="70px" gap="6px"/>
         </f:layoutXS>
         <f:Card class="sapUiMediumMargin" width="300px" height="23rem" id="batchlectura">
            <f:layoutData>
               <f:GridContainerItemLayoutData columns="4"/>
            </f:layoutData>
            <f:header>
               <card:Header title="{datos>Proceso}" subtitle="{path:'datos>Hora', formatter:'.formatter.Hour' }" iconSrc="sap-icon://insurance-house"
                  statusText="{path:'datos>Estatus', formatter:'.formatter.Estatus'}">
                  <customData>
                     <core:CustomData key="Name" value="Contactname"/>
                  </customData>
               </card:Header>
            </f:header>
            <f:content>
               <viz:VizFrame id="idVizFrame" uiConfig="{applicationSet:'fiori'}" height='100%' width="100%" vizType='column'>
                  <viz:dataset>
                     <viz.data:FlattenedDataset data="{datos>/results}">
                        <viz.data:dimensions>
                           <viz.data:DimensionDefinition name="Week" value="1"/>
                        </viz.data:dimensions>
                        <viz.data:measures>
                           <viz.data:MeasureDefinition name="Estimado" value="{datos>Estimado}"/>
                           <viz.data:MeasureDefinition name="Actual" value="{datos>Actual}"/>
                        </viz.data:measures>
                     </viz.data:FlattenedDataset>
                  </viz:dataset>
                  <viz:feeds>
                     <viz.feeds:FeedItem id='valueAxisFeed' uid="valueAxis" type="Measure" values="Estimado"/>
                     <viz.feeds:FeedItem id='valueAxisFeed2' uid="valueAxis" type="Measure" values="Actual"/>
                     <viz.feeds:FeedItem id='categoryAxisFeed' uid="categoryAxis" type="Dimension" values="Week"/>
                  </viz:feeds>
               </viz:VizFrame>
            </f:content>
         </f:Card>
      </f:GridContainer>
   </ScrollContainer>
</mvc:View>
```

Nothing seems to work.
I hope someone can help me.

答: I believe <customData> should be <card:customData> otherwise the default namespace which is sap/m will be used.

Body:
I'm trying to add the custom data aggregation to a card control header. I've tried a lot of things but nothing seems to work, I'm always getting the same error:

Cannot add direct child without default aggregation defined for control sap.f.cards.Header

I also tried attaching the aggregation through the controller an it worked fine but I need it in my XML view.

This is my code:

<mvc:View controllerName="Dashboard2.Dashboard2.controller.View2" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
   xmlns:f="sap.f" xmlns:w="sap.ui.integration.widgets" xmlns:card="sap.f.cards" xmlns:layout="sap.ui.layout"
   xmlns:core="sap.ui.core.customData" xmlns:viz.feeds="sap.viz.ui5.controls.common.feeds" xmlns:viz.data="sap.viz.ui5.data"
   xmlns:viz="sap.viz.ui5.controls">
   <ScrollContainer height="100%" width="100%" vertical="true">
      <f:GridContainer snapToRow="false" id="containerid">
         <f:layout>
            <f:GridContainerSettings rowSize="84px" columnSize="84px" gap="6px"/>
         </f:layout>
         <f:layoutXS>
            <f:GridContainerSettings rowSize="70px" columnSize="70px" gap="6px"/>
         </f:layoutXS>
         <f:Card class="sapUiMediumMargin" width="300px" height="23rem" id="batchlectura">
            <f:layoutData>
               <f:GridContainerItemLayoutData columns="4"/>
            </f:layoutData>
            <f:header>
               <card:Header title="{datos>Proceso}" subtitle="{path:'datos>Hora', formatter:'.formatter.Hour' }" iconSrc="sap-icon://insurance-house"
                  statusText="{path:'datos>Estatus', formatter:'.formatter.Estatus'}">
                  <customData>
                     <core:CustomData key="Name" value="Contactname"/>
                  </customData>
               </card:Header>
            </f:header>
            <f:content>
               <viz:VizFrame id="idVizFrame" uiConfig="{applicationSet:'fiori'}" height='100%' width="100%" vizType='column'>
                  <viz:dataset>
                     <viz.data:FlattenedDataset data="{datos>/results}">
                        <viz.data:dimensions>
                           <viz.data:DimensionDefinition name="Week" value="1"/>
                        </viz.data:dimensions>
                        <viz.data:measures>
                           <viz.data:MeasureDefinition name="Estimado" value="{datos>Estimado}"/>
                           <viz.data:MeasureDefinition name="Actual" value="{datos>Actual}"/>
                        </viz.data:measures>
                     </viz.data:FlattenedDataset>
                  </viz:dataset>
                  <viz:feeds>
                     <viz.feeds:FeedItem id='valueAxisFeed' uid="valueAxis" type="Measure" values="Estimado"/>
                     <viz.feeds:FeedItem id='valueAxisFeed2' uid="valueAxis" type="Measure" values="Actual"/>
                     <viz.feeds:FeedItem id='categoryAxisFeed' uid="categoryAxis" type="Dimension" values="Week"/>
                  </viz:feeds>
               </viz:VizFrame>
            </f:content>
         </f:Card>
      </f:GridContainer>
   </ScrollContainer>
</mvc:View>

Nothing seems to work.
I hope someone can help me.


问:
how to grey out bootstrap modal when a spinner is showing?
I the example below, use can open a modal, type a message and then send it... It would take 2 seconds to send the message... I would like to show a spinner (which is already working) but also I want to background of the modal to be greyed-out while spinner is showing...

$("#sendBtn").click(function() {
  $('.sending-message-spinner').show();
      setTimeout(function () {
        $("#myModal").modal("hide");
    }, 2000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
   width: 100%;
   height: 80px;
}

@keyframes loading {
   0% {
       transform: rotate(0);
   }
   100% {
      transform: rotate(360deg);
   }
}

.sending-message-spinner {
   position: fixed;
   text-align: center;
   z-index: 20;
   display: none;
   width: 40px;
   height: 40px;
   border: 8px solid #B0B0B0;
   border-radius: 50%;
   border-top-color: #000;
   animation: loading .75s linear infinite;
}</code>```

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

Modal Heading

          <button type="button" class="close" data-dismiss="modal">×</button>

type your message:

            <Textarea> </textarea>
            <button id='sendBtn' type="button" class="btn btn-primary">Send Message</button>

```

答:
You can add a class to CSS and have your JS call it when the button is clicked. I added to CSS .myClass and set the opacity in there, then called it in JS with $("#myModal").addClass('myClass'); to add that class to myModal when the button is clicked. See here:

UPDATE:  Here I did it with an overlay div inside myModal This will grey out the modal without making it transparent.

$("#sendBtn").click(function() {
  $("#overlay").show();
  $('.sending-message-spinner').show();
      setTimeout(function () {
        $("#myModal").modal("hide");
    }, 2000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
  width: 100%;
  height: 80px;
}

@keyframes loading {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}

.sending-message-spinner {
  position: fixed;
  text-align: center;
  z-index: 20;
  display: none;
  width: 64px;
  height: 64px;
  border: 8px solid #B0B0B0;
  border-radius: 50%;
  border-top-color: #000;
  animation: loading .75s linear infinite;
}

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 10;
}</code>```

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

Modal Heading

          <button type="button" class="close" data-dismiss="modal">×</button>

type your message:

            <Textarea> </Textarea>
            <button id='sendBtn' type="button" class="btn btn-primary">Send Message</button>

```

Body:
I the example below, use can open a modal, type a message and then send it... It would take 2 seconds to send the message... I would like to show a spinner (which is already working) but also I want to background of the modal to be greyed-out while spinner is showing...

$("#sendBtn").click(function() {
  $('.sending-message-spinner').show();
      setTimeout(function () {
        $("#myModal").modal("hide");
    }, 2000);
});

textarea {
   width: 100%;
   height: 80px;
}

@keyframes loading {
   0% {
       transform: rotate(0);
   }
   100% {
      transform: rotate(360deg);
   }
}

.sending-message-spinner {
   position: fixed;
   text-align: center;
   z-index: 20;
   display: none;
   width: 40px;
   height: 40px;
   border: 8px solid #B0B0B0;
   border-radius: 50%;
   border-top-color: #000;
   animation: loading .75s linear infinite;
}

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

Modal Heading

          <button type="button" class="close" data-dismiss="modal">×</button>

type your message:

            <Textarea> </textarea>
            <button id='sendBtn' type="button" class="btn btn-primary">Send Message</button>

Body:
You can add a class to CSS and have your JS call it when the button is clicked. I added to CSS .myClass and set the opacity in there, then called it in JS with $("#myModal").addClass('myClass'); to add that class to myModal when the button is clicked. See here:

UPDATE:  Here I did it with an overlay div inside myModal This will grey out the modal without making it transparent.

$("#sendBtn").click(function() {
  $("#overlay").show();
  $('.sending-message-spinner').show();
      setTimeout(function () {
        $("#myModal").modal("hide");
    }, 2000);
});

textarea {
  width: 100%;
  height: 80px;
}

@keyframes loading {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}

.sending-message-spinner {
  position: fixed;
  text-align: center;
  z-index: 20;
  display: none;
  width: 64px;
  height: 64px;
  border: 8px solid #B0B0B0;
  border-radius: 50%;
  border-top-color: #000;
  animation: loading .75s linear infinite;
}

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 10;
}

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

  <div class="modal" id="myModal">
  <div id="overlay"></div>
    <div class="modal-dialog">
      <div class="modal-content">
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Modal Heading</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <div class="modal-body">
          <div class="d-flex justify-content-center">
              <div class="feedback-position sending-message-spinner">
              </div>
            </div>
            <p>type your message: </p>
            <Textarea> </Textarea>
            <button id='sendBtn' type="button" class="btn btn-primary">Send Message</button>
        </div>
      </div>
    </div>
  </div>

</div>

</body>
</html>


问:
Entity Framework Core Error: No parameterless constructor defined for this object
At the point of creating a new MVC Controller:

after I click Add button, I get the following Error:

Here is my simple Context class:

```<code>  public class MainDbContext : DbContext
  {
    public MainDbContext(DbContextOptions<MainDbContext> options) : base(options)
    {
    }

    public DbSet<Todo> Todo { get; set; }

  }
</code>```

and my simple model:

```<code>public partial class Todo
{
    public int Id { get; set; }
    public string TaskName { get; set; }
}
</code>```

I have made some search on this issue, most of the posts point to a dropdown list or a SelectList method using MVC, but for my case it is a Controller creation fail, so it seems to be an Entity Framework Core issue

Any help ?

答:
Make sure your project builds and runs without errors before scaffolding.

In Visual Studio 2019, I received this error while attempting to scaffold a new controller because I had a missing comma in my JSON in appsettings.json file.

Eventually I built and tried to run and got a System.FormatException, "Could not parse the JSON file" during runtime.
Since appsettings.json was the only JSON file I was editing recently I knew it had to be appsettings.json.

Scaffolding, code generators, and EF migrations invoke runtime code, this means even if your code compiles, if it throws runtime errors those could cause a problem for such actions.

FYI -
As of EF Core 2.1 parameterized constructors are allowed.
See this Microsoft article for more information.
https://learn.microsoft.com/en-us/ef/core/modeling/constructors

Body:
At the point of creating a new MVC Controller:

after I click Add button, I get the following Error:

Here is my simple Context class:

  public class MainDbContext : DbContext
  {
    public MainDbContext(DbContextOptions<MainDbContext> options) : base(options)
    {
    }

    public DbSet<Todo> Todo { get; set; }

  }

and my simple model:

public partial class Todo
{
    public int Id { get; set; }
    public string TaskName { get; set; }
}

I have made some search on this issue, most of the posts point to a dropdown list or a SelectList method using MVC, but for my case it is a Controller creation fail, so it seems to be an Entity Framework Core issue

Any help ?


问:
Bugs with Java Drum Machine Midi project
I've copied the code from chapter 13 of the book Head First Java, page 420 to study and play around with, but the code doesn't seem to work as advertised.

First of all, the beat does not start at the first input on the GUI. If I place a cymbal splash on beat one to kick off the beat, and a snare on beat 3, the program plays back: Snare - splash.

Secondly, most sounds are not there, instead playing hihat or snare sounds. The Whistle, cowbell and maracass sounds play back hi hats.

Is there something that has changed in Java since this book was released, or are there bugs in the code written in the book. How do I change this code to play correctly and with the right sounds?

Thanks

```<code>import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;

    public class BeatBox {
        JPanel mainPanel;
        ArrayList<JCheckBox> checkboxList;
        Sequencer sequencer;
        Sequence sequence;
        Track track;
        JFrame theFrame;
        String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", "Open Hi-Hat","Acoustic Snare",
            "Crash Cymbal", "Hand Clap", "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", "Cowbell",
                "Vibraslap", "Low-mid Tom", "High Agogo", "Open Hi Conga" };

            int[]instruments={35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};

    public static void main(String[]args){new BeatBox().buildGUI();
            }
    public void buildGUI(){
            theFrame=new JFrame("Cyber BeatBox");
            theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            BorderLayout layout=new BorderLayout();
            JPanel background=new JPanel(layout);
            background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

            checkboxList=new ArrayList<JCheckBox>();
            Box buttonBox=new Box(BoxLayout.Y_AXIS);

            JButton start=new JButton("Start");
            start.addActionListener(new MyStartListener());
            buttonBox.add(start);

            JButton stop=new JButton("Stop");
            stop.addActionListener(new MyStopListener());
            buttonBox.add(stop);

            JButton upTempo=new JButton("Tempo Up");
            upTempo.addActionListener(new MyUpTempoListener());
            buttonBox.add(upTempo);

            JButton downTempo=new JButton("Tempo Down");
            downTempo.addActionListener(new MyDownTempoListener());buttonBox.add(downTempo);

            Box nameBox=new Box(BoxLayout.Y_AXIS);
            for(int i=0;i< 16;i++){
                    nameBox.add(new Label(instrumentNames[i]));
                    }

            background.add(BorderLayout.EAST,buttonBox);
            background.add(BorderLayout.WEST,nameBox);
            theFrame.getContentPane().add(background);

            GridLayout grid=new GridLayout(16,16);grid.setVgap(1);
            grid.setHgap(2);

            mainPanel=new JPanel(grid);
            background.add(BorderLayout.CENTER,mainPanel);

            for(int i=0;i< 256;i++){
                    JCheckBox c=new JCheckBox();
                    c.setSelected(false);
                    checkboxList.add(c);mainPanel.add(c);
                    } // end loop
            setUpMidi();

            theFrame.setBounds(50,50,300,300);
            theFrame.pack();
            theFrame.setVisible(true);
            } // close method

            public void setUpMidi(){
                    try{
                            sequencer=MidiSystem.getSequencer();
                            sequencer.open();
                            sequence=new Sequence(Sequence.PPQ,4);
                            track=sequence.createTrack();
                            sequencer.setTempoInBPM(120);

                    }catch(Exception e){ e.printStackTrace(); }
            } // close method

            public void buildTrackAndStart(){

            int[]trackList=null;
            sequence.deleteTrack(track);
            track=sequence.createTrack();

            for(int i=0;i<16;i++){
                    trackList=new int[16];
                    int key=instruments[i];
                    for(int j=0;j<16;j++){
                            JCheckBox jc=(JCheckBox)checkboxList.get(j+(16*i));
                            if(jc.isSelected()){
                            trackList[j]=key;
                            } else{
                                    trackList[j]=0;
                            }
                    } // close inner loop

                    makeTracks(trackList);
                    track.add(makeEvent(176,1,127,0,16));
            } // close outer

            track.add(makeEvent(192,9,1,0,15));

            try{
                    sequencer.setSequence(sequence);
                    sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
                    sequencer.start();
                    sequencer.setTempoInBPM(120);
            }catch(Exception e){
                    e.printStackTrace();
            }
            } // close buildTrackAndStart method

            public class MyStartListener implements ActionListener{

                    public void actionPerformed(ActionEvent a){
                            buildTrackAndStart();
                    }
            } // close inner class

            public class MyStopListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    sequencer.stop();}
            } // close inner class

            public class MyUpTempoListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    float tempoFactor=sequencer.getTempoFactor();
                    sequencer.setTempoFactor((float)(tempoFactor*1.03));
                    }
            } // close inner class

            public class MyDownTempoListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    float tempoFactor=sequencer.getTempoFactor();
                    sequencer.setTempoFactor((float)(tempoFactor*.97));
                    }
            } // close inner class

            public void makeTracks(int[]list){

                    for(int i=0;i<16;i++){
                    int key=list[i];
                    if(key!=0){
                            track.add(makeEvent(144,9,key,100,i));
                            track.add(makeEvent(128,9,key,100,i+1));
                            }
                    }
            }

            public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){

                    MidiEvent event=null;
                    try{
                    ShortMessage a=new ShortMessage();a.setMessage(comd,chan,one,two);
                    event=new MidiEvent(a,tick);
                    }catch(Exception e){
                            e.printStackTrace();}
                    return event;
                    }
    } // close class
</code>```

答:
I recall building this 10 years ago. I can't recall if it was 100% successful, and I can't find the project in any of my old Eclipse workspace archives. I think it mostly worked but also convinced me to avoid Java Midi. (Am more interested in synthesis, anyway.) I have a few miscellaneous notes and corrections I made to myself about the code in pencil, an old copy of the book, but I don't think any would cause the issues you are describing.

I am noticing that the code you are showing is different from the listing in the appendix of my edition (copyright 2003!). Maybe you have the second edition? Given that the code survived two editions, chances are that it was working pretty well at the time.

Have you checked their errata page? Be sure to check the unconfirmed errata as well. Also, did you type in the code yourself or import it?

Almost certainly the MIDI system that you are accessing with the program is laid out differently from the standard that used to be implemented on most PCs. I never did get a good handle on what sound cards or sound systems used which midi mappings to voices, but it sure sounds like the percussion mapping you are referencing is different. Your system may have more than one percussion set, so it could be a matter of checking out what you are accessing and whether it is a classic GM 1 Sound Set or not.

I seem to recall either or both authors Sierra and Bates had (or still have) an association with the forum Javaranch. You might have some luck cross posting there. If you get an answer from that site, please come back here and resolve this question.

Body:
I've copied the code from chapter 13 of the book Head First Java, page 420 to study and play around with, but the code doesn't seem to work as advertised.

First of all, the beat does not start at the first input on the GUI. If I place a cymbal splash on beat one to kick off the beat, and a snare on beat 3, the program plays back: Snare - splash.

Secondly, most sounds are not there, instead playing hihat or snare sounds. The Whistle, cowbell and maracass sounds play back hi hats.

Is there something that has changed in Java since this book was released, or are there bugs in the code written in the book. How do I change this code to play correctly and with the right sounds?

Thanks

import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;

    public class BeatBox {
        JPanel mainPanel;
        ArrayList<JCheckBox> checkboxList;
        Sequencer sequencer;
        Sequence sequence;
        Track track;
        JFrame theFrame;
        String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", "Open Hi-Hat","Acoustic Snare",
            "Crash Cymbal", "Hand Clap", "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", "Cowbell",
                "Vibraslap", "Low-mid Tom", "High Agogo", "Open Hi Conga" };

            int[]instruments={35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};

    public static void main(String[]args){new BeatBox().buildGUI();
            }
    public void buildGUI(){
            theFrame=new JFrame("Cyber BeatBox");
            theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            BorderLayout layout=new BorderLayout();
            JPanel background=new JPanel(layout);
            background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

            checkboxList=new ArrayList<JCheckBox>();
            Box buttonBox=new Box(BoxLayout.Y_AXIS);

            JButton start=new JButton("Start");
            start.addActionListener(new MyStartListener());
            buttonBox.add(start);

            JButton stop=new JButton("Stop");
            stop.addActionListener(new MyStopListener());
            buttonBox.add(stop);

            JButton upTempo=new JButton("Tempo Up");
            upTempo.addActionListener(new MyUpTempoListener());
            buttonBox.add(upTempo);

            JButton downTempo=new JButton("Tempo Down");
            downTempo.addActionListener(new MyDownTempoListener());buttonBox.add(downTempo);

            Box nameBox=new Box(BoxLayout.Y_AXIS);
            for(int i=0;i< 16;i++){
                    nameBox.add(new Label(instrumentNames[i]));
                    }

            background.add(BorderLayout.EAST,buttonBox);
            background.add(BorderLayout.WEST,nameBox);
            theFrame.getContentPane().add(background);

            GridLayout grid=new GridLayout(16,16);grid.setVgap(1);
            grid.setHgap(2);

            mainPanel=new JPanel(grid);
            background.add(BorderLayout.CENTER,mainPanel);

            for(int i=0;i< 256;i++){
                    JCheckBox c=new JCheckBox();
                    c.setSelected(false);
                    checkboxList.add(c);mainPanel.add(c);
                    } // end loop
            setUpMidi();

            theFrame.setBounds(50,50,300,300);
            theFrame.pack();
            theFrame.setVisible(true);
            } // close method

            public void setUpMidi(){
                    try{
                            sequencer=MidiSystem.getSequencer();
                            sequencer.open();
                            sequence=new Sequence(Sequence.PPQ,4);
                            track=sequence.createTrack();
                            sequencer.setTempoInBPM(120);

                    }catch(Exception e){ e.printStackTrace(); }
            } // close method

            public void buildTrackAndStart(){

            int[]trackList=null;
            sequence.deleteTrack(track);
            track=sequence.createTrack();

            for(int i=0;i<16;i++){
                    trackList=new int[16];
                    int key=instruments[i];
                    for(int j=0;j<16;j++){
                            JCheckBox jc=(JCheckBox)checkboxList.get(j+(16*i));
                            if(jc.isSelected()){
                            trackList[j]=key;
                            } else{
                                    trackList[j]=0;
                            }
                    } // close inner loop

                    makeTracks(trackList);
                    track.add(makeEvent(176,1,127,0,16));
            } // close outer

            track.add(makeEvent(192,9,1,0,15));

            try{
                    sequencer.setSequence(sequence);
                    sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
                    sequencer.start();
                    sequencer.setTempoInBPM(120);
            }catch(Exception e){
                    e.printStackTrace();
            }
            } // close buildTrackAndStart method

            public class MyStartListener implements ActionListener{

                    public void actionPerformed(ActionEvent a){
                            buildTrackAndStart();
                    }
            } // close inner class

            public class MyStopListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    sequencer.stop();}
            } // close inner class

            public class MyUpTempoListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    float tempoFactor=sequencer.getTempoFactor();
                    sequencer.setTempoFactor((float)(tempoFactor*1.03));
                    }
            } // close inner class

            public class MyDownTempoListener implements ActionListener{
                    public void actionPerformed(ActionEvent a){
                    float tempoFactor=sequencer.getTempoFactor();
                    sequencer.setTempoFactor((float)(tempoFactor*.97));
                    }
            } // close inner class

            public void makeTracks(int[]list){

                    for(int i=0;i<16;i++){
                    int key=list[i];
                    if(key!=0){
                            track.add(makeEvent(144,9,key,100,i));
                            track.add(makeEvent(128,9,key,100,i+1));
                            }
                    }
            }

            public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){

                    MidiEvent event=null;
                    try{
                    ShortMessage a=new ShortMessage();a.setMessage(comd,chan,one,two);
                    event=new MidiEvent(a,tick);
                    }catch(Exception e){
                            e.printStackTrace();}
                    return event;
                    }
    } // close class


问:
Simulating traffic signal (a single box)
I wanted to implement a traffic signal (a single box). I saw there were many questions in SO, but  I felt they were not complete code.

The below is the full source. I am using lock and condition for deciding which thread will actually run.

TrafficSignalSimulationUsingLock.java

```<code>package com.example.practice.third;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;
import com.example.practice.third.threads.GreenColorLightThread;
import com.example.practice.third.threads.RedColorLightThread;
import com.example.practice.third.threads.YellowColorLightThread;

public class TrafficSignalSimulationUsingLock {

    public static void main(String[] args) throws InterruptedException {

        TrafficLock lock = new TrafficLock();

        Condition condition = lock.newCondition();

        Thread redThread = new Thread(new RedColorLightThread(lock, condition));
        Thread yellowThread = new Thread(new YellowColorLightThread(lock, condition));
        Thread greenThread = new Thread(new GreenColorLightThread(lock, condition));

        redThread.start();

        Thread.sleep(300);

        yellowThread.start();
        greenThread.start();

        redThread.join();
        yellowThread.join();
        greenThread.join();
    }
}
</code>```

RedColorLightThread.java

```<code>package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class RedColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public RedColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isYellow() && trafficLock.isGreen()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    System.out.println("Red signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setYellow(true);
                trafficLock.setGreen(false);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}
</code>```

YellowColorLightThread.java

```<code>package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class YellowColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public YellowColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isRed() && trafficLock.isGreen()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 3; i++) {
                    System.out.println("Yellow signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setRed(false);
                trafficLock.setGreen(true);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}
</code>```

GreenColorLightThread.java

```<code>package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class GreenColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public GreenColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isRed() && trafficLock.isYellow()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    System.out.println("Green signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setRed(true);
                trafficLock.setYellow(false);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}
</code>```

TrafficLock.java

```<code>package com.example.practice.third.custom.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TrafficLock extends ReentrantLock {

    /**
     *
     */
    private static final long serialVersionUID = 7311233763066170670L;

    private boolean red = true;
    private boolean yellow = false;
    private boolean green = false;

    public TrafficLock() {
        super(true);
    }

    public boolean isRed() {
        return red;
    }

    public void setRed(boolean red) {
        this.red = red;
    }

    public boolean isYellow() {
        return yellow;
    }

    public void setYellow(boolean yellow) {
        this.yellow = yellow;
    }

    public boolean isGreen() {
        return green;
    }

    public void setGreen(boolean green) {
        this.green = green;
    }
}
</code>```

The below is sample output:

```<code>Red signal enabled
Red signal enabled
Red signal enabled
Red signal enabled
Red signal enabled
Yellow signal enabled
Yellow signal enabled
Yellow signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Red signal enabled
Red signal enabled
</code>```

Is this correct way of implementing (pls ignore space , time complexities).

Although this program gives result what I expect, I have a small doubt:

In each "color thread" (e.g. "RedColorLightThread"), the thread first sets the next desired state, followed by condition.signalAll() and in finally block releases the lock.

My doubt is, won't other threads get awake instantaneously when for example "red color thread" hasn't still released the lock?

答: The locks can only be held by one thread at a time. When you signal the other threads, you are telling them that they can wake and try to get the lock, but they will only move on when they get the lock. That only happens when the the other thread unlocks it. After that only of the waiting threads will wake and lock the lock, while the others keep waiting.</p>

Body:
I wanted to implement a traffic signal (a single box). I saw there were many questions in SO, but  I felt they were not complete code.

The below is the full source. I am using lock and condition for deciding which thread will actually run.

TrafficSignalSimulationUsingLock.java

package com.example.practice.third;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;
import com.example.practice.third.threads.GreenColorLightThread;
import com.example.practice.third.threads.RedColorLightThread;
import com.example.practice.third.threads.YellowColorLightThread;

public class TrafficSignalSimulationUsingLock {

    public static void main(String[] args) throws InterruptedException {

        TrafficLock lock = new TrafficLock();

        Condition condition = lock.newCondition();

        Thread redThread = new Thread(new RedColorLightThread(lock, condition));
        Thread yellowThread = new Thread(new YellowColorLightThread(lock, condition));
        Thread greenThread = new Thread(new GreenColorLightThread(lock, condition));

        redThread.start();

        Thread.sleep(300);

        yellowThread.start();
        greenThread.start();

        redThread.join();
        yellowThread.join();
        greenThread.join();
    }
}

RedColorLightThread.java

package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class RedColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public RedColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isYellow() && trafficLock.isGreen()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    System.out.println("Red signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setYellow(true);
                trafficLock.setGreen(false);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}

YellowColorLightThread.java

package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class YellowColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public YellowColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isRed() && trafficLock.isGreen()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 3; i++) {
                    System.out.println("Yellow signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setRed(false);
                trafficLock.setGreen(true);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}

GreenColorLightThread.java

package com.example.practice.third.threads;

import java.util.concurrent.locks.Condition;

import com.example.practice.third.custom.lock.TrafficLock;

public class GreenColorLightThread implements Runnable {

    private TrafficLock trafficLock;
    private Condition condition;

    public GreenColorLightThread(TrafficLock trafficLock, Condition condition) {
        this.trafficLock = trafficLock;
        this.condition = condition;
    }

    @Override
    public void run() {

        while (true) {
            try {
                trafficLock.lock();

                while (trafficLock.isRed() && trafficLock.isYellow()) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    System.out.println("Green signal enabled");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                trafficLock.setRed(true);
                trafficLock.setYellow(false);
                condition.signalAll();

            } finally {
                trafficLock.unlock();
            }
        }
    }
}

TrafficLock.java

package com.example.practice.third.custom.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TrafficLock extends ReentrantLock {

    /**
     *
     */
    private static final long serialVersionUID = 7311233763066170670L;

    private boolean red = true;
    private boolean yellow = false;
    private boolean green = false;

    public TrafficLock() {
        super(true);
    }

    public boolean isRed() {
        return red;
    }

    public void setRed(boolean red) {
        this.red = red;
    }

    public boolean isYellow() {
        return yellow;
    }

    public void setYellow(boolean yellow) {
        this.yellow = yellow;
    }

    public boolean isGreen() {
        return green;
    }

    public void setGreen(boolean green) {
        this.green = green;
    }
}

The below is sample output:

Red signal enabled
Red signal enabled
Red signal enabled
Red signal enabled
Red signal enabled
Yellow signal enabled
Yellow signal enabled
Yellow signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Green signal enabled
Red signal enabled
Red signal enabled

Is this correct way of implementing (pls ignore space , time complexities).

Although this program gives result what I expect, I have a small doubt:

In each "color thread" (e.g. "RedColorLightThread"), the thread first sets the next desired state, followed by condition.signalAll() and in finally block releases the lock.

My doubt is, won't other threads get awake instantaneously when for example "red color thread" hasn't still released the lock?


问:
Efficient way of labelling based on start and end position
I have 2 dataframes

```<code>das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))
</code>```

The expected output is

```<code>val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39
</code>```

I am able to get the expected output with following code

```<code>p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))
</code>```

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

Body:
I have 2 dataframes

das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))

The expected output is

val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39

I am able to get the expected output with following code

p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

Body:
Using R base:

encon <- function(x, y) {
  lower <- y[y[,1] == x[[2]], 2]
  upper <- y[y[,1] == x[[2]], 3]
  paste(as.character(x[[2]]), min(lower[x[[3]] >= lower & x[[3]] <= upper]), sep="_" )
}

for (i in seq(1, nrow(das))) das[i,"label"] <- encon(das[i,], mapper)
> das
   val type weigh label
1    1    A    20  A_19
2    2    A    22  A_19
3    3    A    23  A_19
4    4    A    32  A_27
5    5    A    34  A_27
6    6    A    54  A_37
7    7    B    19  B_17
8    8    B    22  B_17
9    9    B    24  B_17
10  10    B    26  B_25
11  11    B    31  B_25
12  12    B    34  B_25
13  13    B    36  B_25
14  14    B    37  B_25
15  15    B    51  B_50
16  16    B    54  B_50
17  17    C    31  C_23
18  18    C    35  C_33
19  19    C    43  C_39
20  20    C    45  C_39


问:
How to request user login in models or views
I am newbie in Django, and I can’t figure out how to get username through request. I’m working on vocabulary type site and I need that every entry user creates would have username.

Here is my models.py

```<code>from django.db import models

class EngDict(models.Model):

    orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово')
    translate = models.CharField(max_length=500,null=False,blank=False, verbose_name="Перевод")
    remarks = models.TextField(null=True, blank=True, verbose_name="Примечания")
    published_by = models.CharField(max_length=50, verbose_name="Добавлено")
    published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Дата добавления")
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория')

    class Meta:
        verbose_name = ("Перевод")
        verbose_name_plural = "Англо-русский словарь"
        ordering = ['-published_date']
</code>```

This is views.py

```<code>from django.shortcuts import render
from django.template import loader
from .models import EngDict, Category
from django.views.generic.edit import CreateView
from .forms import EngDictForm
from django.urls import reverse_lazy
from django.views.generic import TemplateView, ListView, FormView
from django.db.models import Q
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login

class EngDictCreateView(CreateView):
    template_name = 'dict/create.html'
    form_class = EngDictForm
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context
</code>```

I see that I need some function like def user_name(request) , but I can’t understand where i should write it and what must be inside of it. I need that published_by variable was automatically filled in with user login

Added exclude in forms.py

```<code>from django.forms import ModelForm
from .models import EngDict
from django import forms

class EngDictForm (ModelForm):
    def clean_orig_word(self):
        data = self.cleaned_data['orig_word']
        if EngDict.objects.filter(orig_word = data).count():
            raise forms.ValidationError("ТАКОЕ СЛОВО УЖЕ ЕСТЬ!")
        return data
    class Meta:
        model = EngDict
        fields = ('orig_word', 'translate', 'remarks', 'published_by')
        exclude =['published_by']
</code>```

答:
Please do not use a CharField for that. If later the user changes their username, then it refers to a user that no longer exists. To refer to another object, one uses a relation field like a ForeignKey [Django-doc], OneToOneField [Django-doc], or , ManyToManyField [Django-doc]. Here it looks like a ForeignKey is what you are looking for:

```<code>from django.conf import settings

class EngDict(models.Model):
    orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово')
    translate = models.CharField(max_length=500,null=False,blank=False, verbose_name='Перевод')
    remarks = models.TextField(null=True, blank=True, verbose_name='Примечания')
    published_by = models.<b>ForeignKey(</b>
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        editable=False,
        verbose_name='Добавлено'
    <b>)</b>
    published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Дата добавления')
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория')

    class Meta:
        verbose_name = ('Перевод')
        verbose_name_plural = 'Англо-русский словарь'
        ordering = ['-published_date']</code>```

In the form you should exclude published_by and in the CreateView, you can then "patch" the object with:

```<code>from django.contrib.auth.mixins import <b>LoginRequiredMixin</b>

class EngDictCreateView(LoginRequiredMixin, CreateView):
    template_name = 'dict/create.html'
    form_class = EngDictForm
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

    def form_valid(self, form):
        form<b>.instance.published_by = self.request.user</b>
        return super().form_valid(form)</code>```

Note: You can limit views to a class-based view to authenticated users with the
  LoginRequiredMixin mixin [Django-doc].

Body:
I am newbie in Django, and I can’t figure out how to get username through request. I’m working on vocabulary type site and I need that every entry user creates would have username.

Here is my models.py

from django.db import models

class EngDict(models.Model):

    orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово')
    translate = models.CharField(max_length=500,null=False,blank=False, verbose_name="Перевод")
    remarks = models.TextField(null=True, blank=True, verbose_name="Примечания")
    published_by = models.CharField(max_length=50, verbose_name="Добавлено")
    published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Дата добавления")
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория')

    class Meta:
        verbose_name = ("Перевод")
        verbose_name_plural = "Англо-русский словарь"
        ordering = ['-published_date']

This is views.py

from django.shortcuts import render
from django.template import loader
from .models import EngDict, Category
from django.views.generic.edit import CreateView
from .forms import EngDictForm
from django.urls import reverse_lazy
from django.views.generic import TemplateView, ListView, FormView
from django.db.models import Q
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login

class EngDictCreateView(CreateView):
    template_name = 'dict/create.html'
    form_class = EngDictForm
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

I see that I need some function like def user_name(request) , but I can’t understand where i should write it and what must be inside of it. I need that published_by variable was automatically filled in with user login

Added exclude in forms.py

from django.forms import ModelForm
from .models import EngDict
from django import forms

class EngDictForm (ModelForm):
    def clean_orig_word(self):
        data = self.cleaned_data['orig_word']
        if EngDict.objects.filter(orig_word = data).count():
            raise forms.ValidationError("ТАКОЕ СЛОВО УЖЕ ЕСТЬ!")
        return data
    class Meta:
        model = EngDict
        fields = ('orig_word', 'translate', 'remarks', 'published_by')
        exclude =['published_by']

Body:
Please do not use a CharField for that. If later the user changes their username, then it refers to a user that no longer exists. To refer to another object, one uses a relation field like a ForeignKey [Django-doc], OneToOneField [Django-doc], or , ManyToManyField [Django-doc]. Here it looks like a ForeignKey is what you are looking for:

from django.conf import settings

class EngDict(models.Model):
    orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово')
    translate = models.CharField(max_length=500,null=False,blank=False, verbose_name='Перевод')
    remarks = models.TextField(null=True, blank=True, verbose_name='Примечания')
    published_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        editable=False,
        verbose_name='Добавлено'
    )
    published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Дата добавления')
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория')

    class Meta:
        verbose_name = ('Перевод')
        verbose_name_plural = 'Англо-русский словарь'
        ordering = ['-published_date']

In the form you should exclude published_by and in the CreateView, you can then "patch" the object with:

from django.contrib.auth.mixins import LoginRequiredMixin

class EngDictCreateView(LoginRequiredMixin, CreateView):
    template_name = 'dict/create.html'
    form_class = EngDictForm
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

    def form_valid(self, form):
        form.instance.published_by = self.request.user
        return super().form_valid(form)

Note: You can limit views to a class-based view to authenticated users with the
  LoginRequiredMixin mixin [Django-doc].


问:
SQL: Query to get the last change in value of a specific column
So I have this table of product information. Each time a specific product is changed a new row is inserted with the new values, including time stamp and user who modified it.

To show the information I search for the latest row for a specific product (which is identified by a column which is product_id).

But now I need to know who was the last person that modified one specific column which is named status.

So let's say my table consists of this

So in essence I need to write a query that will tell me when was the last change for that given column.

```<code>product_id | name | status   | user | keyid
--------------------------------------------
598        | prrr | 0        | john | 10
598        | prod | 1        | jane | 11
456        | abcd | 2        | mac  | 12
598        | prdd | 2        | kate | 13
598        | rdpd | 2        | jane | 14
456        | prrr | 3        | john | 15
456        | abbb | 3        | kate | 16
</code>```

So the latest information for product 598 is

```<code>598 rdpd 2 jane 14
</code>```

BUT the last person that changed released is kate

The latest information for product 456 is

```<code>456 abbb 3 kate 16
</code>```

BUT the last person that changed released is john

So Ideally, I would want to write a query that would return

```<code>598 kate 13
456 john 15
</code>```

I don't even begin to have an Idea on how to write such query, so I'm wondering if anyone can help me out here.

答:
If your database does not support window functions, the logic is a bit more complicated.

As a starter, consider the following query, that gives you the first idkeys of rows that have the latest status per product_id:

```<code>select product_id, min(keyid)
from mytable t
where not exists (
    select 1
    from mytable t1
    where t1.product_id = t.product_id and t1.status <> t.status and t1.keyid > t.keyid
)
group by product_id
</code>```

This returns:

```
product_id | min(keyid)
---------: | ---------:
       598 |         13
       456 |         15
```

You can then use this resultset to filter the table:

```<code>select t.*
from mytable t
where t.keyid in (
    select min(keyid)
    from mytable t
    where not exists (
        select 1
        from mytable t1
        where t1.product_id = t.product_id and t1.status <> t.status and t1.keyid > t.keyid
    )
    group by product_id
)
</code>```

Results:

```
product_id | name | status | user | keyid
---------: | :--- | -----: | :--- | ----:
       598 | prdd |      2 | kate |    13
       456 | prrr |      3 | john |    15
```

Demo on DB Fiddle

Body:
So I have this table of product information. Each time a specific product is changed a new row is inserted with the new values, including time stamp and user who modified it.

To show the information I search for the latest row for a specific product (which is identified by a column which is product_id).

But now I need to know who was the last person that modified one specific column which is named status.

So let's say my table consists of this

So in essence I need to write a query that will tell me when was the last change for that given column.

product_id | name | status   | user | keyid
--------------------------------------------
598        | prrr | 0        | john | 10
598        | prod | 1        | jane | 11
456        | abcd | 2        | mac  | 12
598        | prdd | 2        | kate | 13
598        | rdpd | 2        | jane | 14
456        | prrr | 3        | john | 15
456        | abbb | 3        | kate | 16

So the latest information for product 598 is

598 rdpd 2 jane 14

BUT the last person that changed released is kate

The latest information for product 456 is

456 abbb 3 kate 16

BUT the last person that changed released is john

So Ideally, I would want to write a query that would return

598 kate 13
456 john 15

I don't even begin to have an Idea on how to write such query, so I'm wondering if anyone can help me out here.

Body:
If your database does not support window functions, the logic is a bit more complicated.

As a starter, consider the following query, that gives you the first idkeys of rows that have the latest status per product_id:

select product_id, min(keyid)
from mytable t
where not exists (
    select 1
    from mytable t1
    where t1.product_id = t.product_id and t1.status <> t.status and t1.keyid > t.keyid
)
group by product_id

This returns:

product_id | min(keyid)
---------: | ---------:
       598 |         13
       456 |         15

You can then use this resultset to filter the table:

select t.*
from mytable t
where t.keyid in (
    select min(keyid)
    from mytable t
    where not exists (
        select 1
        from mytable t1
        where t1.product_id = t.product_id and t1.status <> t.status and t1.keyid > t.keyid
    )
    group by product_id
)

Results:

product_id | name | status | user | keyid
---------: | :--- | -----: | :--- | ----:
       598 | prdd |      2 | kate |    13
       456 | prrr |      3 | john |    15

Demo on DB Fiddle


问:
Regex does not match the whole string
Following is the regular expression pattern I'm dealing with:

```<code>[\t\v\f ]*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)[\t\v\f ]*(?:\r?\n\s*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)\s*)*
</code>```

It basically tries to match key value pairs in a single section of a .ini file. So, for instance, it should be able to match the whole string below:

```<code>"aa = 11\nbb = 22\ncc = 33"
</code>```

I tried to test it on this regex matching website and some others as well and they all seem to match only the first 2 lines. Here is how the match looks like (global flag is disabled):

However when I try to force the regex to find all 3 lines as follows:

```<code>[\t\v\f ]*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)[\t\v\f ]*(?:\r?\n\s*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)\s*){2}
</code>```

Then it seems to be able to match the whole string.

Can anyone give me a good reason as to why the entire string above does not match my regex? Also what regex should I use in order to match all key value pairs in a string like the one I wrote above?

答: Your problem is the \s* at the end of the non-capturing group; this is being greedy and absorbing the vertical white-space at the end of the line containing bb = 22 and preventing the group matching again on the line with cc = 33 in it. Changing that to [\t\v\f ] (or even \s*?) makes the regex match the entire string as desired. See demo on regex101. The reason it works when you add the {2} quantifier is that the desire to match makes the engine backtrack when processing the \s* to a point where it can then match the non-capturing group again.

Title: Regex does not match the whole string

Body:
Following is the regular expression pattern I'm dealing with:

[\t\v\f ]*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)[\t\v\f ]*(?:\r?\n\s*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)\s*)*

It basically tries to match key value pairs in a single section of a .ini file. So, for instance, it should be able to match the whole string below:

"aa = 11\nbb = 22\ncc = 33"

I tried to test it on this regex matching website and some others as well and they all seem to match only the first 2 lines. Here is how the match looks like (global flag is disabled):

However when I try to force the regex to find all 3 lines as follows:

[\t\v\f ]*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)[\t\v\f ]*(?:\r?\n\s*([^=\s]+)[\t\v\f ]*=[\t\v\f ]*([^=\s]+)\s*){2}

Then it seems to be able to match the whole string.

Can anyone give me a good reason as to why the entire string above does not match my regex? Also what regex should I use in order to match all key value pairs in a string like the one I wrote above?


答:
You can split the multiline string on the line break (\n), use map to remove the first character from each line, and join on the line break to convert the array back to a string. This works no matter what character each line starts with.

const str = `| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|`;
const res = str.split("\n").map(s=>s.slice(1)).join("\n");
console.log(res);```

Title: Javascript Delete First Character on Each Line of String

Body:
I need to remove the first character of a string "|" on each line in javascript.

| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|

end results needed:

 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| Gbm| G| A|
 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| E| G| G A|
 D| Gbm|

This is the page I need to edit to get just the chords.
I removed the quotes with

tOut = tOut.replace("\"", "");

http://www.lesession.co.uk/abc/abcChordsOut.htm
This is the text input in ABC Notation format:

X:1
T:Guitar
L:1/8
K:D
Q:1/4=120
R:Medium Boogie
M:4/4
| "D"D,2 A,,D, D,2 [C,A,,]_B,,/2=B,,/2 | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,/2=D,/2_E,/2=E,/2 | "G"G,3 G, G,3 =G,, | "A"A,,3 A,, A,,2 B,,2 |
| "D"A,,3 =D,/2A,,/2 D,2 F,G, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,=D, | "A"A,2 G,A, A,E, A,,2 |
| "Bm"B,,2 =C,B,,/2A,,/2 B,,2 A,,2 | "Gbm"_G,3 _G,/2=F,/2 _G,2 _D,2 | "G"=G,3 =D, G,2 A,2 | "D"[D3^G,3] D D2 B,/2C/2A,/2^C,/2=C,/2 |
| "Bm"B,,3 B,,/2A,,/2 B,,3 F,,/2E,,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,/2G,,/2_B,,/2^G,,/2 | "A"A,,3 A,, A,,A,,=B,,C, |
| "D"D,3 D,/2A,,/2 D,2 A,2 | "Gbm"_G,,3 _G,,/2=F,,/2 _G,,3 E,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,3/2=C,/2 | "A"A,,4  z4 |
| "D" z3/2 B,,/2 ^C,D, A,,/2D,3/2- D,3/2A,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 _B,,=D, | "A"A,,3 A,, A,,2 E,,2 |
| "Bm"B,2 B,2 [B,3D,3] F, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 =B,,[=D,A,,-- ] | "D"[D,3A,,3] D,  z4 |
| "Bm" z4  z2  z F,/2=F,/2 | "E"E,,3 E,, E,,2 B,,E,,/2G,,/2- | "G"G,,2- G,,/2G,,E,,/2 G,,3/2B,,/2- B,,2 | "G"_A,/2G,3/2 B,G, "A"=A,2 A,,2 |
| "D" z8 | "Gbm" z8 |

after it has been formatted it is pasted into the Java app Impro-Visor to give the chords.


问:
Is it valid to have a html form inside another html form?
Is it valid html to have the following:

```<code><form action="a">
    <input.../>
    <form action="b">
        <input.../>
        <input.../>
        <input.../>
    </form>
    <input.../>
</form>
</code>```

So when you submit "b" you only get the fields within the inner form. When you submit "a" you get all fields minus those within "b".

If it isn't possible, what workarounds for this situation are available?

答:
A non-JavaScript workaround for nesting form tags:

Because you allow for

all fields minus those within "b".

when submitting "a", the following would work, using regular web-forms without fancy JavaScript tricks:

Step 1. Put each form on its own web page.

Step 2. Insert an iframe wherever you want this sub-form to appear.

Step 3. Profit.

I tried to use a code-playground website to show a demo, but many of them prohibit embedding their websites in iframes, even within their own domain.

OwnerDisplayName: FlyByQuestionGuy

LastEditorDisplayName: FlyByQuestionGuy

Body:
Is it valid html to have the following:

<form action="a">
    <input.../>
    <form action="b">
        <input.../>
        <input.../>
        <input.../>
    </form>
    <input.../>
</form>

So when you submit "b" you only get the fields within the inner form. When you submit "a" you get all fields minus those within "b".

If it isn't possible, what workarounds for this situation are available?


答:
Similar to @RonakShah's answer, but with base R:

apply(
  sapply(master_tag$Tag, grepl, master_tib$Description, ignore.case = TRUE),
  1, function(a) paste(master_tag$Tag[a], collapse = ","))
# [1] "Depression,Anxiety" "Depression"         "Anxiety"
# [4] ""
```

(and without lower-casing or "comma-space" niceties, that is easily added if desired).

Title: Detect multiple strings in one df from strings in another df and, if detected, return the strings detected

Body:
I'm learning to use R, so please bear with me.

I have a dataset of google play store apps (master_tib). Each row is a play store app. There's a column titled description that contains text on what the app does.

master_tib

App     Description
App1    Reduce your depression and anxiety
App2    Help your depression
App3    This app helps with Anxiety
App4    Dog walker app 3000

I also have a df of tags (master_tags) that contains words of importance I've predefined. There is a single column titled tag and each row contains a single tag.

master_tag

Tag
Depression
Anxiety
Stress
Mood

My goal is to tag apps from the master_tib df with the tags in master_tags df based on the presence of the tag in the description. It will then print the tags in a new column.
The final result would be a master_tib df that looks like this:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
App2    Help your depression                   depression
App3    This app helps with anxiety            anxiety
App4    Dog walker app 3000                    FALSE

Below is what I've done so far using a combination of str_detect and mapply:

# define function to use in mapply

detect_tag <- function(description, tag){
  if(str_detect(description, tag, FALSE)) {
    return (tag)
  } else {
    return (FALSE)
  }
}

index <-  mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)

master_tib[index,]

Unfortunately, only the first tag is being passed through.

App     Description                            Tag
App1    Reduce your depression and anxiety     depression

Instead of the desired:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety

I haven't gotten as far as printing the results into a new column. Would love to hear anyone's insight or thoughts and apologize in advance for my poor R skills.

Body:
Similar to @RonakShah's answer, but with base R:

apply(
  sapply(master_tag$Tag, grepl, master_tib$Description, ignore.case = TRUE),
  1, function(a) paste(master_tag$Tag[a], collapse = ","))
# [1] "Depression,Anxiety" "Depression"         "Anxiety"
# [4] ""

(and without lower-casing or "comma-space" niceties, that is easily added if desired).


问:
How to show Page Loading div until the page has finished loading?
I have a section on our website that loads quite slowly as it's doing some intensive calls.

Any idea how I can get a div to say something similar to "loading" to show while the page prepares itself and then vanish when everything is ready?

答:
This will be in synchronisation with an api call, When the api call is triggered, the loader is shown. When the api call is succesful, the loader is removed. This can be used for either page load or during an api call.

```<code>  $.ajax({
    type: 'GET',
    url: url,
    async: true,
    dataType: 'json',
    beforeSend: function (xhr) {
      $( "<div class='loader' id='searching-loader'></div>").appendTo("#table-playlist-section");
      $("html, body").animate( { scrollTop: $(document).height() }, 100);
    },
    success: function (jsonOptions) {
      $('#searching-loader').remove();
      .
      .
    }
  });
</code>```

CSS

```<code>.loader {
  border: 2px solid #f3f3f3;
  border-radius: 50%;
  border-top: 2px solid #3498db;
  width: 30px;
  height: 30px;
  margin: auto;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
  margin-top: 35px;
  margin-bottom: -35px;
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</code>```

Body:
This will be in synchronisation with an api call, When the api call is triggered, the loader is shown. When the api call is succesful, the loader is removed. This can be used for either page load or during an api call.

  $.ajax({
    type: 'GET',
    url: url,
    async: true,
    dataType: 'json',
    beforeSend: function (xhr) {
      $( "<div class='loader' id='searching-loader'></div>").appendTo("#table-playlist-section");
      $("html, body").animate( { scrollTop: $(document).height() }, 100);
    },
    success: function (jsonOptions) {
      $('#searching-loader').remove();
      .
      .
    }
  });

CSS

.loader {
  border: 2px solid #f3f3f3;
  border-radius: 50%;
  border-top: 2px solid #3498db;
  width: 30px;
  height: 30px;
  margin: auto;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
  margin-top: 35px;
  margin-bottom: -35px;
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


问:
Laravel rules Error using Laravel-build-form package
i have validate rules error, but I don’t understand why he shows like this even though I write more than 1900

Im using https://kristijanhusak.github.io/laravel-form-builder/ this package

Build Form

```<code>class TruckForm extends Form
{
    public function buildForm()
    {
        $this
            ->add('brand_id','collection', [
                'type' => 'select',
                'rules' => 'required',
                'property' => 'name',
                'options' => [
                    'choices' => Brand::pluck('name')->toArray()
                ]
            ])
           ->add('year', 'number', [
               'rules' => ['required', 'min:1900', 'max:'.Carbon::now()->year]
           ])
           ->add('owner_full_name', Field::TEXT, [
               'rules' => ['required', new MinWordsRule(2)]
           ])
           ->add('number_of_owners', Field::NUMBER, [
               'rules' => 'nullable'
           ])
           ->add('comment', Field::TEXTAREA, [
               'rules' => 'nullable'
           ])
           ->add('Save or Create', Field::BUTTON_SUBMIT,
                [
                    'attr' => ['class' => 'btn btn-success']
                ]
           );

    }
}

</code>```

Screen Error

答:
I think the Validatore is misinterpreting the datatype of year for a string that's why it says

"the year Must be at least 1900 characters".

Try to define the year as Field::NUMBER like 'number_of_owners'

and change the min max to gt 'greater than' and lte 'less than or equal':

```<code> ->add('year', Field::NUMBER, [
           'rules' => ['required', 'gt:1900', 'lte:'.Carbon::now()->year]
       ])
</code>```

Body:
i have validate rules error, but I don’t understand why he shows like this even though I write more than 1900

Im using https://kristijanhusak.github.io/laravel-form-builder/ this package

Build Form

class TruckForm extends Form
{
    public function buildForm()
    {
        $this
            ->add('brand_id','collection', [
                'type' => 'select',
                'rules' => 'required',
                'property' => 'name',
                'options' => [
                    'choices' => Brand::pluck('name')->toArray()
                ]
            ])
           ->add('year', 'number', [
               'rules' => ['required', 'min:1900', 'max:'.Carbon::now()->year]
           ])
           ->add('owner_full_name', Field::TEXT, [
               'rules' => ['required', new MinWordsRule(2)]
           ])
           ->add('number_of_owners', Field::NUMBER, [
               'rules' => 'nullable'
           ])
           ->add('comment', Field::TEXTAREA, [
               'rules' => 'nullable'
           ])
           ->add('Save or Create', Field::BUTTON_SUBMIT,
                [
                    'attr' => ['class' => 'btn btn-success']
                ]
           );

    }
}

Screen Error

Body:
I think the Validatore is misinterpreting the datatype of year for a string that's why it says

"the year Must be at least 1900 characters".

Try to define the year as Field::NUMBER like 'number_of_owners'

and change the min max to gt 'greater than' and lte 'less than or equal':

 ->add('year', Field::NUMBER, [
           'rules' => ['required', 'gt:1900', 'lte:'.Carbon::now()->year]
       ])