问:
find specific words in text files
I have many text files in different sub directories, whereby each files has the file extension ".pro".

Each file contains of one or more lines where the text "PRO <name>," or "Function <name>," occurs.
After the <name> follows a comma followed by variables.

I would like to generate a list consisting of 2 columns:

1st column: the full file name (with full path)

2nd column: "PRO <name>" or/and "Function <name>

For the two example files/scripts below the resulting text would be:

```<code><full path>read_scenes_out.pro  PRO READ_SCENES_CLA
<full path>read_scenes_out.pro  PRO PRO READ_TAU_IN
<full path>read_scenes_out.pro  FUNCTION READ_HRIT
<full path>read_scenes_in.pro   PRO READ_SCENES_FLG
<full path>read_scenes_in.pro   PRO READ_SCENES_ELEV
<full path>read_scenes_in.pro   PRO READ_TAU_IN
<full path>read_scenes_in.pro   FUNCTION READ_HRIT2
</code>```

Since I am a beginner with Linux I cannot solve this myself. The only small success was two find out how to list all full path's of pro files in all subdirectories:

find . | grep ".pro" | sort -z

May be this can be combined with that answer.

Two example files ("..." is a place holder for programming code):

file name 1 named "read_scenes_out.pro"

PRO READ_SCENES_CLA, ICLA, INDATE=INDATE

...

end

PRO READ_TAU_IN, TAU, INFILE=INFILE

...

end

FUNCTION READ_HRIT, slot, ChannelId, counts, pgm=pgm

...

end

file name 2 named "read_scenes_in.pro"

PRO READ_SCENES_FLG, NTEST, INDIR=INDIR, INDATE=INDATE

...

end

PRO READ_SCENES_ELEV, IELEV, INDIR=INDIR

...

end

PRO READ_TAU_IN, TAU, INFILE=INFILE

...

end

FUNCTION READ_HRIT2, slot, ChannelId, counts, pgm=pgm

...

end

答:
Try something like

```<code>find . -name '*.pro' \
  -exec grep -Eo '(PRO|FUNCTION)[ ]+[^ ,]+' /dev/null {} +
</code>```

where the whitespace inside both character classes  [...] consists of a space and a tab.

The file name separator output by grep is a colon; it should not be hard to change this by way of a simple sed postprocessing step if it's important. Or maybe switch from grep to Awk to have more control over how the output is generated.

Title: find specific words in text files

Body:
I have many text files in different sub directories, whereby each files has the file extension ".pro".

Each file contains of one or more lines where the text "PRO <name>," or "Function <name>," occurs.
After the <name> follows a comma followed by variables.

I would like to generate a list consisting of 2 columns:

1st column: the full file name (with full path)

2nd column: "PRO <name>" or/and "Function <name>

For the two example files/scripts below the resulting text would be:

<full path>read_scenes_out.pro  PRO READ_SCENES_CLA
<full path>read_scenes_out.pro  PRO PRO READ_TAU_IN
<full path>read_scenes_out.pro  FUNCTION READ_HRIT
<full path>read_scenes_in.pro   PRO READ_SCENES_FLG
<full path>read_scenes_in.pro   PRO READ_SCENES_ELEV
<full path>read_scenes_in.pro   PRO READ_TAU_IN
<full path>read_scenes_in.pro   FUNCTION READ_HRIT2

Since I am a beginner with Linux I cannot solve this myself. The only small success was two find out how to list all full path's of pro files in all subdirectories:

find . | grep ".pro" | sort -z

May be this can be combined with that answer.

Two example files ("..." is a place holder for programming code):

file name 1 named "read_scenes_out.pro"

PRO READ_SCENES_CLA, ICLA, INDATE=INDATE

...

end

PRO READ_TAU_IN, TAU, INFILE=INFILE

...

end

FUNCTION READ_HRIT, slot, ChannelId, counts, pgm=pgm

...

end

file name 2 named "read_scenes_in.pro"

PRO READ_SCENES_FLG, NTEST, INDIR=INDIR, INDATE=INDATE

...

end

PRO READ_SCENES_ELEV, IELEV, INDIR=INDIR

...

end

PRO READ_TAU_IN, TAU, INFILE=INFILE

...

end

FUNCTION READ_HRIT2, slot, ChannelId, counts, pgm=pgm

...

end

Body:
Try something like

find . -name '*.pro' \
  -exec grep -Eo '(PRO|FUNCTION)[ ]+[^ ,]+' /dev/null {} +

where the whitespace inside both character classes  [...] consists of a space and a tab.

The file name separator output by grep is a colon; it should not be hard to change this by way of a simple sed postprocessing step if it's important. Or maybe switch from grep to Awk to have more control over how the output is generated.


来源: stackexchange

问:
SQL Group By with limit and distinct - MySQL
This is my tables and structure

Shoutbox

SID   //PK

Title //Title

shoutbox_follower

SID

UID //User ID

Shouts

SID

Text //Shouts

I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following

i tried this but it did not worked

```<code>select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;
</code>```

But i can do the work with multiple query

```<code>SELECT SID from shoutBox_Follower where UID=5
SELECT SID,TEXT from Shouts where SID in ($boxList) order by id desc limit 1
SELECT Title from Shoutbox where SID=? limit 1
</code>```

答:
You can combine the queries, in cases like this:

```<code>SELECT SID,
       (select TEXT
       from Shouts
       where Shouts.SID = shoutBox_Follower.SID
       order by Shouts.SID desc limit 1
       ) as shout_text
from shoutBox_Follower
where UID=5
</code>```

It performs very fast for small numbers of rows (assuming you've the needed indexes, of course). Based on your third query, the title can be fetched using a simple inner join.

ContentLicense: CC BY-SA 3.0

Body:
This is my tables and structure

Shoutbox

SID   //PK

Title //Title

shoutbox_follower

SID

UID //User ID

Shouts

SID

Text //Shouts

I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following

i tried this but it did not worked

select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;

But i can do the work with multiple query

SELECT SID from shoutBox_Follower where UID=5
SELECT SID,TEXT from Shouts where SID in ($boxList) order by id desc limit 1
SELECT Title from Shoutbox where SID=? limit 1

Body:
You can combine the queries, in cases like this:

SELECT SID,
       (select TEXT
       from Shouts
       where Shouts.SID = shoutBox_Follower.SID
       order by Shouts.SID desc limit 1
       ) as shout_text
from shoutBox_Follower
where UID=5

It performs very fast for small numbers of rows (assuming you've the needed indexes, of course). Based on your third query, the title can be fetched using a simple inner join.


问:
Is there a way to hide a button but make it clickable?
I'm making a software with wxpython, and I creating a logo with a website that helps make logos, and I want to create an invisible button behind that logo that when the logo is clicked I will perform something, So is there a way to make the button invisible but clickable ?

This image

And I want to create on the Exit text an invisible button that when the exit is clicked, it will quit the software, is there a way ?

答:
This is one simple way to achieve what you are after by binding mouse events to the image.

Ensure that the image is essentially fixed in size or you will have to start calculating positions.

```<code>import wx

class Example(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Mouse Control')
        self.panel1 = wx.Panel(self)
        self.panel2 = wx.Panel(self)
        self.panel3 = wx.Panel(self)
        self.aBitmap = wx.Image(name = "image_button.png").ConvertToBitmap()
        self.bm = wx.StaticBitmap(self.panel2, -1, self.aBitmap)
        self.bm.Bind(wx.EVT_LEFT_DOWN, self.onClick)
        self.bm.Bind(wx.EVT_MOTION, self.onAccess)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.panel1,0)
        vbox.Add(self.panel2,0)
        vbox.Add(self.panel3,0)
        self.panel1.SetMinSize(self.bm.GetSize())
        self.panel2.SetMinSize(self.bm.GetSize())
        self.panel3.SetMinSize(self.bm.GetSize())
        self.panel1.SetBackgroundColour("blue")
        self.panel3.SetBackgroundColour("blue")
        self.SetSizerAndFit(vbox)
        self.Show()

    def onClick(self, event):
        x,y = event.GetPosition()
        if y > 25 and y < 50:
            if x > 30 and x < 170:
                wx.MessageBox("Contact", "Contact Header")
            elif x > 800 and x < 860:
                wx.MessageBox("Exit", "Exit Header")
        else:
            event.Skip()

    def onAccess(self, event):
        x,y = event.GetPosition()
        if y > 25 and y < 50:
            if x > 30 and x < 170:
                self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
            elif x > 800 and x < 860:
                self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
            else:
                self.SetCursor(wx.Cursor(wx.CURSOR_DEFAULT))
        else:
            self.SetCursor(wx.Cursor(wx.CURSOR_DEFAULT))
        event.Skip()

if __name__ == '__main__':
    app = wx.App()
    Example()
    app.MainLoop()
</code>```

This code indicates that you are over a hotspot (Contact us, Exit) by changing the cursor.

ContentLicense: CC BY-SA 4.0

Body:
This is one simple way to achieve what you are after by binding mouse events to the image.

Ensure that the image is essentially fixed in size or you will have to start calculating positions.

import wx

class Example(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Mouse Control')
        self.panel1 = wx.Panel(self)
        self.panel2 = wx.Panel(self)
        self.panel3 = wx.Panel(self)
        self.aBitmap = wx.Image(name = "image_button.png").ConvertToBitmap()
        self.bm = wx.StaticBitmap(self.panel2, -1, self.aBitmap)
        self.bm.Bind(wx.EVT_LEFT_DOWN, self.onClick)
        self.bm.Bind(wx.EVT_MOTION, self.onAccess)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.panel1,0)
        vbox.Add(self.panel2,0)
        vbox.Add(self.panel3,0)
        self.panel1.SetMinSize(self.bm.GetSize())
        self.panel2.SetMinSize(self.bm.GetSize())
        self.panel3.SetMinSize(self.bm.GetSize())
        self.panel1.SetBackgroundColour("blue")
        self.panel3.SetBackgroundColour("blue")
        self.SetSizerAndFit(vbox)
        self.Show()

    def onClick(self, event):
        x,y = event.GetPosition()
        if y > 25 and y < 50:
            if x > 30 and x < 170:
                wx.MessageBox("Contact", "Contact Header")
            elif x > 800 and x < 860:
                wx.MessageBox("Exit", "Exit Header")
        else:
            event.Skip()

    def onAccess(self, event):
        x,y = event.GetPosition()
        if y > 25 and y < 50:
            if x > 30 and x < 170:
                self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
            elif x > 800 and x < 860:
                self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
            else:
                self.SetCursor(wx.Cursor(wx.CURSOR_DEFAULT))
        else:
            self.SetCursor(wx.Cursor(wx.CURSOR_DEFAULT))
        event.Skip()

if __name__ == '__main__':
    app = wx.App()
    Example()
    app.MainLoop()

This code indicates that you are over a hotspot (Contact us, Exit) by changing the cursor.


问:
Cannot download bundle at http://repo1.maven.org/maven2/....oss-catalog-1.6.jar: HTTP Server 'Not Implemented'
Recently, I re-imaged our machines from Windows 7 to Windows 10.
Ever since then, on opening Eclipse, I've been unable to open the M2E Catalog. This means I can't install Maven's the Tycho Project Configurator. As this is an organization, it's pretty certain there may be proxy servers. However, I've not been able to obtain its details. Essentially, installing the Tycho Project Configurator is what I'm trying to do.

Steps to reproduce:

```<code>Eclipse Oxygen -> Quick Access -> "m2e"
</code>```

Error on Eclipse GUI: "Discovery completed without finding any
  extensions. Please check your network connection and try again".

Eclipse logs:

!ENTRY org.eclipse.equinox.p2.discovery 4 0 2020-02-17 10:48:23.685
  !MESSAGE Cannot download bundle at
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar:
  HTTP Server 'Not Implemented':
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar
  !STACK 1 org.eclipse.equinox.p2.core.ProvisionException: HTTP Server
  'Not Implemented':
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.util.CacheManager.createCache(CacheManager.java:109)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.util.TransportUtil.downloadResource(TransportUtil.java:56)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.RemoteBundleDiscoveryStrategy$DownloadBundleJob.call(RemoteBundleDiscoveryStrategy.java:202)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.RemoteBundleDiscoveryStrategy$DownloadBundleJob.call(RemoteBundleDiscoveryStrategy.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748) Caused by:
  org.eclipse.ecf.filetransfer.BrowseFileTransferException:
  HttpComponents connection error response code 501.    at
  org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientFileSystemBrowser.runRequest(HttpClientFileSystemBrowser.java:293)
    at
  org.eclipse.ecf.provider.filetransfer.browse.AbstractFileSystemBrowser$DirectoryJob.run(AbstractFileSystemBrowser.java:69)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)

Java version: 1.8.0_181

Any suggestions?

答: Try a newer release of Eclipse. Maven Central only provides downloads by https, now.</p>

Body:
Recently, I re-imaged our machines from Windows 7 to Windows 10.
Ever since then, on opening Eclipse, I've been unable to open the M2E Catalog. This means I can't install Maven's the Tycho Project Configurator. As this is an organization, it's pretty certain there may be proxy servers. However, I've not been able to obtain its details. Essentially, installing the Tycho Project Configurator is what I'm trying to do.

Steps to reproduce:

Eclipse Oxygen -> Quick Access -> "m2e"

Error on Eclipse GUI: "Discovery completed without finding any
  extensions. Please check your network connection and try again".

Eclipse logs:

!ENTRY org.eclipse.equinox.p2.discovery 4 0 2020-02-17 10:48:23.685
  !MESSAGE Cannot download bundle at
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar:
  HTTP Server 'Not Implemented':
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar
  !STACK 1 org.eclipse.equinox.p2.core.ProvisionException: HTTP Server
  'Not Implemented':
  http://repo1.maven.org/maven2/.m2e/discovery-catalog/org.eclipse.m2e.discovery.oss-catalog-1.6.jar
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.util.CacheManager.createCache(CacheManager.java:109)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.util.TransportUtil.downloadResource(TransportUtil.java:56)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.RemoteBundleDiscoveryStrategy$DownloadBundleJob.call(RemoteBundleDiscoveryStrategy.java:202)
    at
  org.eclipse.equinox.internal.p2.discovery.compatibility.RemoteBundleDiscoveryStrategy$DownloadBundleJob.call(RemoteBundleDiscoveryStrategy.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748) Caused by:
  org.eclipse.ecf.filetransfer.BrowseFileTransferException:
  HttpComponents connection error response code 501.    at
  org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientFileSystemBrowser.runRequest(HttpClientFileSystemBrowser.java:293)
    at
  org.eclipse.ecf.provider.filetransfer.browse.AbstractFileSystemBrowser$DirectoryJob.run(AbstractFileSystemBrowser.java:69)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)

Java version: 1.8.0_181

Any suggestions?


问:
Practical differences between explicitly subscribing to an Observable vs calling subscribe() with parameter
I have a service that returns an Observable:

```<code>contactsSerice (): Observable<Contact[]> {...}
</code>```

For using this data on my template and keep the template "alive" based on what's in the Observable I've found two ways.

I declared a Subject within the context of my Component:

```<code>export class ExampleComponent implements OnInit {

    contacts$: Subject<Contact[]> = new Subject<Contact[]>();
    constructor(){}

}
</code>```

And then:

Explicitly subscribing to the Observable (and emitting the contacts) like this:

```<code>ngOnInit() {

   this.contactsSerice().subscribe((contacts: Contact[]) => {
           this.contacts$.next(contacts);
   });
}
</code>```

Calling directly the .subscribe() using my Subject as a parameter:

```<code>ngOnInit() {
  this.contactsSerice().subscribe(this.contacts$);
}
</code>```

After this, I can use the | async pipe in the template like:

```<code><section *ngIf="contacts$ | async as contacts">
...
</section>
</code>```

I was wondering if there's any practical difference between calling subscribe() passing the Subject vs properly subscribing to the Observable and trigger the Subject's next() method.

答:
The short answers is none, there is no difference (besides that you will be using a bit more memory for the Subject itself).

From a practical point of view (let's say the question is when should I use intermediate Subject) you want to use intermediate subjects whenever you want to cache somehow the response that you receive from your back-end.

Let's say for example you want to do the following thing

// Left side of the screen

...

// Right side of the screen

...

```

So in this case, if you are using directly the service you will make two calls to the back-end (as each |async is a new subscription).

So the short answer is that there will be no difference, but it is better to have it.

** Side note: If you are new to Angular and have trouble managing states, look into NGRX.

Body:
I have a service that returns an Observable:

contactsSerice (): Observable<Contact[]> {...}

For using this data on my template and keep the template "alive" based on what's in the Observable I've found two ways.

I declared a Subject within the context of my Component:

export class ExampleComponent implements OnInit {

    contacts$: Subject<Contact[]> = new Subject<Contact[]>();
    constructor(){}

}

And then:

Explicitly subscribing to the Observable (and emitting the contacts) like this:

ngOnInit() {

   this.contactsSerice().subscribe((contacts: Contact[]) => {
           this.contacts$.next(contacts);
   });
}

Calling directly the .subscribe() using my Subject as a parameter:

ngOnInit() {
  this.contactsSerice().subscribe(this.contacts$);
}

After this, I can use the | async pipe in the template like:

...

I was wondering if there's any practical difference between calling subscribe() passing the Subject vs properly subscribing to the Observable and trigger the Subject's next() method.

Body:
The short answers is none, there is no difference (besides that you will be using a bit more memory for the Subject itself).

From a practical point of view (let's say the question is when should I use intermediate Subject) you want to use intermediate subjects whenever you want to cache somehow the response that you receive from your back-end.

Let's say for example you want to do the following thing

// Left side of the screen
<section *ngIf="contacts$ | async as contacts">
...
</section>

// Right side of the screen
<section *ngIf="contacts$ | async as contacts">
...
</section>

So in this case, if you are using directly the service you will make two calls to the back-end (as each |async is a new subscription).

So the short answer is that there will be no difference, but it is better to have it.

** Side note: If you are new to Angular and have trouble managing states, look into NGRX.


问:
What is actually use of non escaping closures?
If a function can return a value itself then why need to call non escaping closure to return value?
Consider following example </p>

```<code> func add(a: Int, b: Int, completion: (Int) -> ()) {
        let addition = a + b
        completion(addition)
 }
</code>```

答:
Common use cases for closure are:

Asynchronous calls; networking.

Functions stored as variables; think actions and supplied callbacks.

Scheduling tasks on a dispatch queue.

If there is a process where it take sometime to get work done and give back result. In these cases closure are best options.

Non Escaping Closures

Non-escaping closures have a very clear lifecycle and have become the default closure type in Swift 3 because of it. A non-escaping closure is simple: It’s passed into a function (or other containing scope), the function/scope executes that closure, and the function returns. The closure cannot return or finish executing after the body of the calling function has returned. Due to that fact, the compiler is able to optimize non-escaping closures over escaping closures.

Default closure behaviour (non-escaping)

Say for a simple function with closure like this :

```<code>func macICanBuy(budget: Int, closure: (String) -> Void) {
  print("checking budget...")

  closure("Mcdonalds' Big Mac")

  print("macICanBuy finished execution")
}

override func viewDidLoad(){
  macICanBuy(budget: 100, closure: { mac in
    print("I can afford a \(mac)")
  })
}

// output:
// checking budget...
// I can afford a Mcdonalds' Big Mac
// macICanBuy finished execution
</code>```

Before the app executes the macICanBuy function, it will load the passed parameter (budget and closure) into the phone memory (RAM) so the function can use these data.

After the app finish execute the macICanBuy function, the app no longer needs the budget and closure data, hence it will remove them from the memory. The closure data didn't manage to escape from being removed from memory after the function has finished executing, hence it is called 'non-escaping' closure.

Above reference from:

https://fluffy.es/what-is-escaping-closure/

Body:
If a function can return a value itself then why need to call non escaping closure to return value?
Consider following example

 func add(a: Int, b: Int, completion: (Int) -> ()) {
        let addition = a + b
        completion(addition)
 }

Body:
Common use cases for closure are:

Asynchronous calls; networking.

Functions stored as variables; think actions and supplied callbacks.

Scheduling tasks on a dispatch queue.

If there is a process where it take sometime to get work done and give back result. In these cases closure are best options.

Non Escaping Closures

Non-escaping closures have a very clear lifecycle and have become the default closure type in Swift 3 because of it. A non-escaping closure is simple: It’s passed into a function (or other containing scope), the function/scope executes that closure, and the function returns. The closure cannot return or finish executing after the body of the calling function has returned. Due to that fact, the compiler is able to optimize non-escaping closures over escaping closures.

Default closure behaviour (non-escaping)

Say for a simple function with closure like this :

func macICanBuy(budget: Int, closure: (String) -> Void) {
  print("checking budget...")

  closure("Mcdonalds' Big Mac")

  print("macICanBuy finished execution")
}

override func viewDidLoad(){
  macICanBuy(budget: 100, closure: { mac in
    print("I can afford a \(mac)")
  })
}

// output:
// checking budget...
// I can afford a Mcdonalds' Big Mac
// macICanBuy finished execution

Before the app executes the macICanBuy function, it will load the passed parameter (budget and closure) into the phone memory (RAM) so the function can use these data.

After the app finish execute the macICanBuy function, the app no longer needs the budget and closure data, hence it will remove them from the memory. The closure data didn't manage to escape from being removed from memory after the function has finished executing, hence it is called 'non-escaping' closure.

Above reference from:

https://fluffy.es/what-is-escaping-closure/


问:
Removing duplicate values without using distinct
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.     </p>

```<code>select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week
</code>```

答:
You can check using row_number() :

```<code>select replace(wk.article, ' - paper', '') as p, wk.pageviews, wk.login_clicks, wk.paywall_clicks,
       row_number() over (partition by replace(wk.article, ' - paper', '') order by ?) as seq
from analytics.article_action_week wk;
</code>```

You can filtered seq with 1 to get unique rows. Use ordering column instead ?

Body:
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.

select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week

Body:
You can check using row_number() :

select replace(wk.article, ' - paper', '') as p, wk.pageviews, wk.login_clicks, wk.paywall_clicks,
       row_number() over (partition by replace(wk.article, ' - paper', '') order by ?) as seq
from analytics.article_action_week wk;

You can filtered seq with 1 to get unique rows. Use ordering column instead ?


问:
Using window function in redshift to aggregate conditionally
I have a table with following data:

Link to test data: http://sqlfiddle.com/#!15/dce01/1/0

I want to aggregate the items column (using listagg) for each group in gid in sequence as specified by seq column based on the condition that aggregation ends when pid becomes 0 again for a group.

i.e.
for group g1, there would be 2 aggregations; 1 for seq 1-3 and another for sequence 4-6; since for group g1, the pid becomes 0 for seq 4.

I expect the result for the given example to be as follows (Please note that seq in result is the min value of seq for the group where the pid becomes 0):

答:
it's gaps and islands problem:</p>

```<code>with
 subgroup_ids as (
    select *, sum(case when pid=0 then 1 else 0 end) over (partition by gid order by seq) as subgroup_id
    from tablename
)
select gid, subgroup_id, listagg(items,',')
from subgroup_ids
group by 1,2
</code>```

Body:
it's gaps and islands problem:

with
 subgroup_ids as (
    select *, sum(case when pid=0 then 1 else 0 end) over (partition by gid order by seq) as subgroup_id
    from tablename
)
select gid, subgroup_id, listagg(items,',')
from subgroup_ids
group by 1,2


问:
count down timer in shopify app development
I'm a newbie in Shopify apps development. I want to create an app countdown timer. I follow all the steps of Build a Shopify app with Node and React where I learn some basic concepts like retrieve data from graghql (query/mutation) and discount the products. My question is what is the next step for my app to save countdown timer for my selected products and display on front below the add to cart button. Where I save my code to display on the front side.

答:
to add your counter you need to inject your js to shopify store.

for this you need to make use of Script Tag

And if you want to add some liquid stuff using app then you need to use themes API.


问:
How should I serialize / reference App Engine users?
This is a follow-up to this question:

How do I correctly reference Users in GQL queries on App Engine?

In my app, I have a Photos db.Model, where each photo has a UserProperty.  I want to display a list of users, where clicking on a user will show all of the user's photos.

What is the best way to reference the user when creating a link to the user's photo page?

I've found two options, both which have their shortcomings.

user.nickname() - this can be used in a GQL query (e.g. Photos.gql("WHERE user = USER(:1)", user.nickname()) ), but it can change, it's not necessarily unique, and sometimes (e.g. for Gmail addresses) user.nickname() truncates at the '@' symbol and can't be used for lookups without appending "@gmail.com".

user.user_id() - this is unique, but I haven't found a way to lookup a user by the user_id()

Is there a better way to do this?  Currently, I'm storing both the user and the user_id() on the Photo model, doing a GQL search by user_id passed in the link, and then referencing the user from the UserProperty on the Photo model.

答: Use the user_id. 'looking up' a user isn't really a meaningful operation unless you mean to get their email address and/or nickname. You should have a users table that stores User objects, keyed by the user_id, along with any other site-specific information you need on them (eg, preferences, profile information).


问:
Unable to connect Dongle K5150 to iot core
I'm trying to connect Dongle K5150 with Emnify SIM to raspberry Pi3 with iot core 17763 version.
I followed these steps:
USB Mobile Broadband Modem on Windows 10 IoT?
but at the end I had an error:
Connect Failure: error 0x139f.

Can someone help me?

答:
I found the solution,
the problem was in my "profile.xml".

In detail in two nodes:

```<code><HomeProviderName>em</HomeProviderName>
</code>```

and

```<code><AccessString>em</AccessString>
</code>```

Body:
I found the solution,
the problem was in my "profile.xml".

In detail in two nodes:

<HomeProviderName>em</HomeProviderName>

and

<AccessString>em</AccessString>


问:
In shiny, how to have a new actionButton when a different variable is selected?
I have a simple task of printing the output of a call to table() on a selected variable.

I want to display the output when the button "Print" is clicked.

In the following example, once the button is clicked, the output is always triggered when I change the selected variable.

If I clicked "Print", and then change the selected variable, I want the ouput to be gone, waited to be printed again when clicking "Print".

Thank you!

Here is a reproducible example:

```<code>library(shiny)
data = iris

ui = fluidPage(
    uiOutput("selectvar"),
    actionButton("print", "Print"),
    verbatimTextOutput("info")
)

server = function(input, output, session)
{
    output$selectvar = renderUI({
        selectInput("selectedvar",
                    "Select variable",
                    choices = colnames(iris))
    })

    tab = reactive( table(data[[input$selectedvar]]) )

    observeEvent(input$print, {
        output$info = renderPrint( tab() )
    })

}

shinyApp(ui, server)
</code>```

答:
That's because output$info is reactive to tab(), even while it is enclosed in an observeEvent. I think this app does what you want:

```<code>library(shiny)
data = iris

ui = fluidPage(
  uiOutput("selectvar"),
  actionButton("print", "Print"),
  verbatimTextOutput("info")
)

server = function(input, output, session)
{
  output$selectvar = renderUI({
    selectInput("selectedvar",
                "Select variable",
                choices = colnames(iris))
  })

  tab <- reactiveVal()
  observeEvent(input$selectedvar, {
    tab(NULL)
  })
  observeEvent(input$print, {
    tab(table(data[[input$selectedvar]]))
  })

  output$info <- renderPrint({
    tab()
  })

}

shinyApp(ui, server)
</code>```

Body:
I have a simple task of printing the output of a call to table() on a selected variable.

I want to display the output when the button "Print" is clicked.

In the following example, once the button is clicked, the output is always triggered when I change the selected variable.

If I clicked "Print", and then change the selected variable, I want the ouput to be gone, waited to be printed again when clicking "Print".

Thank you!

Here is a reproducible example:

library(shiny)
data = iris

ui = fluidPage(
    uiOutput("selectvar"),
    actionButton("print", "Print"),
    verbatimTextOutput("info")
)

server = function(input, output, session)
{
    output$selectvar = renderUI({
        selectInput("selectedvar",
                    "Select variable",
                    choices = colnames(iris))
    })

    tab = reactive( table(data[[input$selectedvar]]) )

    observeEvent(input$print, {
        output$info = renderPrint( tab() )
    })

}

shinyApp(ui, server)

Body:
That's because output$info is reactive to tab(), even while it is enclosed in an observeEvent. I think this app does what you want:

library(shiny)
data = iris

ui = fluidPage(
  uiOutput("selectvar"),
  actionButton("print", "Print"),
  verbatimTextOutput("info")
)

server = function(input, output, session)
{
  output$selectvar = renderUI({
    selectInput("selectedvar",
                "Select variable",
                choices = colnames(iris))
  })

  tab <- reactiveVal()
  observeEvent(input$selectedvar, {
    tab(NULL)
  })
  observeEvent(input$print, {
    tab(table(data[[input$selectedvar]]))
  })

  output$info <- renderPrint({
    tab()
  })

}

shinyApp(ui, server)


问:
C++, copy_if with vector<class>
This is a part of the code, that I'm in trouble with

```<code>#include<iostream>
#include<fstream>
#include<conio.h>
#include<list>
#include<iterator>
#include<map>
#include<algorithm>
#include<ctime>
#include<sstream>
#include<vector>
#include<numeric>
#include<string>

using namespace std;

class C_Person
{
protected:
    string M_SName;
    string M_SEGN;

public:
    inline C_Person& operator=(const C_Person& c_p) {
        this->M_SName = c_p.M_SName;
        this->M_SEGN = c_p.M_SEGN;
        return *this;
    }
};

class C_Student :public C_Person
{
public:

    C_Student() {};

    C_Student(const string Name, const string EGN, const string FN, const map<string, unsigned> st_book)
    {
        this->SetName(Name);
        this->SetEGN(EGN);
        this->SetFN(FN);
        this->Student_Book = st_book;
    }

    C_Student(const C_Student &stud)
    {
        this->SetName(stud.GetName());
        this->SetEGN(stud.GetEGN());
        this->M_SFacNum = stud.M_SFacNum;
        this->Student_Book = stud.Student_Book;
    }

    C_Student operator=(const C_Student&st) {
        this->M_SName = st.M_SName;
        this->M_SEGN = st.M_SEGN;
        this->M_SFacNum = st.M_SFacNum;
    }
private:
    string M_SFacNum;
    map <string, unsigned> Student_Book;
};

class C_Speciality
{
public:
    C_Speciality(string spec, vector<C_Student>Vec_St) :
        M_SSpec(spec),
        V_Students(Vec_St)
    {}

    C_Speciality(const string &filename)//3.1*
    {
        try {
            ifstream file(filename);
            if (!file)
            {
                exception e;
                throw e;
            }
            file >> this->M_SSpec;
            copy(istream_iterator<C_Student>(file), istream_iterator<C_Student>(), back_inserter(this->V_Students));
            file.close();
        }
        catch (exception e)
        {
            cout << "File did not open!";
        }
    }

    list<C_Student*> GetStudentsWithDegeree(string const disciplineName, unsigned const degree) {//3.3*
        list<C_Student*> listt;

        copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
            [=](C_Student&st) {return st.GetDegreeByDisciplineName(disciplineName) == degree; });
        return listt;
    }
private:
    string M_SSpec;
    vector<C_Student> V_Students;
};
</code>```

And on

```<code>copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
    [=](C_Student&st) {return st.GetDegreeByDisciplineName(disciplineName) == degree; }
);
</code>```

It gives me

```<code>    Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'C_Student' (or there is no acceptable conversion)   C++_echo    c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm   585
</code>```

Or the full output

```<code>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm(585): error C2679: binary '=': no operator found which takes a right-hand operand of type 'C_Student' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4233): note: could be 'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>> &&)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4233): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(const std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>> &)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4210): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(C_Student *&&)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4204): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(C_Student *const &)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm(585): note: while trying to match the argument list '(std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>>, C_Student)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\users\echo\source\repos\c++_lubo_kursova\c++_lubo_kursova\source.cpp(304): note: see reference to function template instantiation '_OutIt std::copy_if<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,std::back_insert_iterator<std::list<C_Student *,std::allocator<C_Student*>>>,C_Speciality::GetStudentsWithDegeree::<lambda_3c3836fbaa0c70067d1b37845af861f2>>(_InIt,_InIt,_OutIt,_Pr)' being compiled
1>        with
1>        [
1>            _OutIt=std::back_insert_iterator<std::list<C_Student *,std::allocator<C_Student *>>>,
1>            _Ty=C_Student,
1>            _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<C_Student>>>,
1>            _Pr=C_Speciality::GetStudentsWithDegeree::<lambda_3c3836fbaa0c70067d1b37845af861f2>
1>        ]
1>Done building project "C++_echo.vcxproj" -- FAILED.
</code>```

I can see that there is no operator= that takes C_Student, but what am I doing wrong? Is it just the operator-overloading? Also I want to ask if the lambda is properly used here. Should I just replace it with a comparator (I am using it one single time)?

答:
In your GetStudentsWithDegeree you are trying to take an objects from a vector of V_Students and put in a list of C_Student* i.e. pointers to an object. Here is the correct member function code:

    list<C_Student> GetStudentsWithDegeree(string const disciplineName, unsigned const degree) {
        list<C_Student> listt;

        copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
                [=] (const C_Student &st) {
                    return st.GetDegreeByDisciplineName(disciplineName) == degree;
                });
        return listt;
    }
```

Regarding the use of lambdas, this is just a modern way of using functional objects. You are free to use any method that suits you. In this case, a comparator such as std::less or std::greater is not suitable, since you select the necessary objects with custom code, and not sort them.

Title: C++, copy_if with vector<class>

Body:
This is a part of the code, that I'm in trouble with

#include<iostream>
#include<fstream>
#include<conio.h>
#include<list>
#include<iterator>
#include<map>
#include<algorithm>
#include<ctime>
#include<sstream>
#include<vector>
#include<numeric>
#include<string>

using namespace std;

class C_Person
{
protected:
    string M_SName;
    string M_SEGN;

public:
    inline C_Person& operator=(const C_Person& c_p) {
        this->M_SName = c_p.M_SName;
        this->M_SEGN = c_p.M_SEGN;
        return *this;
    }
};

class C_Student :public C_Person
{
public:

    C_Student() {};

    C_Student(const string Name, const string EGN, const string FN, const map<string, unsigned> st_book)
    {
        this->SetName(Name);
        this->SetEGN(EGN);
        this->SetFN(FN);
        this->Student_Book = st_book;
    }

    C_Student(const C_Student &stud)
    {
        this->SetName(stud.GetName());
        this->SetEGN(stud.GetEGN());
        this->M_SFacNum = stud.M_SFacNum;
        this->Student_Book = stud.Student_Book;
    }

    C_Student operator=(const C_Student&st) {
        this->M_SName = st.M_SName;
        this->M_SEGN = st.M_SEGN;
        this->M_SFacNum = st.M_SFacNum;
    }
private:
    string M_SFacNum;
    map <string, unsigned> Student_Book;
};

class C_Speciality
{
public:
    C_Speciality(string spec, vector<C_Student>Vec_St) :
        M_SSpec(spec),
        V_Students(Vec_St)
    {}

    C_Speciality(const string &filename)//3.1*
    {
        try {
            ifstream file(filename);
            if (!file)
            {
                exception e;
                throw e;
            }
            file >> this->M_SSpec;
            copy(istream_iterator<C_Student>(file), istream_iterator<C_Student>(), back_inserter(this->V_Students));
            file.close();
        }
        catch (exception e)
        {
            cout << "File did not open!";
        }
    }

    list<C_Student*> GetStudentsWithDegeree(string const disciplineName, unsigned const degree) {//3.3*
        list<C_Student*> listt;

        copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
            [=](C_Student&st) {return st.GetDegreeByDisciplineName(disciplineName) == degree; });
        return listt;
    }
private:
    string M_SSpec;
    vector<C_Student> V_Students;
};

And on

copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
    [=](C_Student&st) {return st.GetDegreeByDisciplineName(disciplineName) == degree; }
);

It gives me

    Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'C_Student' (or there is no acceptable conversion)   C++_echo    c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm   585

Or the full output

c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm(585): error C2679: binary '=': no operator found which takes a right-hand operand of type 'C_Student' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4233): note: could be 'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>> &&)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4233): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(const std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>> &)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4210): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(C_Student *&&)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility(4204): note: or       'std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>> &std::back_insert_iterator<std::list<_Ty,std::allocator<_Ty>>>::operator =(C_Student *const &)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\algorithm(585): note: while trying to match the argument list '(std::back_insert_iterator<std::list<C_Student *,std::allocator<_Ty>>>, C_Student)'
1>        with
1>        [
1>            _Ty=C_Student *
1>        ]
1>c:\users\echo\source\repos\c++_lubo_kursova\c++_lubo_kursova\source.cpp(304): note: see reference to function template instantiation '_OutIt std::copy_if<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,std::back_insert_iterator<std::list<C_Student *,std::allocator<C_Student*>>>,C_Speciality::GetStudentsWithDegeree::<lambda_3c3836fbaa0c70067d1b37845af861f2>>(_InIt,_InIt,_OutIt,_Pr)' being compiled
1>        with
1>        [
1>            _OutIt=std::back_insert_iterator<std::list<C_Student *,std::allocator<C_Student *>>>,
1>            _Ty=C_Student,
1>            _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<C_Student>>>,
1>            _Pr=C_Speciality::GetStudentsWithDegeree::<lambda_3c3836fbaa0c70067d1b37845af861f2>
1>        ]
1>Done building project "C++_echo.vcxproj" -- FAILED.

I can see that there is no operator= that takes C_Student, but what am I doing wrong? Is it just the operator-overloading? Also I want to ask if the lambda is properly used here. Should I just replace it with a comparator (I am using it one single time)?

Body:
In your GetStudentsWithDegeree you are trying to take an objects from a vector of V_Students and put in a list of C_Student* i.e. pointers to an object. Here is the correct member function code:

    list<C_Student> GetStudentsWithDegeree(string const disciplineName, unsigned const degree) {
        list<C_Student> listt;

        copy_if(V_Students.begin(), V_Students.end(), back_inserter(listt),
                [=] (const C_Student &st) {
                    return st.GetDegreeByDisciplineName(disciplineName) == degree;
                });
        return listt;
    }

Regarding the use of lambdas, this is just a modern way of using functional objects. You are free to use any method that suits you. In this case, a comparator such as std::less or std::greater is not suitable, since you select the necessary objects with custom code, and not sort them.


问:
Page breaks(LastRenderedPageBreak) missing when openXml extracted by Office.js
W:LastRenderedPageBreak tag missing when document.xml extracted through Office.js. please let me know is there a way to get this tag through Office.js.

Thank you in advance!

答:
This tag is "ephemeral". Word may or may not create it in the Word Open XML when the document is closed - one cannot rely on it being present in the closed file.

When the document is opened in Word again, there's no need for the tag as Word will immediately recalculate line and page breaks. It does this dynamically the entire time a document is opened for editing.

So it's not possible to get this tag in a document opened in Word.


问:
overriding property in maven plugin from command line
This maven command launches an older version (1.3.162) of the H2 database:

```<code>mvn -debug com.edugility:h2-maven-plugin:1.0:spawn
</code>```

As recommended here, I'm trying to override a property of the plugin on the command line....so I can instead use a more recent h2 version:

```<code>mvn -debug -Dh2Version=1.4.200 com.edugility:h2-maven-plugin:1.0:spawn
</code>```

This h2Version property with the older h2 version is defined here on github in the plugin's pom.

Here is the end of the verbose maven output

```<code> [DEBUG] Process arguments: [C:\java\jdk-9.0.4\bin\java, -cp, C:\Users\eoste\.m2\repository\com\h2database\h2\1.3.162\h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 9092]
 [INFO] H2 server spawned at tcp://localhost:9092
</code>```

Not only does the old 1.3.162 version launch, but the there is zero mention anywhere of the h2Version property that I placed on the command line.

I tried moving the -Dh2Version parameter to the end of the command line.  I also tried deleting the plugin from the local repo, to force a download so maybe the h2Version would then get reevaluated....none of these things worked.
This blog shows how to embed a dependency inside a plugin, but that's tons more complicated than my simple command line invocation.

What am I doing wrong?

Using windows 10, java 9, maven 3.6.2

答:
What am I doing wrong?

1) Beware when you want to use plugins/libraries not maintained. The source code was not updated from about 8 years. That may have important issues.

2) To know how to use a maven plugin, don't look in the pom declaration. You can find some information in but you will find much more information in the mojo implementation/specification.

But in fact no, you should not even rely on that to understand how to use a plugin.

3) Indeed a Maven plugin may support configurable properties : directly in the pom.xml and even export them for command line usage. But that is not automatic.
But in both cases, that has to be foreseen by the plugin developer and it is generally documented on the plugin or the source repository homepage.

In fact in your case, if you go into the Mojo implementation : AbstractH2Mojo, you can see how the configuration is set.

All properties have default values in the mojo constructor.

```<code> protected AbstractH2Mojo() {
    super();
    final Service tcpService = new Service("tcp", Service.getDefaultPort("tcp"), false, false);
    this.setServices(Collections.singletonList(tcpService));
    this.setPort(Service.getDefaultPort("tcp"));
    this.setShutdownPassword("h2-maven-plugin");
    this.setJava(new File(new File(new File(System.getProperty("java.home")), "bin"), "java"));
 }
</code>```

The mojo empty constructor is first invoked, then all setter are invoked on the created instance.

It means that you can override any of these properties defined in that class at runtime by providing the property such as ${artifactIdPrefixWithoutMavenPlugin}.field.

Since the maven plugin is h2-maven-plugin, the prefix to refer is h2.

If you run that :

```<code>mvn -X com.edugility:h2-maven-plugin:1.0:spawn -Dh2.port=8084 -Dh2.useSSL=false
</code>```

You could see in the output :

```
[DEBUG] Configuring mojo 'com.edugility:h2-maven-plugin:1.0:spawn' with basic configurator -->
[DEBUG]   (s) port = 8084
[DEBUG]   (s) shutdownHost = localhost
[DEBUG]   (s) shutdownPassword = h2-maven-plugin
[DEBUG]   (s) useSSL = false
[DEBUG] -- end configuration --
[DEBUG] Process arguments: [/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, /home/david/.m2/repository/com/h2database/h2/1.3.162/h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 8084]
```

Concerning the h2 jar used, if you still look in the same class, you will see that part that retrieves the jar file from the classpath :

```<code> public final File getH2() {
    final ProtectionDomain pd = Server.class.getProtectionDomain();
    assert pd != null;
    final CodeSource cs = pd.getCodeSource();
    assert cs != null;
    final URL location = cs.getLocation();
    assert location != null;
    try {
      return new File(location.toURI());
    } catch (final URISyntaxException wontHappen) {
      throw (InternalError)new InternalError().initCause(wontHappen);
    }
 }
</code>```

It means that you have no way to change the H2 JAR used : from the command line when you run the plugin or from the plugin declaration in the pom.xml, since no property is defined in the Mojo to achieve that.

if you will change the H2 version, you need to change the version embedded by the plugin.   As a starter, you could try to fork the plugin GIT repository, change the h2 dependency used in the pom to match to your requirement and check whether in spite of the gap version, working with that plugin is a possible thing.

Note that you could add a new property of the Mojo to make it completely configurable such as :

```<code>mvn ... -Dh2Version=1.4.200
</code>```

But in that case you will need to retrieve that. For example by performing a request to download the dependency from the m2 central repo for example.

And you should also ensure that only valid ranges of the h2 version are used.

Body:
This maven command launches an older version (1.3.162) of the H2 database:

mvn -debug com.edugility:h2-maven-plugin:1.0:spawn

As recommended here, I'm trying to override a property of the plugin on the command line....so I can instead use a more recent h2 version:

mvn -debug -Dh2Version=1.4.200 com.edugility:h2-maven-plugin:1.0:spawn

This h2Version property with the older h2 version is defined here on github in the plugin's pom.

Here is the end of the verbose maven output

 [DEBUG] Process arguments: [C:\java\jdk-9.0.4\bin\java, -cp, C:\Users\eoste\.m2\repository\com\h2database\h2\1.3.162\h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 9092]
 [INFO] H2 server spawned at tcp://localhost:9092

Not only does the old 1.3.162 version launch, but the there is zero mention anywhere of the h2Version property that I placed on the command line.

I tried moving the -Dh2Version parameter to the end of the command line.  I also tried deleting the plugin from the local repo, to force a download so maybe the h2Version would then get reevaluated....none of these things worked.
This blog shows how to embed a dependency inside a plugin, but that's tons more complicated than my simple command line invocation.

What am I doing wrong?

Using windows 10, java 9, maven 3.6.2

Body:
What am I doing wrong?

1) Beware when you want to use plugins/libraries not maintained. The source code was not updated from about 8 years. That may have important issues.

2) To know how to use a maven plugin, don't look in the pom declaration. You can find some information in but you will find much more information in the mojo implementation/specification.

But in fact no, you should not even rely on that to understand how to use a plugin.

3) Indeed a Maven plugin may support configurable properties : directly in the pom.xml and even export them for command line usage. But that is not automatic.
But in both cases, that has to be foreseen by the plugin developer and it is generally documented on the plugin or the source repository homepage.

In fact in your case, if you go into the Mojo implementation : AbstractH2Mojo, you can see how the configuration is set.

All properties have default values in the mojo constructor.

 protected AbstractH2Mojo() {
    super();
    final Service tcpService = new Service("tcp", Service.getDefaultPort("tcp"), false, false);
    this.setServices(Collections.singletonList(tcpService));
    this.setPort(Service.getDefaultPort("tcp"));
    this.setShutdownPassword("h2-maven-plugin");
    this.setJava(new File(new File(new File(System.getProperty("java.home")), "bin"), "java"));
 }

The mojo empty constructor is first invoked, then all setter are invoked on the created instance.

It means that you can override any of these properties defined in that class at runtime by providing the property such as ${artifactIdPrefixWithoutMavenPlugin}.field.

Since the maven plugin is h2-maven-plugin, the prefix to refer is h2.

If you run that :

mvn -X com.edugility:h2-maven-plugin:1.0:spawn -Dh2.port=8084 -Dh2.useSSL=false

You could see in the output :

[DEBUG] Configuring mojo 'com.edugility:h2-maven-plugin:1.0:spawn' with basic configurator -->
[DEBUG]   (s) port = 8084
[DEBUG]   (s) shutdownHost = localhost
[DEBUG]   (s) shutdownPassword = h2-maven-plugin
[DEBUG]   (s) useSSL = false
[DEBUG] -- end configuration --
[DEBUG] Process arguments: [/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, /home/david/.m2/repository/com/h2database/h2/1.3.162/h2-1.3.162.jar, org.h2.tools.Server, -tcp, -tcpPassword, h2-maven-plugin, -tcpPort, 8084]

Concerning the h2 jar used, if you still look in the same class, you will see that part that retrieves the jar file from the classpath :

 public final File getH2() {
    final ProtectionDomain pd = Server.class.getProtectionDomain();
    assert pd != null;
    final CodeSource cs = pd.getCodeSource();
    assert cs != null;
    final URL location = cs.getLocation();
    assert location != null;
    try {
      return new File(location.toURI());
    } catch (final URISyntaxException wontHappen) {
      throw (InternalError)new InternalError().initCause(wontHappen);
    }
 }

It means that you have no way to change the H2 JAR used : from the command line when you run the plugin or from the plugin declaration in the pom.xml, since no property is defined in the Mojo to achieve that.

if you will change the H2 version, you need to change the version embedded by the plugin.   As a starter, you could try to fork the plugin GIT repository, change the h2 dependency used in the pom to match to your requirement and check whether in spite of the gap version, working with that plugin is a possible thing.

Note that you could add a new property of the Mojo to make it completely configurable such as :

mvn ... -Dh2Version=1.4.200

But in that case you will need to retrieve that. For example by performing a request to download the dependency from the m2 central repo for example.

And you should also ensure that only valid ranges of the h2 version are used.


问:
Single linked lists C++
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

```<code>#include <iostream>
#include <string>
using namespace std;

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout << p->data << " ";
        p = p->next;
    }
    cout << p->data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}
</code>```

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

答:
There is a bug in the node constructor. The argument data conflicts with the memeber variable named data. This should fix it:

```<code>node::node(int data){
    this->data = data;
    next = NULL;
}
</code>```

The better option is to rename the argument to something else. Also consider using an initialization list:

```<code>node::node(int d) : data(d), next(NULL) { }
</code>```

Title: Single linked lists C++

Body:
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

#include <iostream>
#include <string>
using namespace std;

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout <
data << " ";
        p = p->next;
    }
    cout <
data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

Body:
There is a bug in the node constructor. The argument data conflicts with the memeber variable named data. This should fix it:

node::node(int data){
    this->data = data;
    next = NULL;
}

The better option is to rename the argument to something else. Also consider using an initialization list:

node::node(int d) : data(d), next(NULL) { }


问:
Using ScrollView Programmatically in Swift 3
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

```<code>import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}
</code>```

答:
Copy and paste this controller in your project

```<code>class BaseScrollViewController: UIViewController {

lazy var contentViewSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 100)
lazy var scrollView: UIScrollView = {
    let view = UIScrollView(frame: .zero)
    view.backgroundColor = .white
    view.frame = self.view.bounds
    view.contentSize = contentViewSize
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()
lazy var containerView: UIView = {
    let v = UIView()
    v.backgroundColor = .white
    v.frame.size = contentViewSize
    return v
}()

override func viewDidLoad() {
    view.backgroundColor = .white
    view.addSubview(scrollView)
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    scrollView.addSubview(containerView)
    setupContainer(containerView)
    super.viewDidLoad()

}

public func setupContainer(_ container: UIView) {

}
</code>```

}

Usage for above code:

```<code>class ClientViewController: BaseScrollViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    // do your stuff here
}

override func setupContainer(_ container: UIView) {
    // add views here
}
</code>```

}

Body:
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}

Body:
Copy and paste this controller in your project

class BaseScrollViewController: UIViewController {

lazy var contentViewSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 100)
lazy var scrollView: UIScrollView = {
    let view = UIScrollView(frame: .zero)
    view.backgroundColor = .white
    view.frame = self.view.bounds
    view.contentSize = contentViewSize
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()
lazy var containerView: UIView = {
    let v = UIView()
    v.backgroundColor = .white
    v.frame.size = contentViewSize
    return v
}()

override func viewDidLoad() {
    view.backgroundColor = .white
    view.addSubview(scrollView)
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    scrollView.addSubview(containerView)
    setupContainer(containerView)
    super.viewDidLoad()

}

public func setupContainer(_ container: UIView) {

}

}

Usage for above code:

class ClientViewController: BaseScrollViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    // do your stuff here
}

override func setupContainer(_ container: UIView) {
    // add views here
}

}


问:
What's the best way to design a DynamoDB table to store cloudwatch alarms
Actually i'm using Cloudwatch to generate alarms for my different services (Elasticsearch, RDS, ELB, ...) and my goal is to store these alarms in a DynamoDB table.

These are the fieds that i will store :

```<code> - Service (Elasticsearch, RDS, ELB, ...)
 - Priority of the alert(P1,P2,P3,P4)
 - Datetime
 - Resource Name
 - Status
 - Reason
</code>```

Is it ok to design the table like that :

```<code>id = Service#Priority
sort_key = Datetime
</code>```

Or simply :

```<code>id = Service
sort_key = Datetime
</code>```

I'm not sure what's the best approach to use to better design the table.

NOTE : About 50 alerts will be stored each day.

Thanks.

答:
Is this 50 alerts per service/resource combination or 50 overall? Why not schedule an export from AWS Cloudwatch and have your analytics built on the S3/Athena combination. </p>

<p>You should also consider using AWS EMR for such log analytics use cases. Any reason why you are building your solution on DynamoDB, as any of the above partition techniques may tend to create hot spots which will be performance dampener.  </p>

Body:
Actually i'm using Cloudwatch to generate alarms for my different services (Elasticsearch, RDS, ELB, ...) and my goal is to store these alarms in a DynamoDB table.

These are the fieds that i will store :

 - Service (Elasticsearch, RDS, ELB, ...)
 - Priority of the alert(P1,P2,P3,P4)
 - Datetime
 - Resource Name
 - Status
 - Reason

Is it ok to design the table like that :

id = Service#Priority
sort_key = Datetime

Or simply :

id = Service
sort_key = Datetime

I'm not sure what's the best approach to use to better design the table.

NOTE : About 50 alerts will be stored each day.

Thanks.

Body:
Is this 50 alerts per service/resource combination or 50 overall? Why not schedule an export from AWS Cloudwatch and have your analytics built on the S3/Athena combination.

You should also consider using AWS EMR for such log analytics use cases. Any reason why you are building your solution on DynamoDB, as any of the above partition techniques may tend to create hot spots which will be performance dampener.


问:
GettUncaught Error: reCAPTCHA placeholder element must be empty ; loaded only once
I'm getting following error on using v2 invisible capcha

recaptcha__en.js:513 Uncaught Error: reCAPTCHA placeholder element
  must be empty
      at YG (recaptcha__en.js:513)
      at recaptcha__en.js:520
      at Array.forEach ()
      at pG (recaptcha__en.js:520)
      at xG (recaptcha__en.js:517)
      at recaptcha__en.js:507
      at j$ (recaptcha__en.js:304)
      at RZ (recaptcha__en.js:507)
      at recaptcha__en.js:523
      at recaptcha__en.js:543

I have searched but everywhere it is saying you are loading script multiple times, which I think i'm not doing

Following is my code

```<code>
    <div class="osnlogin-button">
        <a type="submit" href="" id="recaptcha-submit" class="osnlogin-signin-btn g-recaptcha"><span class="signin lightboxed">Login</span></a>
    </div>
    <div class="g-recaptcha" data-sitekey="xxx" data-bind="recaptcha-submit" data-callback="onCapchaValidated">
    </div>

</code>```

```<code>    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    var onCapchaValidated = function () {
        $('#loginForm').submit();
    };
</code>```

答:
Just fixed it. Was using "g-recaptcha" class on more than one attribute. I think it should be only on one element in a page.

Original

```<code> <div class="osnlogin-button">
    <a type="submit" href="" id="recaptcha-submit" class="osnlogin-signin-btn g-recaptcha"><span class="signin lightboxed">Login</span></a>
</div>
<div class="g-recaptcha" data-sitekey="xxx" data-bind="recaptcha-submit" data-callback="onCapchaValidated">
</div>
</code>```

Updated

```<code><div class="osnlogin-button">
    <a type="submit" href="" id="recaptcha-submit" class="osnlogin-signin-btn"><span class="signin lightboxed">Login</span></a>
</div>
<div class="g-recaptcha" data-sitekey="xxx" data-bind="recaptcha-submit" data-callback="onCapchaValidated">
</div>
</code>```

It worked finally

Body:
I'm getting following error on using v2 invisible capcha

recaptcha__en.js:513 Uncaught Error: reCAPTCHA placeholder element
  must be empty
      at YG (recaptcha__en.js:513)
      at recaptcha__en.js:520
      at Array.forEach ()
      at pG (recaptcha__en.js:520)
      at xG (recaptcha__en.js:517)
      at recaptcha__en.js:507
      at j$ (recaptcha__en.js:304)
      at RZ (recaptcha__en.js:507)
      at recaptcha__en.js:523
      at recaptcha__en.js:543

I have searched but everywhere it is saying you are loading script multiple times, which I think i'm not doing

Following is my code

        Login

    var onCapchaValidated = function () {
        $('#loginForm').submit();
    };

Body:
Just fixed it. Was using "g-recaptcha" class on more than one attribute. I think it should be only on one element in a page.

Original

 <div class="osnlogin-button">
    <a type="submit" href="" id="recaptcha-submit" class="osnlogin-signin-btn g-recaptcha"><span class="signin lightboxed">Login</span></a>
</div>
<div class="g-recaptcha" data-sitekey="xxx" data-bind="recaptcha-submit" data-callback="onCapchaValidated">
</div>

Updated

<div class="osnlogin-button">
    <a type="submit" href="" id="recaptcha-submit" class="osnlogin-signin-btn"><span class="signin lightboxed">Login</span></a>
</div>
<div class="g-recaptcha" data-sitekey="xxx" data-bind="recaptcha-submit" data-callback="onCapchaValidated">
</div>

It worked finally


问:
why this regular does not Match the html using python
the html is :

```<code><div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のｽﾃｰﾀｽ</span>
</div>
</code>```

my Regular is :

```<code>a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+)</span>
</div>
'''
</code>```

but this Regular does not Match the html ,

so what is wrong  ?

thanks

答: At the very least, you have a case-sensitivity problem in the color.  Plus, you might want to meditate on BoltClock's comment.</p>

Body:
the html is :

{{rk_user.name}}のｽﾃｰﾀｽ

my Regular is :

a = r'''

\s*(.+)

'''

but this Regular does not Match the html ,

so what is wrong  ?

thanks


问:
How to create proper Find***.cmake file
I wrote a simple Find***.cmake file for my project which works fine on Windows,

```<code>if(WIN32)
    find_path(Shaderc_INCLUDE_DIR
            NAMES shaderc/shaderc.hpp
            PATH "$ENV{VULKAN_SDK}/Include")
    find_library(Shaderc_LIBRARY
            NAMES shaderc_combined
            PATH "$ENV{VULKAN_SDK}/Lib")
elseif(UNIX)
    find_path(Shaderc_INCLUDE_DIR
            NAMES shaderc/shaderc.hpp
            PATH "$ENV{SHADERC_DIR}/include")
    find_library(Shaderc_LIBRARY
            NAMES libshaderc_combined
            PATH "$ENV{SHADERC_DIR}/lib")
endif()
set(Shaderc_INCLUDE_DIRS ${Shaderc_INCLUDE_DIR})
set(Shaderc_LIBRARIES ${Shaderc_LIBRARY})
</code>```

, but throws an error on Linux. The error message is:

CMake Error: The following variables are used in this project, but
  they are set to NOTFOUND. Please set them or make sure they are set
  and tested correctly in the CMake files: Shaderc_LIBRARY

If I copy this code to my main CMakeLists file it compiles fine on Linux as well. What I'm doing wrong? Is it a bad practice to use environment variables on Linux for this purpose?

Thanks for your help!

答:
Well, judging from the code, your module looks in directories specified by environmental variables.

Instead, you should make it search in well-known places, like /usr/lib or /usr/local/lib.

Title: How to create proper Find***.cmake file

Body:
I wrote a simple Find***.cmake file for my project which works fine on Windows,

if(WIN32)
    find_path(Shaderc_INCLUDE_DIR
            NAMES shaderc/shaderc.hpp
            PATH "$ENV{VULKAN_SDK}/Include")
    find_library(Shaderc_LIBRARY
            NAMES shaderc_combined
            PATH "$ENV{VULKAN_SDK}/Lib")
elseif(UNIX)
    find_path(Shaderc_INCLUDE_DIR
            NAMES shaderc/shaderc.hpp
            PATH "$ENV{SHADERC_DIR}/include")
    find_library(Shaderc_LIBRARY
            NAMES libshaderc_combined
            PATH "$ENV{SHADERC_DIR}/lib")
endif()
set(Shaderc_INCLUDE_DIRS ${Shaderc_INCLUDE_DIR})
set(Shaderc_LIBRARIES ${Shaderc_LIBRARY})

, but throws an error on Linux. The error message is:

CMake Error: The following variables are used in this project, but
  they are set to NOTFOUND. Please set them or make sure they are set
  and tested correctly in the CMake files: Shaderc_LIBRARY

If I copy this code to my main CMakeLists file it compiles fine on Linux as well. What I'm doing wrong? Is it a bad practice to use environment variables on Linux for this purpose?

Thanks for your help!


问:
Angular material radio button unchecked on opening angular modal pop up
We are using angular material mat radio button and it is selected.  This radio button gets unchecked on opening angular modal pop up with another set of angular material radio button.</p>

```<code><mat-radio-group class="example-radio-group" formControlName="selectedToRole" [name]="selectedRole"  >
                                <mat-radio-button *ngFor="let item of rolesForTransferToRadio"  [value]="item.role" (change)="displayBasedOnSelectedRole(item.role)">
                                    <span class="labelFontsValue col-md-3">{{item.roleCode}} </span>
                                </mat-radio-button>
                            </mat-radio-group>

```Typescript
this.modalReference = this.modalService.open(loadPlantLocationsContent);
</code>```

答:
If I understood your question correctly, you are looking for radio button selected by default

Can you try adding the following CSS class to radio button

```<code>mat-radio-checked
</code>```

Body:
We are using angular material mat radio button and it is selected.  This radio button gets unchecked on opening angular modal pop up with another set of angular material radio button.

<mat-radio-group class="example-radio-group" formControlName="selectedToRole" [name]="selectedRole"  >
                                <mat-radio-button *ngFor="let item of rolesForTransferToRadio"  [value]="item.role" (change)="displayBasedOnSelectedRole(item.role)">
                                    {{item.roleCode}}
                                </mat-radio-button>
                            </mat-radio-group>

```Typescript
this.modalReference = this.modalService.open(loadPlantLocationsContent);

Body:
If I understood your question correctly, you are looking for radio button selected by default

Can you try adding the following CSS class to radio button

mat-radio-checked


问:
react-redux connect() function mapStateToProps is updating but component not re-rendering
I'm using React, Redux and React-Redux Provider function

```<code>const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return store.textTwo;
};
</code>```

if I use above mapStateToProps function to connect method of react-redux and update the state it will console.log changes in mapStateToProps function but not a rerendering component, not even it comes componentWillReceiveProps hook.

but when I add spread operator i.e. mutate the mapStateToProps return data it will re-render the complete component.

```<code>const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return { ...store.textTwo }; <-- this will re render complete component
};
</code>```

how to pass state to props of the component without re-rendering complete component.

--- Update ---

sample state data

```<code>store = {
    textTwo: {
        headerText: 'Sample',
        list: [
            {
                id: 1,
                name: 'test 1'
            }
        ]
    },
    text: {}
}
</code>```

headerText is a child component to show the header title.
the list is an Array of data that I'm iterating and listing name.

Tried below solution (given by @Siva Kondapi Venkata) and it's working but if I add a new item in the list, the header component is also re-rendering.

```<code>const mapStateToProps = (store: any) => ({
  textTwo: store.textTwo
});
</code>```

答:
You need to do like this. Return the props you are interested.

```<code>const mapStateToProps = (store: any) => ({
  textTwo: store.textTwo
});

const mapDispatchToProps = {

};

export default connect(mapStateToProps, mapDispatchToProps)(Component);
</code>```

Body:
I'm using React, Redux and React-Redux Provider function

const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return store.textTwo;
};

if I use above mapStateToProps function to connect method of react-redux and update the state it will console.log changes in mapStateToProps function but not a rerendering component, not even it comes componentWillReceiveProps hook.

but when I add spread operator i.e. mutate the mapStateToProps return data it will re-render the complete component.

const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return { ...store.textTwo }; <-- this will re render complete component
};

how to pass state to props of the component without re-rendering complete component.

--- Update ---

sample state data

store = {
    textTwo: {
        headerText: 'Sample',
        list: [
            {
                id: 1,
                name: 'test 1'
            }
        ]
    },
    text: {}
}

headerText is a child component to show the header title.
the list is an Array of data that I'm iterating and listing name.

Tried below solution (given by @Siva Kondapi Venkata) and it's working but if I add a new item in the list, the header component is also re-rendering.

const mapStateToProps = (store: any) => ({
  textTwo: store.textTwo
});

Body:
You need to do like this. Return the props you are interested.

const mapStateToProps = (store: any) => ({
  textTwo: store.textTwo
});

const mapDispatchToProps = {

};

export default connect(mapStateToProps, mapDispatchToProps)(Component);


问:
Is there any way to customize the UNnotification for local notifications in swift
I am new to Xcode and swift. I want to know that is there any way that we can customize the local notifications. If possible I also want to add a map on the notification.
 Thanks in advance</p>

答:
You can add a target from File -> New -> Target -> Notification Content Extension
which will add an extension for your custom UI. Set the UNNotificationExtensionCategory to the string identifier.

If you want to add a map on the notification , add a Mapkit View  into storyboard in the extension. I have attached the code for the map:

```<code>import UIKit
import UserNotifications
import UserNotificationsUI
import MapKit
import CoreLocation

class NotificationViewController: UIViewController, UNNotificationContentExtension{

  //  @IBOutlet weak var mapView: MKMapView!

    @IBOutlet var label: UILabel?
   fileprivate let locationManager:CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.startUpdatingLocation()
       // mapView.showsUserLocation = true

    }

    func didReceive(_ notification: UNNotification) {
        //self.label?.text = notification.request.content.body

        self.label?.text = "Reminder for your charging "
    }

    @IBAction func notibutton(_ sender: Any) {

    }

}
</code>```

Body:
You can add a target from File -> New -> Target -> Notification Content Extension
which will add an extension for your custom UI. Set the UNNotificationExtensionCategory to the string identifier.

If you want to add a map on the notification , add a Mapkit View  into storyboard in the extension. I have attached the code for the map:

import UIKit
import UserNotifications
import UserNotificationsUI
import MapKit
import CoreLocation

class NotificationViewController: UIViewController, UNNotificationContentExtension{

  //  @IBOutlet weak var mapView: MKMapView!

    @IBOutlet var label: UILabel?
   fileprivate let locationManager:CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.startUpdatingLocation()
       // mapView.showsUserLocation = true

    }

    func didReceive(_ notification: UNNotification) {
        //self.label?.text = notification.request.content.body

        self.label?.text = "Reminder for your charging "
    }

    @IBAction func notibutton(_ sender: Any) {

    }

}


问:
Auto select value of dropdown
i have an dropdown like this:

```<code><select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....
</code>```

VM name:

```<code> 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191
</code>```

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....

答:
I'm afraid form controls are notoriously difficult to style. Even if you do something dynamically with JavaScript, you would have to put a lot of work in to make it consistent across browsers. If your user base is narrow enough, you could play around with things like the overflow or min-width properties and see what they do on your browser of choice. Some have browser-specific rules, or have hidden elements inside that have different effects than their containers.

I know that doesn't help much. Sorry.

Title: Auto select value of dropdown

Body:
i have an dropdown like this:

<select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....

VM name:

 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....


问:
Create a JSON list from database entity framework
So I looked around but can't seem to find quite what I'm looking for.

I want to fetch a list of all my users in the database.
I know that I can create a new User object, but I want the object to be created from the database, and return in a JSON format. I'm using entityframework.

```<code>    TimeFlowDbContext db = new TimeFlowDbContext();

    private List<User> _users = new List<User>
    {
        new User {
            UserId = 1,
            Firstname = "Test",
            Lastname = "Man",
            Username = "test",
            Password = "test"
        }
    };
</code>```

I've tried a lot of different things, but I don't really understand how to list them from my database and return JSON..

Thanks in advance if anyone can link me some documentations or explain the right answer.

答:
You can use Newtonsoft.JSON library for this. You can get this from Global Nuget Store.

Code to covert your entity farmework object as JSON.

```<code>    var settings = new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Error = (sender, args) =>
        {
            args.ErrorContext.Handled = true;
        },
    };

    using(var db = new TimeFlowDbContext();)
    {
        var user = db.Users.First();
        return JsonConvert.SerializeObject(user, settings);
    }
</code>```

Body:
So I looked around but can't seem to find quite what I'm looking for.

I want to fetch a list of all my users in the database.
I know that I can create a new User object, but I want the object to be created from the database, and return in a JSON format. I'm using entityframework.

    TimeFlowDbContext db = new TimeFlowDbContext();

    private List<User> _users = new List<User>
    {
        new User {
            UserId = 1,
            Firstname = "Test",
            Lastname = "Man",
            Username = "test",
            Password = "test"
        }
    };

I've tried a lot of different things, but I don't really understand how to list them from my database and return JSON..

Thanks in advance if anyone can link me some documentations or explain the right answer.

Body:
You can use Newtonsoft.JSON library for this. You can get this from Global Nuget Store.

Code to covert your entity farmework object as JSON.

    var settings = new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Error = (sender, args) =>
        {
            args.ErrorContext.Handled = true;
        },
    };

    using(var db = new TimeFlowDbContext();)
    {
        var user = db.Users.First();
        return JsonConvert.SerializeObject(user, settings);
    }


问:
Need some clarity with GAS userProperties
I'm programming a Telegram bot with GAS. Am I right in thinking that whenever I store something using userProperties, like

```<code>userProperties.setProperty('name', 'Alex');
</code>```

the value gets stored for this particular instance of the script AND this particular user? Does it mean that if there are 10 more or less simultaneous instances of this script by ten different users, I will later be able to retrieve each user's respective name by calling

```<code>var username = userProperties.getProperty('name');
</code>```

I get the impression that sometimes there's some sort of interference happening that results in retrieving values different from those stored for this or that user. Would appreciate some clarity here.

答:
IMPORTANT:

UserProperties has been deprecated, use PropertiesService.getUserProperties() instead.

As you can see in the documentation

getUserProperties()

Gets a property store that only the current user
can access, and only within this script.

So indeed, if the script can be accessed by several users, PropertiesService.getUserProperties() will always retrieve the properties of the specific user who runs the script, and if there will be 10 simultaneous script executions - each user executing the script will retrieve different user properties.

Body:
I'm programming a Telegram bot with GAS. Am I right in thinking that whenever I store something using userProperties, like

userProperties.setProperty('name', 'Alex');

the value gets stored for this particular instance of the script AND this particular user? Does it mean that if there are 10 more or less simultaneous instances of this script by ten different users, I will later be able to retrieve each user's respective name by calling

var username = userProperties.getProperty('name');

I get the impression that sometimes there's some sort of interference happening that results in retrieving values different from those stored for this or that user. Would appreciate some clarity here.