问:
Show search bar with action (bar item)
I have a problem with search bar. I need to create a table view with a search button in the right corner, and when I click on it, it should show the search bar.

My code is here:

```<code>// Search controller
searchController = ({
    let controller = UISearchController(searchResultsController: nil)
    controller.delegate = self
    controller.searchBar.delegate = self
    controller.searchResultsUpdater = self
    controller.dimsBackgroundDuringPresentation = false
    controller.hidesNavigationBarDuringPresentation = true
    controller.searchBar.sizeToFit()
    return controller
})()
</code>```

And here is action:

```<code>// Search action
@IBAction func search(sender: UIBarButtonItem) {
    print("Open search")
    searchController.active = true
    if searchController.searchBar.isFirstResponder() == false {
        searchController.searchBar.becomeFirstResponder()
    }
}
</code>```

When I click on the button, nothing happens (only prints text in console), and what I want is in the image below:

答:
Old question, but want to add a new answer (maybe things changed since the original answer from 2016).

Simply call this on the view controller, assuming you already set up the search controller. No need to conform to UISearchBarDelegate:

Swift 5

```<code>present(searchController, animated: true, completion: nil)
</code>```

Title: Show search bar with action (bar item)

Body:
I have a problem with search bar. I need to create a table view with a search button in the right corner, and when I click on it, it should show the search bar.

My code is here:

// Search controller
searchController = ({
    let controller = UISearchController(searchResultsController: nil)
    controller.delegate = self
    controller.searchBar.delegate = self
    controller.searchResultsUpdater = self
    controller.dimsBackgroundDuringPresentation = false
    controller.hidesNavigationBarDuringPresentation = true
    controller.searchBar.sizeToFit()
    return controller
})()

And here is action:

// Search action
@IBAction func search(sender: UIBarButtonItem) {
    print("Open search")
    searchController.active = true
    if searchController.searchBar.isFirstResponder() == false {
        searchController.searchBar.becomeFirstResponder()
    }
}

When I click on the button, nothing happens (only prints text in console), and what I want is in the image below:

Body:
Old question, but want to add a new answer (maybe things changed since the original answer from 2016).

Simply call this on the view controller, assuming you already set up the search controller. No need to conform to UISearchBarDelegate:

Swift 5

present(searchController, animated: true, completion: nil)


来源: stackexchange

问:
await with null propagation System.NullReferenceException
I have the following code:

```<code>await _user?.DisposeAsync();
</code>```

Visual Studio highlights this code, saying 'Possible NullReferenceException'

by the way, without await Visual Studio doesn't show this warning
Why NullReferenceException is possible here?

答: await is expecting a result. If _user is null then the result will be null, hence the NullReferenceException.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the following code:

await _user?.DisposeAsync();

Visual Studio highlights this code, saying 'Possible NullReferenceException'

by the way, without await Visual Studio doesn't show this warning
Why NullReferenceException is possible here?


问:
Why doesn't my use of "protected" work?
I have read that a protected member can be accessed from derived classes, but the following does not work.</p>

```<code>class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}
</code>```

答:
You can access to it through the same class not as a public member of the base class.

```<code>class A
{
    protected int Test;
}

class B:A
{
    void TestMethod()
    {
         this.Test = 3; // Possible
    }
}
</code>```

Check protected access modifier in C#.

ContentLicense: CC BY-SA 3.0

Title: Why doesn't my use of "protected" work?

Body:
I have read that a protected member can be accessed from derived classes, but the following does not work.

class A
{
    protected int Test;
}
class B:A
{
    A instanceOfA= new A()

    public B()
    {
        instanceOfA.Test //Not possible
    }
}

Body:
You can access to it through the same class not as a public member of the base class.

class A
{
    protected int Test;
}

class B:A
{
    void TestMethod()
    {
         this.Test = 3; // Possible
    }
}

Check protected access modifier in C#.


问:
how can I generate previous state of conway's game of life algorithm?
suppose we have ith state of conway's game of life algorithm how can I generate a previous state of this algorithm

I have no idea about this problem

答:
Conway's Game of Life, one of the most famous cellular automaton rules, is not reversible: for instance, it has many patterns that die out completely, so the configuration in which all cells are dead has many predecessors, and it also has Garden of Eden patterns with no predecessors. However, another rule called "Critters" by its inventors, Tommaso Toffoli and Norman Margolus, is reversible and has similar dynamic behavior to Life.

From https://en.wikipedia.org/wiki/Reversible_cellular_automaton


答: Async methods return a Task that can be awaited.  If _user is null then you would not be returning a Task but null instead

Title: await with null propagation System.NullReferenceException


问:
Calling a Powershell Runspace Scriptblock from a remote file
I am working on a project which starts with a GUI Wizard to get some info from the user such as EndPoint FQDN, Username, Password, etc..

Once the User has provided all required info and reach to the final page in the GUI, a start button will be ready for him to click. Once this Start button is clicked, the tool will call 32 different scripts that are located into separate files.

To make the GUI more responsive and overcome the hanging issues as well as adding multithreading and better performance, I am using Runspace and RunspcaePools. So the GUI itself is running in a Runspace and once the user clicks on start a RunspacePool will be created and for each script form the 32 scripts there would be a Powershell session created and invoked.

The GUI is working fine and everything is working as expected untill the start button. My issue is that I am not able to call those script files when I am adding the script to the PowerShell Session. it is just nothing happen. If I use Wait-Debugger, I do not see any errors it is as if the ScriptBlock I am passing to the Powershell session (that has the value of the path to the script I want to execute) is just a sting and not a ScriptBlock.

My Code is as follow:

```<code>    #   This Section will add all the required Subscript Files into variables to be called by the main code of the tool.
    $SubScriptFolderPath = $CurrentWorkingDirectory + "SubCode\Scripts\"
    $SubscriptFilePath = @{}
    $SubscriptFilePath.BasicVspherePowerCliData = $SubScriptFolderPath + "BasicVspherePowerCliData.ps1"
    $SubscriptFilePath.NsxManagerPowerCliData = $SubScriptFolderPath + "NsxManagerPowerCliData.ps1"
    $SubscriptFilePath.NsxManagerPowerNsxData = $SubScriptFolderPath + "NsxManagerPowerNsxData.ps1"
    $SubscriptFilePath.NsxManagerNsxCliData = $SubScriptFolderPath + "NsxManagerNsxCliData.ps1"
    $SubscriptFilePath.ControllerPowerCliData = $SubScriptFolderPath + "ControllerPowerCliData.ps1"
    $SubscriptFilePath.ControllerPowerNsxData = $SubScriptFolderPath + "ControllerPowerNsxData.ps1"
    $SubscriptFilePath.ControllerNsxCliData = $SubScriptFolderPath + "ControllerNsxCliData.ps1"
    $SubscriptFilePath.ControllerSshData = $SubScriptFolderPath + "ControllerSshData.ps1"
    $SubscriptFilePath.ClusterPowerCliData = $SubScriptFolderPath + "ClusterPowerCliData.ps1"
    $SubscriptFilePath.ClusterPowerNsxData = $SubScriptFolderPath + "ClusterPowerNsxData.ps1"
    $SubscriptFilePath.ClusterNsxApiData = $SubScriptFolderPath + "ClusterNsxApiData.ps1"
    $SubscriptFilePath.HostPowerCliData = $SubScriptFolderPath + "HostPowerCliData.ps1"
    $SubscriptFilePath.HostPowerNsxData = $SubScriptFolderPath + "HostPowerNsxData.ps1"
    $SubscriptFilePath.HostEsxCliData = $SubScriptFolderPath + "HostEsxCliData.ps1"
    $SubscriptFilePath.HostNsxCliData = $SubScriptFolderPath + "HostNsxCliData.ps1"
    $SubscriptFilePath.DvsPowerCliData = $SubScriptFolderPath + "DvsPowerCliData.ps1"
    $SubscriptFilePath.DvsPowerNsxData = $SubScriptFolderPath + "DvsPowerNsxData.ps1"
    $SubscriptFilePath.LogicalSwitchPowerCliData = $SubScriptFolderPath + "LogicalSwitchPowerCliData.ps1"
    $SubscriptFilePath.LogicalSwitchPowerNsxData = $SubScriptFolderPath + "LogicalSwitchPowerNsxData.ps1"
    $SubscriptFilePath.TransportZonePowerCliData = $SubScriptFolderPath + "TransportZonePowerCliData.ps1"
    $SubscriptFilePath.TransportZonePowerNsxData = $SubScriptFolderPath + "TransportZonePowerNsxData.ps1"
    $SubscriptFilePath.DlrPowerCliData = $SubScriptFolderPath + "DlrPowerCliData.ps1"
    $SubscriptFilePath.DlrPowerNsxData = $SubScriptFolderPath + "DlrPowerNsxData.ps1"
    $SubscriptFilePath.DlrNsxCliData = $SubScriptFolderPath + "DlrNsxCliData.ps1"
    $SubscriptFilePath.EsgPowerCliData = $SubScriptFolderPath + "EsgPowerCliData.ps1"
    $SubscriptFilePath.EsgPowerNsxData = $SubScriptFolderPath + "EsgPowerNsxData.ps1"
    $SubscriptFilePath.EsgNsxCliData = $SubScriptFolderPath + "EsgNsxCliData.ps1"
    $SubscriptFilePath.DfwPowerCliData = $SubScriptFolderPath + "DfwPowerCliData.ps1"
    $SubscriptFilePath.DfwPowerNSXData = $SubScriptFolderPath + "DfwPowerNSXData.ps1"
    $SubscriptFilePath.DumpEndPoints = $SubScriptFolderPath + "DumpEndPoints.ps1"

    #   Create  Sync HashTable (GuiHash) to allow readability across different Runscpases and add required variables.
    $Global:GuiHash = [hashtable]::Synchronized(@{ })
    $Global:GuiHash.IPCehckPattern = $IPRegex   #   Add the IPCehckPattern Variable to be used within other runspaces
    $Global:GuiHash.SubscriptFilePath = $SubscriptFilePath  #   Add the SubCodePaths Variable to be used within other runspaces

    #   Crate the Runspace that will be used for the GUI and configure settings. After, Open the Runspace and import variables.
    #   You must import variables that will be used in other Runspaces, thus importing the required variables to this Runspace.
    $GuiRunspace =[runspacefactory]::CreateRunspace()
    $GuiRunspace.ApartmentState = "STA"
    $GuiRunspace.ThreadOptions = "ReuseThread"
    $GuiRunspace.Open()
    $GuiRunspace.SessionStateProxy.SetVariable("GuiHash",$Global:GuiHash)
    $GuiRunspace.SessionStateProxy.SetVariable("XamlFilesArray",$XamlFilesArray)

    #   Create a PowerShell Session and add it to the Runspace.
    $GuiPSSession = [PowerShell]::Create()
    $GuiPSSession.Runspace = $GuiRunspace

    #   Create the GUI PowerShell Session ScriptBlock. This will be the main code of the tool.
    [void]$GuiPSSession.AddScript({

          [Some code that is taking care of GUI]

          $GuiHash.WizardFinalPageStart.Add_Click({

               #    Create Session State Object and Add GuiHash Variable to it
               $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
               $RunHash = New-object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'RunHash',$Global:GuiHash,$Null
               $InitialSessionState.Variables.Add($RunHash)
               #  Create Runspace Pool
               $RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1, $InitialSessionState, $Host)
               $RunspacePool.ApartmentState = "MTA"
               $RunspacePool.Open()
               ForEach ($ScriptBlock in $Global:GuiHash.SubscriptFilePath) {
                    $PowerShellSession = [PowerShell]::Create()
                    $PowerShellSession.RunspacePool = $RunspacePool
                    $PowerShellSession.AddScript({$ScriptBlock})
                    $PowerShellSession.BeginInvoke()
               }
          })

        #   Show Wizard Window.
        $Global:GuiHash.WizardMainWindow.ShowDialog() | Out-Null
    })

    $ShowGui = $GuiPSSession.BeginInvoke()
</code>```

I have tried many things such as:

Adding & to the beginning of the script path.

Adding . to the beginning of the script path.

Using Get-Content

Using the ScriptBlock System Object

$Scriptblock = [scriptblock]::Create((Get-Content $ScriptPath))

Nothing seems to work.
I would appreciate your help over this one.

Thanks

答:
I think I did the same mistake again, Sorry this project is making my mind to hang sometimes. You need to remove the brackets when calling a script block. so you need to call the script block as below</p>

```<code>$PowerShellSession.AddScript($ScriptBlock)
</code>```

Body:
I am working on a project which starts with a GUI Wizard to get some info from the user such as EndPoint FQDN, Username, Password, etc..

Once the User has provided all required info and reach to the final page in the GUI, a start button will be ready for him to click. Once this Start button is clicked, the tool will call 32 different scripts that are located into separate files.

To make the GUI more responsive and overcome the hanging issues as well as adding multithreading and better performance, I am using Runspace and RunspcaePools. So the GUI itself is running in a Runspace and once the user clicks on start a RunspacePool will be created and for each script form the 32 scripts there would be a Powershell session created and invoked.

The GUI is working fine and everything is working as expected untill the start button. My issue is that I am not able to call those script files when I am adding the script to the PowerShell Session. it is just nothing happen. If I use Wait-Debugger, I do not see any errors it is as if the ScriptBlock I am passing to the Powershell session (that has the value of the path to the script I want to execute) is just a sting and not a ScriptBlock.

My Code is as follow:

    #   This Section will add all the required Subscript Files into variables to be called by the main code of the tool.
    $SubScriptFolderPath = $CurrentWorkingDirectory + "SubCode\Scripts\"
    $SubscriptFilePath = @{}
    $SubscriptFilePath.BasicVspherePowerCliData = $SubScriptFolderPath + "BasicVspherePowerCliData.ps1"
    $SubscriptFilePath.NsxManagerPowerCliData = $SubScriptFolderPath + "NsxManagerPowerCliData.ps1"
    $SubscriptFilePath.NsxManagerPowerNsxData = $SubScriptFolderPath + "NsxManagerPowerNsxData.ps1"
    $SubscriptFilePath.NsxManagerNsxCliData = $SubScriptFolderPath + "NsxManagerNsxCliData.ps1"
    $SubscriptFilePath.ControllerPowerCliData = $SubScriptFolderPath + "ControllerPowerCliData.ps1"
    $SubscriptFilePath.ControllerPowerNsxData = $SubScriptFolderPath + "ControllerPowerNsxData.ps1"
    $SubscriptFilePath.ControllerNsxCliData = $SubScriptFolderPath + "ControllerNsxCliData.ps1"
    $SubscriptFilePath.ControllerSshData = $SubScriptFolderPath + "ControllerSshData.ps1"
    $SubscriptFilePath.ClusterPowerCliData = $SubScriptFolderPath + "ClusterPowerCliData.ps1"
    $SubscriptFilePath.ClusterPowerNsxData = $SubScriptFolderPath + "ClusterPowerNsxData.ps1"
    $SubscriptFilePath.ClusterNsxApiData = $SubScriptFolderPath + "ClusterNsxApiData.ps1"
    $SubscriptFilePath.HostPowerCliData = $SubScriptFolderPath + "HostPowerCliData.ps1"
    $SubscriptFilePath.HostPowerNsxData = $SubScriptFolderPath + "HostPowerNsxData.ps1"
    $SubscriptFilePath.HostEsxCliData = $SubScriptFolderPath + "HostEsxCliData.ps1"
    $SubscriptFilePath.HostNsxCliData = $SubScriptFolderPath + "HostNsxCliData.ps1"
    $SubscriptFilePath.DvsPowerCliData = $SubScriptFolderPath + "DvsPowerCliData.ps1"
    $SubscriptFilePath.DvsPowerNsxData = $SubScriptFolderPath + "DvsPowerNsxData.ps1"
    $SubscriptFilePath.LogicalSwitchPowerCliData = $SubScriptFolderPath + "LogicalSwitchPowerCliData.ps1"
    $SubscriptFilePath.LogicalSwitchPowerNsxData = $SubScriptFolderPath + "LogicalSwitchPowerNsxData.ps1"
    $SubscriptFilePath.TransportZonePowerCliData = $SubScriptFolderPath + "TransportZonePowerCliData.ps1"
    $SubscriptFilePath.TransportZonePowerNsxData = $SubScriptFolderPath + "TransportZonePowerNsxData.ps1"
    $SubscriptFilePath.DlrPowerCliData = $SubScriptFolderPath + "DlrPowerCliData.ps1"
    $SubscriptFilePath.DlrPowerNsxData = $SubScriptFolderPath + "DlrPowerNsxData.ps1"
    $SubscriptFilePath.DlrNsxCliData = $SubScriptFolderPath + "DlrNsxCliData.ps1"
    $SubscriptFilePath.EsgPowerCliData = $SubScriptFolderPath + "EsgPowerCliData.ps1"
    $SubscriptFilePath.EsgPowerNsxData = $SubScriptFolderPath + "EsgPowerNsxData.ps1"
    $SubscriptFilePath.EsgNsxCliData = $SubScriptFolderPath + "EsgNsxCliData.ps1"
    $SubscriptFilePath.DfwPowerCliData = $SubScriptFolderPath + "DfwPowerCliData.ps1"
    $SubscriptFilePath.DfwPowerNSXData = $SubScriptFolderPath + "DfwPowerNSXData.ps1"
    $SubscriptFilePath.DumpEndPoints = $SubScriptFolderPath + "DumpEndPoints.ps1"

    #   Create  Sync HashTable (GuiHash) to allow readability across different Runscpases and add required variables.
    $Global:GuiHash = [hashtable]::Synchronized(@{ })
    $Global:GuiHash.IPCehckPattern = $IPRegex   #   Add the IPCehckPattern Variable to be used within other runspaces
    $Global:GuiHash.SubscriptFilePath = $SubscriptFilePath  #   Add the SubCodePaths Variable to be used within other runspaces

    #   Crate the Runspace that will be used for the GUI and configure settings. After, Open the Runspace and import variables.
    #   You must import variables that will be used in other Runspaces, thus importing the required variables to this Runspace.
    $GuiRunspace =[runspacefactory]::CreateRunspace()
    $GuiRunspace.ApartmentState = "STA"
    $GuiRunspace.ThreadOptions = "ReuseThread"
    $GuiRunspace.Open()
    $GuiRunspace.SessionStateProxy.SetVariable("GuiHash",$Global:GuiHash)
    $GuiRunspace.SessionStateProxy.SetVariable("XamlFilesArray",$XamlFilesArray)

    #   Create a PowerShell Session and add it to the Runspace.
    $GuiPSSession = [PowerShell]::Create()
    $GuiPSSession.Runspace = $GuiRunspace

    #   Create the GUI PowerShell Session ScriptBlock. This will be the main code of the tool.
    [void]$GuiPSSession.AddScript({

          [Some code that is taking care of GUI]

          $GuiHash.WizardFinalPageStart.Add_Click({

               #    Create Session State Object and Add GuiHash Variable to it
               $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
               $RunHash = New-object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'RunHash',$Global:GuiHash,$Null
               $InitialSessionState.Variables.Add($RunHash)
               #  Create Runspace Pool
               $RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1, $InitialSessionState, $Host)
               $RunspacePool.ApartmentState = "MTA"
               $RunspacePool.Open()
               ForEach ($ScriptBlock in $Global:GuiHash.SubscriptFilePath) {
                    $PowerShellSession = [PowerShell]::Create()
                    $PowerShellSession.RunspacePool = $RunspacePool
                    $PowerShellSession.AddScript({$ScriptBlock})
                    $PowerShellSession.BeginInvoke()
               }
          })

        #   Show Wizard Window.
        $Global:GuiHash.WizardMainWindow.ShowDialog() | Out-Null
    })

    $ShowGui = $GuiPSSession.BeginInvoke()

I have tried many things such as:

Adding & to the beginning of the script path.

Adding . to the beginning of the script path.

Using Get-Content

Using the ScriptBlock System Object

$Scriptblock = [scriptblock]::Create((Get-Content $ScriptPath))

Nothing seems to work.
I would appreciate your help over this one.

Thanks

Body:
I think I did the same mistake again, Sorry this project is making my mind to hang sometimes. You need to remove the brackets when calling a script block. so you need to call the script block as below

$PowerShellSession.AddScript($ScriptBlock)


问:
VBA code for giving slides a constant name
I am trying to reduce the effort needed to keep a certain slide (lets call it SlideXYZ) up to date. SlideXYZ is an important content slide that can be found in multiple slide decks. I initially created slide objects that updated automatically when a change was made in the "source slide". However, slide objects unfortunately don't contain animations (they are simply a snapshot of the actual slide). I am now trying to write a VBA script that will search and replace SlideXYZ in each deck with a newer version of SlideXYZ. However, the slide number is dynamic (it changes when a new slide is added above). I need a static, constant reference to SlideXYZ.

I thought of copying SlideXYZ into all presentations once and then using the Slide.Name property to find all instances of it once an update is needed.

However, it appears that the Slide.Name is reassigned by powerpoint each time the slide is pasted into a new presentation. I need a reference that will not change so that I can find and replace SlideXYZ.

答:
@Asger's suggestion would work but a more consistent approach (IMO) would be to use tags. Any presentation, slide, or shape on a slide can have one or more bits of text attached in the form of a tag.

For example:

```<code>ActivePresentation.Slides(1).Tags.Add "SlideIdentifier", "Bob"
</code>```

will create a tag named SlideIdentifier with a value of Bob on slide #1 in the current presentation. These tags will travel with the slide, wherever it goes.

This page on the PowerPoint FAQ that I maintain has more info on using tags:

http://www.pptfaq.com/FAQ00815_Working_with_Tags_-and_a_bit_about_Functions-.htm

Body:
@Asger's suggestion would work but a more consistent approach (IMO) would be to use tags. Any presentation, slide, or shape on a slide can have one or more bits of text attached in the form of a tag.

For example:

ActivePresentation.Slides(1).Tags.Add "SlideIdentifier", "Bob"

will create a tag named SlideIdentifier with a value of Bob on slide #1 in the current presentation. These tags will travel with the slide, wherever it goes.

This page on the PowerPoint FAQ that I maintain has more info on using tags:

http://www.pptfaq.com/FAQ00815_Working_with_Tags_-and_a_bit_about_Functions-.htm


问:
How to build and manipulate the color of 4 squares?
I am asked to build an HTML and CSS page which contains 4 different colored squares that have a double size of each other(For ex. First one 2x2 px, second one 4x4, third one 8x8 and fourth one 16x16), and when the cursor is hovered on the square, the corresponding square receives the color of the square next to it.</p>

答:
```<code><div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<style>
 .box1{
  width:20px;
  height:20px;
  background-color:blue
}
 .box2{
  width:40px;
  height:40px;
  background-color:black
 }
.box3{
  width:80px;
  height:80px;
  background-color:yellow
}
.box4{
 width:160px;
 height:160px;
 background-color:green
}
<script>
 document.querySelector(".box1").addEventListener("mouseenter",function(){
 document.querySelector(".box3").style.backgroundColor="red";
})
<style>
</code>```

This is a link of a demo that does that for the first box. You will have to set the boxes that should change manually
https://jsfiddle.net/xj60tq4d/1/

Body:
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<style>
 .box1{
  width:20px;
  height:20px;
  background-color:blue
}
 .box2{
  width:40px;
  height:40px;
  background-color:black
 }
.box3{
  width:80px;
  height:80px;
  background-color:yellow
}
.box4{
 width:160px;
 height:160px;
 background-color:green
}
<script>
 document.querySelector(".box1").addEventListener("mouseenter",function(){
 document.querySelector(".box3").style.backgroundColor="red";
})
<style>

This is a link of a demo that does that for the first box. You will have to set the boxes that should change manually
https://jsfiddle.net/xj60tq4d/1/


答:
await null will throw a NullReferenceException. Therefore if _user is null, then _user?.DisposeAsync() will return null, and the await will throw.

You can do:

```<code>if (_user != null)
{
    await _user.DisposeAsync();
}
</code>```

(you might need a local copy of _user if it might change between reads)

or:

```<code>await (_user?.DisposeAsync() ?? ValueTask.CompletedTask);
</code>```

(Prior to .NET 5, you will need:)

```<code>await (_user?.DisposeAsync().AsTask() ?? Task.CompletedTask);
</code>```

Body:
await null will throw a NullReferenceException. Therefore if _user is null, then _user?.DisposeAsync() will return null, and the await will throw.

You can do:

if (_user != null)
{
    await _user.DisposeAsync();
}

(you might need a local copy of _user if it might change between reads)

or:

await (_user?.DisposeAsync() ?? ValueTask.CompletedTask);

(Prior to .NET 5, you will need:)

await (_user?.DisposeAsync().AsTask() ?? Task.CompletedTask);


问:
tests failing because user not authenticated
i'm using a before filter: authenticate_user! on my pages. I have cucumber tests that test behaviour on these pages, they're now failing because i don't have an authenticated user, what is the simplest way to make these tests pass? short of having to create a user each time and log him in? is there a way? i've tested that the page is not accessible if the user is not logged in, i dont want to have to test this each time i add a test for the page

using rails 3 , devise 1.2, cucumber

答:
You should write a reusable set of cucumber steps to log your user in for your tests.  This is the way Devise explicitly suggests in their readme for testing that a user is logged in and has a proper session.

You can create reusable cucumber steps, so you only need to write the steps to log a user in once, then you can just do:

```<code>Given a valid user is logged in
When ...
</code>```

There's a lot more info on using cucumber this way online, but if you want a simple example I found this one in the answer to this question.

Body:
You should write a reusable set of cucumber steps to log your user in for your tests.  This is the way Devise explicitly suggests in their readme for testing that a user is logged in and has a proper session.

You can create reusable cucumber steps, so you only need to write the steps to log a user in once, then you can just do:

Given a valid user is logged in
When ...

There's a lot more info on using cucumber this way online, but if you want a simple example I found this one in the answer to this question.


问:
Is there any reason why this php / mysql behaves differently on localhost and remote server?
I have my code working well on localhost, but when loaded on the remove server it behaves differently - the id on localhost shows as it should (see image) - id is in order.

However, on the remote server it is not, yet the code is identical!!

I have tried running just the sql query in myphpadmin on the remote server and it is fine.

```<code>$con = mysqli_connect("localhost", "******", "******", "ps10");

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

if ($_POST['selClass'] == 'All records' OR $_SESSION['selClass'] == 'All records') {
    $query_rs4 = "SELECT *
                  FROM  marker
                  INNER JOIN users ON marker.class = users.class";
} else {
    if (empty($_POST['selClass']) && empty($_SESSION['selClass'])) {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class";
    } else {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class
                      WHERE users.username='{$_SESSION['selClass']}'";
    }
}

$rs4 = mysqli_query($con, $query_rs4) or die(mysqli_error($con));
$row = mysqli_num_rows($rs4);

echo "There are ".$row." students in this class";
</code>```

答:
The reason is that the SQL query is returning multiple columns with the name id.

The the result array/hash allows only one 'id' element i.e. $row['id'] gets assigned a single value.

The difference between the two environments could be as simple as someone did an

```<code>ALTER TABLE `somereferencedtable` ADD `id` INT UNSIGNED ;
</code>```

And that broke the code.

The fix is to follow best practice patterns:

Ditch the lazy ass * from the SELECT, and explicitly specify the expressions to be returned, with all column references fully qualified. Where there are duplicate column names, provide aliases...

```<code>SELECT users.id AS id, marker.id AS marker_id, user.class, marker.sub, ...
  FROM
</code>```

This aid the future reader, not having to lookup which columns come from which tables, ... as well as avoiding the code breaking, when someone adds a column to a table in the future, causing "ambiguous column" error, or silently wrong behavior (as demonstrated in the question).

Also, without an ORDER BY clause, MySQL is free to return rows in any order.

Body:
I have my code working well on localhost, but when loaded on the remove server it behaves differently - the id on localhost shows as it should (see image) - id is in order.

However, on the remote server it is not, yet the code is identical!!

I have tried running just the sql query in myphpadmin on the remote server and it is fine.

$con = mysqli_connect("localhost", "******", "******", "ps10");

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: ".mysqli_connect_error();
}

if ($_POST['selClass'] == 'All records' OR $_SESSION['selClass'] == 'All records') {
    $query_rs4 = "SELECT *
                  FROM  marker
                  INNER JOIN users ON marker.class = users.class";
} else {
    if (empty($_POST['selClass']) && empty($_SESSION['selClass'])) {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class";
    } else {
        $query_rs4 = "SELECT *
                      FROM  marker
                      INNER JOIN users ON marker.class = users.class
                      WHERE users.username='{$_SESSION['selClass']}'";
    }
}

$rs4 = mysqli_query($con, $query_rs4) or die(mysqli_error($con));
$row = mysqli_num_rows($rs4);

echo "There are ".$row." students in this class";

Body:
The reason is that the SQL query is returning multiple columns with the name id.

The the result array/hash allows only one 'id' element i.e. $row['id'] gets assigned a single value.

The difference between the two environments could be as simple as someone did an

ALTER TABLE `somereferencedtable` ADD `id` INT UNSIGNED ;

And that broke the code.

The fix is to follow best practice patterns:

Ditch the lazy ass * from the SELECT, and explicitly specify the expressions to be returned, with all column references fully qualified. Where there are duplicate column names, provide aliases...

SELECT users.id AS id, marker.id AS marker_id, user.class, marker.sub, ...
  FROM

This aid the future reader, not having to lookup which columns come from which tables, ... as well as avoiding the code breaking, when someone adds a column to a table in the future, causing "ambiguous column" error, or silently wrong behavior (as demonstrated in the question).

Also, without an ORDER BY clause, MySQL is free to return rows in any order.


问:
Fail to run nodes across machines [corda]
I am trying to run CORDA blockchain network across machines by using java version source code (source code: https://github.com/corda/samples/cordapp-example), but fail to connect nodes in a single network.

If somebody can advise any missing steps or ways to check the connection fail, it will be very thankful. Thanks!

I follow instructions of https://docs.corda.net/tutorial-cordapp.html#running-nodes-across-machines for the network setup and form network as below:

Machine 1: Notary, PartyA, runnodes, runnodes.bat , runnodes.jar

Machine 2: PartyB, runnodes, runnodes.bat , runnodes.jar

Network Boostrapper Tool: https://www.corda.net/develop/resources.html

Notary_node.conf

```<code>devMode=true
myLegalName="O=Notary,L=London,C=GB"
notary {
    validating=false
}
p2pAddress="IP_address_of_machineA:10000"
rpcSettings {
    address="localhost:10001"
    adminAddress="localhost:10002"
}
</code>```

PartyA_node.conf

```<code>devMode=true
myLegalName="O=PartyA,L=London,C=GB"
p2pAddress="IP_address_of_machineA:10004"
rpcSettings {
    address="localhost:10005"
    adminAddress="localhost:10006"
}
security {
    authService {
        dataSource {
            type=INMEMORY
            users=[
                {
                    password=test
                    permissions=[
                        ALL
                    ]
                    user=user1
                }
            ]
        }
    }
}
</code>```

PartyB_node.conf

```<code>devMode=true
myLegalName="O=PartyB,L=New York,C=US"
p2pAddress="IP_address_of_machineB:10008"
rpcSettings {
    address="localhost:10009"
    adminAddress="localhost:10010"
}
security {
    authService {
        dataSource {
            type=INMEMORY
            users=[
                {
                    password=test
                    permissions=[
                        ALL
                    ]
                    user=user1
                }
            ]
        }
    }
}
</code>```

I see the following error in the node logs:

```<code>[ERROR] 15:18:45+0800 [Node thread-1] corda.flow.processEventsUntilFlowIsResumed - Flow interrupted while waiting for events, aborting immediately {actor_id=internalShell, actor_owning_identity=O=PartyA, L=London, C=GB, actor_store_id=NODE_CONFIG, fiber-id=10000003, flow-id=86f29b02-f5d2-4eac-9803-1de797cb43b3, invocation_id=e3c19de7-1052-412f-bc2a-05c1014f7fc3, invocation_timestamp=2019-05-21T06:57:58.807Z, origin=internalShell, session_id=7639f617-f126-4e0c-b4d1-5515f62a85cd, session_timestamp=2019-05-21T06:56:57.730Z, thread-id=181}
</code>```

答:
Try using the following in the node.conf for both nodes:

rpcSettings {
    address="0.0.0.0:10001"
    adminAddress="0.0.0.0:10002"
}```

Body:
I am trying to run CORDA blockchain network across machines by using java version source code (source code: https://github.com/corda/samples/cordapp-example), but fail to connect nodes in a single network.

If somebody can advise any missing steps or ways to check the connection fail, it will be very thankful. Thanks!

I follow instructions of https://docs.corda.net/tutorial-cordapp.html#running-nodes-across-machines for the network setup and form network as below:

Machine 1: Notary, PartyA, runnodes, runnodes.bat , runnodes.jar

Machine 2: PartyB, runnodes, runnodes.bat , runnodes.jar

Network Boostrapper Tool: https://www.corda.net/develop/resources.html

Notary_node.conf

devMode=true
myLegalName="O=Notary,L=London,C=GB"
notary {
    validating=false
}
p2pAddress="IP_address_of_machineA:10000"
rpcSettings {
    address="localhost:10001"
    adminAddress="localhost:10002"
}

PartyA_node.conf

devMode=true
myLegalName="O=PartyA,L=London,C=GB"
p2pAddress="IP_address_of_machineA:10004"
rpcSettings {
    address="localhost:10005"
    adminAddress="localhost:10006"
}
security {
    authService {
        dataSource {
            type=INMEMORY
            users=[
                {
                    password=test
                    permissions=[
                        ALL
                    ]
                    user=user1
                }
            ]
        }
    }
}

PartyB_node.conf

devMode=true
myLegalName="O=PartyB,L=New York,C=US"
p2pAddress="IP_address_of_machineB:10008"
rpcSettings {
    address="localhost:10009"
    adminAddress="localhost:10010"
}
security {
    authService {
        dataSource {
            type=INMEMORY
            users=[
                {
                    password=test
                    permissions=[
                        ALL
                    ]
                    user=user1
                }
            ]
        }
    }
}

I see the following error in the node logs:

[ERROR] 15:18:45+0800 [Node thread-1] corda.flow.processEventsUntilFlowIsResumed - Flow interrupted while waiting for events, aborting immediately {actor_id=internalShell, actor_owning_identity=O=PartyA, L=London, C=GB, actor_store_id=NODE_CONFIG, fiber-id=10000003, flow-id=86f29b02-f5d2-4eac-9803-1de797cb43b3, invocation_id=e3c19de7-1052-412f-bc2a-05c1014f7fc3, invocation_timestamp=2019-05-21T06:57:58.807Z, origin=internalShell, session_id=7639f617-f126-4e0c-b4d1-5515f62a85cd, session_timestamp=2019-05-21T06:56:57.730Z, thread-id=181}


问:
SQL Update using subquery
I'm trying to update a table using a sub query but it's not recognising the table alias, when I try and run it a box pops up with 't1.rDate', my query is:

```<code> UPDATE Results SET odds4 =
(SELECT SUM(IIF(odds >= 4, 1, 0)) FROM Results t1
GROUP BY t1.rDate, t1.rTime, t1.rTrack)
WHERE rDate = t1.rDate AND rTime = t1.rTime AND rTrack = t1.rTrack AND t1.rDate
>= #2019/05/28#;
</code>```

Example:

```<code>   rDate   | rTime | rTrack | horse   | odds | odds4
------------------------------------------------------
28/05/2019 | 13:00 | Ascot  | horse1  | 2.5  |  3
28/05/2019 | 13:00 | Ascot  | horse2  | 34   |  3
28/05/2019 | 13:00 | Ascot  | horse3  | 1.4  |  3
28/05/2019 | 13:00 | Ascot  | horse4  | 6    |  3
28/05/2019 | 13:00 | Ascot  | horse5  | 4    |  3
28/05/2019 | 14:30 | Epsom  | horse1  | 3    |  2
28/05/2019 | 14:30 | Epsom  | horse2  | 1.75 |  2
28/05/2019 | 14:30 | Epsom  | horse3  | 2    |  2
28/05/2019 | 14:30 | Epsom  | horse4  | 12   |  2
28/05/2019 | 14:30 | Epsom  | horse5  | 66   |  2
</code>```

答:
I think you want a correlated subquery:</p>

```<code>UPDATE Results
    SET odds4 = (SELECT SUM(IIF(t1.odds >= 4, 1, 0))
                 FROM Results t1
                 WHERE t1.rDate = Results.rDate AND
                       t1.rTime = Results.rTime AND
                       t1.rTrack = Results.rTrack
                )
WHERE Results.rDate >= #2019/05/28#;
</code>```

Title: SQL Update using subquery

Body:
I'm trying to update a table using a sub query but it's not recognising the table alias, when I try and run it a box pops up with 't1.rDate', my query is:

 UPDATE Results SET odds4 =
(SELECT SUM(IIF(odds >= 4, 1, 0)) FROM Results t1
GROUP BY t1.rDate, t1.rTime, t1.rTrack)
WHERE rDate = t1.rDate AND rTime = t1.rTime AND rTrack = t1.rTrack AND t1.rDate
>= #2019/05/28#;

Example:

   rDate   | rTime | rTrack | horse   | odds | odds4
------------------------------------------------------
28/05/2019 | 13:00 | Ascot  | horse1  | 2.5  |  3
28/05/2019 | 13:00 | Ascot  | horse2  | 34   |  3
28/05/2019 | 13:00 | Ascot  | horse3  | 1.4  |  3
28/05/2019 | 13:00 | Ascot  | horse4  | 6    |  3
28/05/2019 | 13:00 | Ascot  | horse5  | 4    |  3
28/05/2019 | 14:30 | Epsom  | horse1  | 3    |  2
28/05/2019 | 14:30 | Epsom  | horse2  | 1.75 |  2
28/05/2019 | 14:30 | Epsom  | horse3  | 2    |  2
28/05/2019 | 14:30 | Epsom  | horse4  | 12   |  2
28/05/2019 | 14:30 | Epsom  | horse5  | 66   |  2

Body:
I think you want a correlated subquery:

UPDATE Results
    SET odds4 = (SELECT SUM(IIF(t1.odds >= 4, 1, 0))
                 FROM Results t1
                 WHERE t1.rDate = Results.rDate AND
                       t1.rTime = Results.rTime AND
                       t1.rTrack = Results.rTrack
                )
WHERE Results.rDate >= #2019/05/28#;


问:
How to change the color of the HyperLink in ASP.NET
i am doing mini ERP project., in that i have 3 frames.
frame is used as Header where i have "Home" and "logout" image button
when i click "Home" the frame3 goes to Home page and when i click "Logout" button, all the frames disappears and main window of "Login" screen comes.
i have used "Home " and "Logout" button in image using Hyperlink control in ASP.NET
the problem is due to Hyperlink the button gets blue border around it.
i want to remove that border around the image button.
can any one knows how to remove that border
here my codes

```<code><asp:HyperLink ID="HomeButtonlink"
    BorderWidth="0px"
    Font-Overline = "False"
    ImageUrl="~/Images/Untitled-5.png"
    runat="server"
    Height="100%"
    Target ="frame3"
    NavigateUrl="~/About.aspx"
    BorderStyle="None"></asp:HyperLink>
</code>```

thanks in advances
A.S.Rajkumar.Rajguru

答:
I would create a new css class for this instead:

```<code><asp:HyperLink ID="HomeButtonlink" CssClass="linkbutton"
    ImageUrl="~/Images/Untitled-5.png"
    runat="server" Target="frame3" NavigateUrl="~/About.aspx"></asp:HyperLink>
</code>```

and you can define your class like this:

```<code>a.linkbutton, a.linkbutton:visited, a.linkbutton img
{
    border: none;
    outline: none;
}
</code>```

You gain very little by using the asp.net server control. You can do the same like this:

```<code><a href="<%=ResolveUrl("~/about.aspx")%>" target="frame3" class="linkbutton">
    <img src="<%=ResolveUrl("~/images/untitled-5.png") %>" />
</a>
</code>```

Body:
i am doing mini ERP project., in that i have 3 frames.
frame is used as Header where i have "Home" and "logout" image button
when i click "Home" the frame3 goes to Home page and when i click "Logout" button, all the frames disappears and main window of "Login" screen comes.
i have used "Home " and "Logout" button in image using Hyperlink control in ASP.NET
the problem is due to Hyperlink the button gets blue border around it.
i want to remove that border around the image button.
can any one knows how to remove that border
here my codes

<asp:HyperLink ID="HomeButtonlink"
    BorderWidth="0px"
    Font-Overline = "False"
    ImageUrl="~/Images/Untitled-5.png"
    runat="server"
    Height="100%"
    Target ="frame3"
    NavigateUrl="~/About.aspx"
    BorderStyle="None"></asp:HyperLink>

thanks in advances
A.S.Rajkumar.Rajguru

Body:
I would create a new css class for this instead:

<asp:HyperLink ID="HomeButtonlink" CssClass="linkbutton"
    ImageUrl="~/Images/Untitled-5.png"
    runat="server" Target="frame3" NavigateUrl="~/About.aspx"></asp:HyperLink>

and you can define your class like this:

a.linkbutton, a.linkbutton:visited, a.linkbutton img
{
    border: none;
    outline: none;
}

You gain very little by using the asp.net server control. You can do the same like this:

<a href="<%=ResolveUrl("~/about.aspx")%>" target="frame3" class="linkbutton">
    <img src="<%=ResolveUrl("~/images/untitled-5.png") %>" />
</a>


问:
Where should I place the event listener?
I made many of objects such as JButton, JLabel, JCheckBox, etc. And I've added an event listener to the object. Like this.
object obj = new obj();
obj.listneraddActionListener(){};
However, if listener uses other objects, that objects must be created before listener code.
I'm thinking about whether I should sort object definition in advance or pull all listeners to below.
What should I do for this?

Edit:: I'm sorry, I didn't post because the code was too big. the below is part of the code. I got error message from checkboxes(chkName, chkAddress, chkType, chkComment)

```<code>    JButton btnSearch = new JButton("");
    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String str = "";
            ResultSet rsSid, rsNM = null;
            int count = 0;

            if (chkName.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION "; ++count;}
            if (chkAddress.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "ADDR LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkType.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "TYPE LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkComment.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "COMMENT LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (count == 0) return;

            if (txtSearch.getText() != "")
                str = str.substring(0, str.length() - 7) + ';';
            else
                str = "SELECT * FROM " + tableName;

            rsSid = jdbc.executeQuery(conn, str);
            try {
                behindList.clear();
                lstSRmodel.clear();
                TableSummary temp = new TableSummary();
                while(rsSid.next()) {
                    for (int i = 1; i <= rsSid.getMetaData().getColumnCount(); ++i) {
                        temp.TABLE_SID = rsSid.getInt(i);
                        rsNM = jdbc.executeQuery(conn, "SELECT " + tableName + "_NM FROM " + tableName + " WHERE " + tableName + "_SID = " + temp.TABLE_SID + ";");
                        if (rsNM.next()) {
                            temp.TABLE_NM = rsNM.getString(1);
                            behindList.add(new TableSummary(temp.TABLE_SID, temp.TABLE_NM));
                            lstSRmodel.addElement(temp.TABLE_NM);
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    JCheckBox chkAll = new JCheckBox("\uC804\uCCB4");

    chkAll.setBounds(14, 75, 131, 27);
    contentPane.add(chkAll);

    JCheckBox chkName = new JCheckBox("\uC774\uB984");
    chkName.setBounds(14, 106, 131, 27);
    contentPane.add(chkName);

    JCheckBox chkAddress = new JCheckBox("\uC704\uCE58");
    chkAddress.setBounds(14, 137, 131, 27);
    contentPane.add(chkAddress);

    JCheckBox chkType = new JCheckBox("\uD0C0\uC785");
    chkType.setBounds(14, 168, 131, 27);
    contentPane.add(chkType);

    JCheckBox chkComment = new JCheckBox("\uC138\uBD80\uC0AC\uD56D");
    chkComment.setBounds(14, 199, 131, 27);
    contentPane.add(chkComment);
</code>```

答:
I am not sure if you have read this, but I would start by reading The Java™ Tutorials on Writing Event Listeners. This tutorial helped me a great deal when I was learning how to properly handle GUI events. Because there are so many events to handle, Java provides the primary interface called EventListener which has no methods (it's what is known as a Marker Interface). Each JComponent defines what kind of event it must handle. For example, JButton objects are concerned about different set of events than JFrame objects.

The best thing you can do is understand the basic premise of why this API is needed for. GUIs must be event-driven because there is no effective way to capture a user interaction right at the moment the action takes place. For example, a JButton object must listen, at least, to "click" events. This much should be obvious to you. But there are other events you probably didn't think about. For instance, mousing over the button to show a tool tip.

To your question,

If listener uses other objects, that objects must be created before listener code...
   What should I do for this?

There are a few ways to handle this. I am going to show you very simple cases that, hopefully, you can use to expand on. Suppose you have a panel with two buttons, OK and Cancel. Obviously, you know these two buttons will perform different functions when clicked. For this illustration, the job they will do is irrelevant. So, I am just going to print out some message when clicked. The code snippet below shows only the relevant pieces. To handle button clicks, you must add an ActionListener to each of the buttons.

```<code>public class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        String name = button.getName(); // Assuming you set "OK" and "Cancel" as the names
        if (name.equals("OK")
            System.out.println("I will comply with your command!");
        else
            System.out.println("You cancelled your request.");
    }
}
</code>```

Then, you can add a listener to your buttons like this...

```<code>MyActionListener listener = new MyActionListener();
cancelBtn.addActionListener(listener);
okBtn.addActionListener(listener);
</code>```

This solution should work fine, but it doesn't scale very well. If you were to add more buttons to your application, having a single listener like this is bad because your listener will become overworked. A slightly better solution is to provide each instance with its own listener. You can do this by taking advantage of Anonymous Classes. Here's how:

```<code>cancelBtn.addActionListener(new MyActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.out.println("I will comply with your command!");
    }
});
okBtn.addActionListener(new MyActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.out.println("You cancelled your request.");
    }
});
</code>```

Some people don't like anonymous classes very much because it affects the readability of your code. I happen to like the fact that each object's instance has its own personalized listener that does precisely the job that the object instance needs to do when the action takes place.

I think this approach should work for your case just fine. There are other ways as well, but I think you should start using this simple approach until you gain more knowledge on how to handle events. Let me know what you think.

Body:
I made many of objects such as JButton, JLabel, JCheckBox, etc. And I've added an event listener to the object. Like this.
object obj = new obj();
obj.listneraddActionListener(){};
However, if listener uses other objects, that objects must be created before listener code.
I'm thinking about whether I should sort object definition in advance or pull all listeners to below.
What should I do for this?

Edit:: I'm sorry, I didn't post because the code was too big. the below is part of the code. I got error message from checkboxes(chkName, chkAddress, chkType, chkComment)

    JButton btnSearch = new JButton("");
    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String str = "";
            ResultSet rsSid, rsNM = null;
            int count = 0;

            if (chkName.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + tableName + "_NM LIKE '%" + txtSearch.getText() + "%') UNION "; ++count;}
            if (chkAddress.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "ADDR LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkType.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "TYPE LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (chkComment.isSelected()) {str += "(SELECT " + tableName + "_SID FROM " + tableName + " WHERE " + "COMMENT LIKE '%" + txtSearch.getText() +"%') UNION "; ++count;}
            if (count == 0) return;

            if (txtSearch.getText() != "")
                str = str.substring(0, str.length() - 7) + ';';
            else
                str = "SELECT * FROM " + tableName;

            rsSid = jdbc.executeQuery(conn, str);
            try {
                behindList.clear();
                lstSRmodel.clear();
                TableSummary temp = new TableSummary();
                while(rsSid.next()) {
                    for (int i = 1; i <= rsSid.getMetaData().getColumnCount(); ++i) {
                        temp.TABLE_SID = rsSid.getInt(i);
                        rsNM = jdbc.executeQuery(conn, "SELECT " + tableName + "_NM FROM " + tableName + " WHERE " + tableName + "_SID = " + temp.TABLE_SID + ";");
                        if (rsNM.next()) {
                            temp.TABLE_NM = rsNM.getString(1);
                            behindList.add(new TableSummary(temp.TABLE_SID, temp.TABLE_NM));
                            lstSRmodel.addElement(temp.TABLE_NM);
                        }
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });

    JCheckBox chkAll = new JCheckBox("\uC804\uCCB4");

    chkAll.setBounds(14, 75, 131, 27);
    contentPane.add(chkAll);

    JCheckBox chkName = new JCheckBox("\uC774\uB984");
    chkName.setBounds(14, 106, 131, 27);
    contentPane.add(chkName);

    JCheckBox chkAddress = new JCheckBox("\uC704\uCE58");
    chkAddress.setBounds(14, 137, 131, 27);
    contentPane.add(chkAddress);

    JCheckBox chkType = new JCheckBox("\uD0C0\uC785");
    chkType.setBounds(14, 168, 131, 27);
    contentPane.add(chkType);

    JCheckBox chkComment = new JCheckBox("\uC138\uBD80\uC0AC\uD56D");
    chkComment.setBounds(14, 199, 131, 27);
    contentPane.add(chkComment);

Body:
I am not sure if you have read this, but I would start by reading The Java™ Tutorials on Writing Event Listeners. This tutorial helped me a great deal when I was learning how to properly handle GUI events. Because there are so many events to handle, Java provides the primary interface called EventListener which has no methods (it's what is known as a Marker Interface). Each JComponent defines what kind of event it must handle. For example, JButton objects are concerned about different set of events than JFrame objects.

The best thing you can do is understand the basic premise of why this API is needed for. GUIs must be event-driven because there is no effective way to capture a user interaction right at the moment the action takes place. For example, a JButton object must listen, at least, to "click" events. This much should be obvious to you. But there are other events you probably didn't think about. For instance, mousing over the button to show a tool tip.

To your question,

If listener uses other objects, that objects must be created before listener code...
   What should I do for this?

There are a few ways to handle this. I am going to show you very simple cases that, hopefully, you can use to expand on. Suppose you have a panel with two buttons, OK and Cancel. Obviously, you know these two buttons will perform different functions when clicked. For this illustration, the job they will do is irrelevant. So, I am just going to print out some message when clicked. The code snippet below shows only the relevant pieces. To handle button clicks, you must add an ActionListener to each of the buttons.

public class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        String name = button.getName(); // Assuming you set "OK" and "Cancel" as the names
        if (name.equals("OK")
            System.out.println("I will comply with your command!");
        else
            System.out.println("You cancelled your request.");
    }
}

Then, you can add a listener to your buttons like this...

MyActionListener listener = new MyActionListener();
cancelBtn.addActionListener(listener);
okBtn.addActionListener(listener);

This solution should work fine, but it doesn't scale very well. If you were to add more buttons to your application, having a single listener like this is bad because your listener will become overworked. A slightly better solution is to provide each instance with its own listener. You can do this by taking advantage of Anonymous Classes. Here's how:

cancelBtn.addActionListener(new MyActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.out.println("I will comply with your command!");
    }
});
okBtn.addActionListener(new MyActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.out.println("You cancelled your request.");
    }
});

Some people don't like anonymous classes very much because it affects the readability of your code. I happen to like the fact that each object's instance has its own personalized listener that does precisely the job that the object instance needs to do when the action takes place.

I think this approach should work for your case just fine. There are other ways as well, but I think you should start using this simple approach until you gain more knowledge on how to handle events. Let me know what you think.


问:
Java War File Will Not Update in Eclipse with WildFly
I am using Eclipse version 2019-03 (4.11.0) and Wildfly 16 on Windows 7 64-bit. I've converted my Java Web Project to a Maven one in Eclipse. The initial configuration and deployment through the wizards works but now anytime I make a change to my code and try to re-deploy I am not seeing the updated code. What I've tried so far(I actually am not sure how to make the re-deployment and assumed that one or a combination of the following would force a re-deployment):

Update Project (Alt + F5 and Right-click Project --> Maven --> Update Project)

mvn clean

mvn install

mvn clean install

Update Project followed by mvn clean install

Here is my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>GumboChannel</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>GumboChannel</name>
  <description></description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.1</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.2.Final</version>
</dependency>
  </dependencies>
</project>
</code>```

EDIT: I updated the question to clarify that I actually am not sure how to re-deploy.

答:
Actually, none of the options that you listed above redeploys the application.

Update Project: modifies the Eclipse project to take changes from pom.xml

mvn clean install (from CLI): runs Maven (outside Eclipse), cleans the target directory, compiles all sources into target directory, packages the .war file, installs it in the local .m2 repository. Usually you don't need this at all, just choose "Build automatically" from the menu.

I imagine you have configured Wildfly in the "Server" view of Eclipse. If you want to redeploy, you should find some kind of "Restart" and/or "Redeploy" command in that view.

Body:
I am using Eclipse version 2019-03 (4.11.0) and Wildfly 16 on Windows 7 64-bit. I've converted my Java Web Project to a Maven one in Eclipse. The initial configuration and deployment through the wizards works but now anytime I make a change to my code and try to re-deploy I am not seeing the updated code. What I've tried so far(I actually am not sure how to make the re-deployment and assumed that one or a combination of the following would force a re-deployment):

Update Project (Alt + F5 and Right-click Project --> Maven --> Update Project)

mvn clean

mvn install

mvn clean install

Update Project followed by mvn clean install

Here is my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>GumboChannel</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>GumboChannel</name>
  <description></description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.1</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.9</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.9</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.2.Final</version>
</dependency>
  </dependencies>
</project>

EDIT: I updated the question to clarify that I actually am not sure how to re-deploy.


问:
Swapping assemblies to implement DBMS-specific functionality
(continuation of my question here, but thought it was different enough to start a new thread)

I want to write an application that will allow the eventual customers to use their preferred DBMS (SQLServer, Oracle, etc) for the backend.

I could have the main app call a "Factory" object, located in a separate assembly, that will return a DBMS-specific object that implements a common interface containing all the calls required for DB access. However, this means having the compiled code for all possible DBMS systems deployed with every installation. The factory just chooses the configured assembly.

Could someone comment on this alternative method? : I could create separate assemblies for each DBMS that all use the same namespace e.g. MyDBMS, and implement the same interface. Upon installation, we'd only deploy the assembly for the customer's chosen DBMS. By changing the build configuration so that the assemblies all get the same name, COM ID, etc. then the main app wouldn't know the difference. I've tested this and it seems to work very well.

Just wondering about the pros/cons of this? The main benefit is that we could supply additional/updated DBMS DLLs without any other redeployment.

Thanks

答:
Yes, it's possible: this is how DBMS drivers -- such as those in ADO.NET -- work (except they have different names/assemblies while sharing the same interface/contract).

If swapping assemblies are used over a configuration then it is a trade where the configuration is done (file-system vs. configuration entry, for instance). There are some things that need to be considered such as strong-names and explicit versions.

I can not justify just swapping the assembly and some advantages for requiring the configuration entry (instead of swapping) are:

Other parameters such as credentials or options can also be easily stored/passed in to the factory/activator.

It's just as trivial to keep the assembly names different which is less confusing: which DAL is thedall.dll? (If the version, etc, are the same, the only thing to go on is some check-sum or de-compilation or 'info' method. Not very fun.)

Can have multiple back-ends installed at once which can simplify distribution packages and testing, etc.

Do not need to control the build steps as much. Do not need to to "hijack" GUIDs or all claim to be the same version.

One tool I have used in the past is iBATIS and there is iBATIS.NET. It is not in the same "ORM class" as Hibernate or Active Record, etc, as it is a simple mapper between defined SQL statements and objects. Very primitive, yes. Requires lots of SQL, yes. But some people swear by it.

Happy coding.


问:
Spring boot @Scheduler not working on tomcat
I have a @Scheduled method which runs without a problem when I build my Spring Boot application using embedded tomcat. But when i build my project in .war and deploy it using tomcat v8, it seem like scheduler not trigger. Other functions working great just this scheduler not trigger on my server.</p>

```<code>@Component
public class DeleteUser {

@Autowired
private UserService userService;

@Autowired
private UserAuthoritiesService userAuthService;

private static final Logger logger = LoggerFactory.getLogger(DeleteUser.class);

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

//(cron="second, minute, hour, day of month, month, day(s) of week")
@Scheduled(cron="0 0 8 * * *", zone="Asia/Kuala_Lumpur")
public void schedulerDeleteUser() {

    List<User> ls = userService.getAllInactiveUser3Day(new Date());

    try {
        if(ls.size()>0) {

            for(User user: ls) {
                userService.updateStatusAccount(false, user.getId());
            }
        }
    }
    catch(Exception e) {
        logger.error(e.getMessage());
    }
    logger.info("Scheduler run at {}", dateFormat.format(new Date()));
  }
}
</code>```

答:
I had the same problem: everything working fine on built-in tomcat server but not
when I've deployed .war file into production. I've tried a few things to solve it (don't remember exactly which particular one worked) and eventually I've ended up with the following:

I have dedicated scheduler configuration class:

```<code>@Configuration
@EnableScheduling
@EnableAsync
public class SchedulerConfiguration implements SchedulingConfigurer {

    private final int POOL_SIZE = 2;
    private final String THREAD_NAME_PREFIX = "task-scheduler-";

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix(THREAD_NAME_PREFIX);
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}
</code>```

I guess, what's most important above are @EnableScheduling and @EnableAsync annotations (I didn't had the 2nd one before)

Last but not least, I have noticed that my main application class wasn't extending SpringBootServletInitializer so I have fixed that too:

```<code>public class SpringBootApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(MarketplaceMonitorApplication.class, args);
    }
}
</code>```

Without it, application started but @Scheduling wasn't working.. or I fixed that earlier and forget :-) Anyway, please make sure you have it! ;-)

Now everything works on the production as expected.

Body:
I have a @Scheduled method which runs without a problem when I build my Spring Boot application using embedded tomcat. But when i build my project in .war and deploy it using tomcat v8, it seem like scheduler not trigger. Other functions working great just this scheduler not trigger on my server.

@Component
public class DeleteUser {

@Autowired
private UserService userService;

@Autowired
private UserAuthoritiesService userAuthService;

private static final Logger logger = LoggerFactory.getLogger(DeleteUser.class);

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

//(cron="second, minute, hour, day of month, month, day(s) of week")
@Scheduled(cron="0 0 8 * * *", zone="Asia/Kuala_Lumpur")
public void schedulerDeleteUser() {

    List<User> ls = userService.getAllInactiveUser3Day(new Date());

    try {
        if(ls.size()>0) {

            for(User user: ls) {
                userService.updateStatusAccount(false, user.getId());
            }
        }
    }
    catch(Exception e) {
        logger.error(e.getMessage());
    }
    logger.info("Scheduler run at {}", dateFormat.format(new Date()));
  }
}

Body:
I had the same problem: everything working fine on built-in tomcat server but not
when I've deployed .war file into production. I've tried a few things to solve it (don't remember exactly which particular one worked) and eventually I've ended up with the following:

I have dedicated scheduler configuration class:

@Configuration
@EnableScheduling
@EnableAsync
public class SchedulerConfiguration implements SchedulingConfigurer {

    private final int POOL_SIZE = 2;
    private final String THREAD_NAME_PREFIX = "task-scheduler-";

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix(THREAD_NAME_PREFIX);
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}

I guess, what's most important above are @EnableScheduling and @EnableAsync annotations (I didn't had the 2nd one before)

Last but not least, I have noticed that my main application class wasn't extending SpringBootServletInitializer so I have fixed that too:

public class SpringBootApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(MarketplaceMonitorApplication.class, args);
    }
}

Without it, application started but @Scheduling wasn't working.. or I fixed that earlier and forget :-) Anyway, please make sure you have it! ;-)

Now everything works on the production as expected.


问:
PHP GearmanClient::doBackground just hangs
Mehod doBackground of GearmanClient and its descendants such as doLowBackground and doHighBackground sometimes hang. I cannot figure out why.

php 5.4

Gearman server version 1.1.18

Gearman php lib version 1.1.2

At some point of time user clicks the button, and tasks (more than 700) go to the gearman. DoBackground freezes randomly, it can hang after 20 task put into gearman, or can hang after 200-300, maybe 500 tasks.

I don't see errors in gearman/php logs nor see in direct link (when I directly start debugging)

When I try to debug, I just minimize tasks count to 50, and issue request directly from browser. If everything goes well, browser's circle (loading action) dissapears, and I see my var_dumps. But if at some task doBackground didnt return control, browser request goes to infinite loop, waiting server response

My code is simple. I collect data, put into array, and one by one send to queue

```<code>for($i = 0; $i < count($itemsToProcess); $i++) {var_dump($i);
    $method = array_shift($itemsToProcess[$i]['methodsAfter']);
    Yii::app()->gearman->client()->doBackground($method, json_encode($itemsToProcess[$i]));
}
</code>```

As additional information, I have another server with

php 7.1

installed,

server version is 1.1.12

, and

libgearman for php was auto installed with yum

. There seems to be same problem, but!!! it appears very very rarely.

Of course it's crucial and very critical problem, if you issue A count and B count goes into queue.

P.S: The reason of different enviroments is that we cannot still migrate to php7. Php5.4 is prod and php7 is dev

答:
It's not gearmand, nor php extension problem

https://github.com/gearman/gearmand/issues/241

Body:
Mehod doBackground of GearmanClient and its descendants such as doLowBackground and doHighBackground sometimes hang. I cannot figure out why.

php 5.4

Gearman server version 1.1.18

Gearman php lib version 1.1.2

At some point of time user clicks the button, and tasks (more than 700) go to the gearman. DoBackground freezes randomly, it can hang after 20 task put into gearman, or can hang after 200-300, maybe 500 tasks.

I don't see errors in gearman/php logs nor see in direct link (when I directly start debugging)

When I try to debug, I just minimize tasks count to 50, and issue request directly from browser. If everything goes well, browser's circle (loading action) dissapears, and I see my var_dumps. But if at some task doBackground didnt return control, browser request goes to infinite loop, waiting server response

My code is simple. I collect data, put into array, and one by one send to queue

for($i = 0; $i < count($itemsToProcess); $i++) {var_dump($i);
    $method = array_shift($itemsToProcess[$i]['methodsAfter']);
    Yii::app()->gearman->client()->doBackground($method, json_encode($itemsToProcess[$i]));
}

As additional information, I have another server with

php 7.1

installed,

server version is 1.1.12

, and

libgearman for php was auto installed with yum

. There seems to be same problem, but!!! it appears very very rarely.

Of course it's crucial and very critical problem, if you issue A count and B count goes into queue.

P.S: The reason of different enviroments is that we cannot still migrate to php7. Php5.4 is prod and php7 is dev


问:
Regex pattern needs to match only the first occurrence and not be "greedy"
I'm stumped on one pattern that keeps returning all matches beyond the first (it's "greedy")
my pattern: ISS/(?\w\S*)
Where the text has two matches:

ISS/2018-03-02

ISS/2005-03-09

I only want the C# regex to return the first match "2018-03-02"

```<code>    private static readonly Regex tagIssueDateRegex = new Regex(
        @"ISS\/(?<issue>\w+\S*)",
        RegexOptions.Singleline);
</code>```

答:
Use this pattern:

```<code>^ISS\/(?<issue>\w+\S*)
</code>```

If there can be text before the first "ISS", use this one:

```<code>^.*?ISS\/(?<issue>\w+\S*)
</code>```

^ means "beginning of the line", .*? means "any character, from 0 to n times, as few as possible.

Body:
I'm stumped on one pattern that keeps returning all matches beyond the first (it's "greedy")
my pattern: ISS/(?\w\S*)
Where the text has two matches:

ISS/2018-03-02

ISS/2005-03-09

I only want the C# regex to return the first match "2018-03-02"

    private static readonly Regex tagIssueDateRegex = new Regex(
        @"ISS\/(?<issue>\w+\S*)",
        RegexOptions.Singleline);

Body:
Use this pattern:

^ISS\/(?<issue>\w+\S*)

If there can be text before the first "ISS", use this one:

^.*?ISS\/(?<issue>\w+\S*)

^ means "beginning of the line", .*? means "any character, from 0 to n times, as few as possible.


问:
ASP.NET Core MVC tag helper for collections data binding
I'm using a model that contains a List of "Country" and i'm using...

```<code>            <input asp-for="Countries" type="hidden" />
</code>```

... to do my data binding but when it renders it populates the value attribute with the toString() of the list. so its just...

```<code><input type="hidden" id="Countries" name="Countries" value="System.Collections.Generic.List`1[Models.Country]">
</code>```

is there a proper way of doing data binding for a model that contains a collections using tag helpers in in asp.net core?

答:
You could use the following technique:

```<code>@{
    for (int i=0; i<Model.Countries.Count(); i++) {
        <input asp-for="Model.Countries[i].Name" type="text"/>
    }
}
</code>```

That should do the trick.

Body:
I'm using a model that contains a List of "Country" and i'm using...

            <input asp-for="Countries" type="hidden" />

... to do my data binding but when it renders it populates the value attribute with the toString() of the list. so its just...

<input type="hidden" id="Countries" name="Countries" value="System.Collections.Generic.List`1[Models.Country]">

is there a proper way of doing data binding for a model that contains a collections using tag helpers in in asp.net core?

Body:
You could use the following technique:

@{
    for (int i=0; i<Model.Countries.Count(); i++) {
        <input asp-for="Model.Countries[i].Name" type="text"/>
    }
}

That should do the trick.


答:
Non-Greedy

For non-greedy, we would just add a s flag:

```<code>ISS\/(\d{4}-\d{2}-\d{2})
</code>```

DEMO for non-greedy

Test

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})";
        string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
        RegexOptions options = RegexOptions.Singleline;

        Match m = Regex.Match(input, pattern, options);
        Console.WriteLine("'{0}' found at index {1}", m.Value, m.Index);
    }
}
</code>```

Greedy

I'm guessing that we wish to only return the first instance of ISS followed by a date, for which, we would start with an expression:

```<code>ISS\/(\d{4}-\d{2}-\d{2})
</code>```

then we would add one of these expressions:

```<code>[\s\S]*
[\w\W]*
[\d\D]*
[\s\S].*
[\w\W].*
[\d\D].*
</code>```

to swipe all chars and new lines to the end of our string, and we would have:

```<code>ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*
</code>```

if I understand the question correctly.

We can add or reduce our boundaries, if necessary.

Test

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*";
        string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

DEMO for greedy

RegEx Circuit

jex.im visualizes regular expressions:

Title: Regex pattern needs to match only the first occurrence and not be "greedy"

Body:
Non-Greedy

For non-greedy, we would just add a s flag:

ISS\/(\d{4}-\d{2}-\d{2})

DEMO for non-greedy

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})";
        string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
        RegexOptions options = RegexOptions.Singleline;

        Match m = Regex.Match(input, pattern, options);
        Console.WriteLine("'{0}' found at index {1}", m.Value, m.Index);
    }
}

Greedy

I'm guessing that we wish to only return the first instance of ISS followed by a date, for which, we would start with an expression:

ISS\/(\d{4}-\d{2}-\d{2})

then we would add one of these expressions:

[\s\S]*
[\w\W]*
[\d\D]*
[\s\S].*
[\w\W].*
[\d\D].*

to swipe all chars and new lines to the end of our string, and we would have:

ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*

if I understand the question correctly.

We can add or reduce our boundaries, if necessary.

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*";
        string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

DEMO for greedy

RegEx Circuit

jex.im visualizes regular expressions:


问:
Suggestions for matching spoken and written digits with Machine Learning
I’m working on a machine learning problem which is proving very difficult. I want to learn to recognize whether an image of a hand written digit and a recording of a spoken digit refer to the same or different number. False: the image and the recording refer to different numbers and True: the image and the recording refer to the same number.

The Data:

Each image is given as 784-dimensional vector, which represents 28x28 pixel grayscale image. The pixel intensities range from 0 (black) to 255 (white).
Each sound recording of a spoken name of a digit (e.g. “zero”, “one’ etc, pronounced in Arabic) is given as an array of pre-extracted audio features, so called Mel-Frequency Cepstral Coefficients (MFCC). These features encode the charachteristics of a 10 milisecond frame of speech. Each recording is of variable length, and thus each example is given as an array of shape (N, 13), where N is the number of frames in the recording, and 13 the number of MFCC features.

For this problem I got 5 datasets:

Written_train.npy: array with 45,000 rows and 784 columns

Written_test.npy: array with 15,000 rows and 784 columns

Spoken_train.npy: array with 45,000 rows. Each row Is an object of shape (N, 13)

Spoken_test.npy: array with 15,000 rows. Each row is an object of shape (N, 13)

Match_train.nyp: array with 45,000 boolean values (False or True)

Notice that there aren't any labels for the written and spoken digits.

In sum: I want to create an array of 15000 boolean values, specifying whether the images and sounds from the test data matched or not.

Current Approaches:

One approach I have tried implementing was clustering both spoken and written data, and then training a classifier to see what clusters match. However, I do not have a way of checking if the clustering is accurate in the audio data.

Another approach I'm trying is combining both data sets to feed into a MLP. Here however, I am not sure how to approach combining the data.

Finally, I also found an article describing a network that combines mixed data: https://www.pyimagesearch.com/2019/02/04/keras-multiple-inputs-and-mixed-data/

Do you recommend proceeding with one of the approaches mentioned above? Or is there a different/simpler method I am missing.

Thank you in advance!

答:
One solution for this will be two run two models. One to recognize the image and this model could be convolutional neural network. You will be able to find several CNN examples for number recognition.

The second part of your solution will be to use RNN or any simple word recognition library to classify the spoken number. You will find enough examples for this too.

the last task will be to compare the prediction from both the model and see if they match. To do this, store predictions into list for models and then use whatever evaluation metric you want to use on that.


问:
How can I create a stacked bar chart from this table
I am new to PowerBI so please bear with me.

I have this table:

```<code>RespondentID         Question 1                Question 2                    Question 3
 1          Neither Agree or Disagree            Agree                         Agree
 2                    Disagree                   Agree                         Agree
 3          Neither Agree or Disagree    Neither Agree or Disagree       Neither Agree or Disagree
 4                    Agree                      Disagree                Neither Agree or Disagree
</code>```

and I want to view it as a stacked bar chart, showing the question number to the left and for each question, a bar coloured depending on the count of values (disagree, agree, neither)

Thanks,

答:
Your table isn't in a good model for the kind of visualization you're trying to create.  It must be 'unpivoted.'

So, highlight your table by right clicking it and choose 'Edit Query.'  When the Power Query Editor window loads, you should see your table in the editing area.  Right click the ID column and select 'Unpivot other columns.'  Rename 'Attribute' to 'Question' and 'Value' to 'Answer'

Close and apply.

Now you can create your stacked bar.  Drag 'Answer' to the value dwell, it will automatically become 'count of answer.'  Drag 'Answer' again to Legend.  You'll get your stacked column effect.  And then add 'Question' to Axis.

Good luck, hope it helps.

Body:
I am new to PowerBI so please bear with me.

I have this table:

RespondentID         Question 1                Question 2                    Question 3
 1          Neither Agree or Disagree            Agree                         Agree
 2                    Disagree                   Agree                         Agree
 3          Neither Agree or Disagree    Neither Agree or Disagree       Neither Agree or Disagree
 4                    Agree                      Disagree                Neither Agree or Disagree

and I want to view it as a stacked bar chart, showing the question number to the left and for each question, a bar coloured depending on the count of values (disagree, agree, neither)

Thanks,


问:
Packaging JSF web app with Quarkus with JVM mode
Quarkus JVM mode with JSF

I have an existing thorntail 2.4 based web application built using JSF and JEE (CDI/EJB).

For my technology stack above, if I am only using the JVM mode and not the native mode, is it possible to package my application using runtime?

I understand that EJB spec is not implemented with quarkus and I am OK with rewriting EJBs as CDI+JTA services but want to know if it's possible to use JSF with quarkus.

答:
There is an extension for it available: https://github.com/tandraschko/quarkus-myfaces

UPDATE: I moved my 'personal' extension to MyFaces Core and we already have an 2.3-next-M1 release ready.
The showcase is available here and already uses the released version: https://github.com/apache/myfaces/tree/master/extensions/quarkus/showcase

UPDATE: We even released M2 today which supports native images!


问:
How to update data to mysql although some textboxes are blank? (The data of blank textboxes will be kept)
I want to update the data through textboxes and if some of the textboxes are blank, then the data, which supposed to be updated by those textboxes, would be kept.</p>

答:
If this is a user facing application and the text boxes have existing data associated, a much better UI would involve actually loading that data out and displaying it to the user so they know all the information that will be contained in the record.

Then you can not update fields that match if that is important for some reason.

If for some reason this is impossible, individual update statements guarded by if is not blank checks could get the job done, or case statements in a single update statement involving the database value if the update value is blank, but this all seems like a hack to me.


问:
Docker alias incorrectly resolved by application when container started
I am creating two docker-compose files (mainly because I don't want to have to keep restarting my infrastructure while developing my application.) that need to reside on the same docker network so they can use alias names to connect.

The files look similar to the following:

APP:

```<code>version: '3.5'

networks:
  default:
    name: kafka_network
    driver: bridge
services:
  client:
    build:
      context: .
      dockerfile: ./Dockerfile
    working_dir: /app/
    command: ./client
    environment:
      BADDR: kafka:9092
      CGROUP: test_group
      TOPICS: my-topic
</code>```

INFRASTRUCTURE:

```<code>version: '3.5'

networks:
  default:
    name: kafka_network
    driver: bridge

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    ports:
      - 2181:2181
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 9092:9092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
</code>```

My issue is that the client doesn't resolve kafka:9092 correctly... it always resolves to 127.0.0.1:9092.

ERROR:

```<code>Broker:  kafka:9092
Consumer_Group:  my_group
Topics:  [my-topic]
Created Consumer rdkafka#consumer-1
% Error: GroupCoordinator: Connect to ipv4#127.0.0.1:9092 failed: Connection refused (after 0ms in state CONNECT)
</code>```

When run locally, it appears to run fine, so I am really confused as to what the issue might be.  If anyone knows anything about this I would be very grateful!

LOCAL:

```<code>[procyclinsur@P-428 client]$ ./client
Broker:  localhost:9092
Consumer_Group:  my-group
Topics:  [my-topic]
Created Consumer rdkafka#consumer-1
% AssignedPartitions: [my-topic[0]@unset]
% Message on my-topic[0]@0:
hello mate
</code>```

答:
That's problem related to your Kafka's config - not to docker at all.

Look on:

```<code>  KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
</code>```

It means that you setup 2 listeners for your Kafka which your clients will receive in Kafka's protocol when connecting.

So when you connect on port 9092 your client's will try to get Kafka at "localhost "and when you connect at port 29092 your clients will try to get Kafka at "kafka" DNS name.

It's working locally for you because your Kafka container is exposed on localhost:9092 via docker ports section.

Here is article which is well describing that topic: https://rmoff.net/2018/08/02/kafka-listeners-explained/

Body:
I am creating two docker-compose files (mainly because I don't want to have to keep restarting my infrastructure while developing my application.) that need to reside on the same docker network so they can use alias names to connect.

The files look similar to the following:

APP:

version: '3.5'

networks:
  default:
    name: kafka_network
    driver: bridge
services:
  client:
    build:
      context: .
      dockerfile: ./Dockerfile
    working_dir: /app/
    command: ./client
    environment:
      BADDR: kafka:9092
      CGROUP: test_group
      TOPICS: my-topic

INFRASTRUCTURE:

version: '3.5'

networks:
  default:
    name: kafka_network
    driver: bridge

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    ports:
      - 2181:2181
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 9092:9092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

My issue is that the client doesn't resolve kafka:9092 correctly... it always resolves to 127.0.0.1:9092.

ERROR:

Broker:  kafka:9092
Consumer_Group:  my_group
Topics:  [my-topic]
Created Consumer rdkafka#consumer-1
% Error: GroupCoordinator: Connect to ipv4#127.0.0.1:9092 failed: Connection refused (after 0ms in state CONNECT)

When run locally, it appears to run fine, so I am really confused as to what the issue might be.  If anyone knows anything about this I would be very grateful!

LOCAL:

[procyclinsur@P-428 client]$ ./client
Broker:  localhost:9092
Consumer_Group:  my-group
Topics:  [my-topic]
Created Consumer rdkafka#consumer-1
% AssignedPartitions: [my-topic[0]@unset]
% Message on my-topic[0]@0:
hello mate

Body:
That's problem related to your Kafka's config - not to docker at all.

Look on:

  KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092

It means that you setup 2 listeners for your Kafka which your clients will receive in Kafka's protocol when connecting.

So when you connect on port 9092 your client's will try to get Kafka at "localhost "and when you connect at port 29092 your clients will try to get Kafka at "kafka" DNS name.

It's working locally for you because your Kafka container is exposed on localhost:9092 via docker ports section.

Here is article which is well describing that topic: https://rmoff.net/2018/08/02/kafka-listeners-explained/


问:
UICollectionViewCell Shake
I have created a UICollectionView and would like to have all the cells shake like the edit mode of the springboard on the iPhone. I have created my shake code but don't know how to implement it. I have custom cells so I assume it goes in there but don't know how it gets implemented. Thank You.</p>

```<code>#define degreesToRadians(x) (M_PI * (x) / 180.0)
#define kAnimationRotateDeg 0.5
#define kAnimationTranslateX 1.0
#define kAnimationTranslateY 1.0

//startJiggling

int count = 1;
CGAffineTransform leftWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? +1 : -1 ) ));
CGAffineTransform rightWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? -1 : +1 ) ));
CGAffineTransform moveTransform = CGAffineTransformTranslate(rightWobble, -kAnimationTranslateX, -kAnimationTranslateY);
CGAffineTransform conCatTransform = CGAffineTransformConcat(rightWobble, moveTransform);

    self.transform = leftWobble;  // starting point

    [UIView animateWithDuration:0.1
                          delay:(count * 0.08)
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
                     animations:^{ self.transform = conCatTransform; }
                     completion:nil];
</code>```

答:
Swift 5 Easy like this

Enter this 2 functions to your UICollectionViewCell and call it when ever you want to animate/stop, ex: cell render

```<code>func shake() {
    let shakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shakeAnimation.duration = 0.05
    shakeAnimation.repeatCount = 2
    shakeAnimation.autoreverses = true
    let startAngle: Float = (-2) * 3.14159/180
    let stopAngle = -startAngle
    shakeAnimation.fromValue = NSNumber(value: startAngle as Float)
    shakeAnimation.toValue = NSNumber(value: 3 * stopAngle as Float)
    shakeAnimation.autoreverses = true
    shakeAnimation.duration = 0.15
    shakeAnimation.repeatCount = 10000
    shakeAnimation.timeOffset = 290 * drand48()

    let layer: CALayer = self.layer
    layer.add(shakeAnimation, forKey:"shaking")
}

func stopShaking() {
    let layer: CALayer = self.layer
    layer.removeAnimation(forKey: "shaking")
}
</code>```

Help Source from Git

Title: UICollectionViewCell Shake

Body:
I have created a UICollectionView and would like to have all the cells shake like the edit mode of the springboard on the iPhone. I have created my shake code but don't know how to implement it. I have custom cells so I assume it goes in there but don't know how it gets implemented. Thank You.

#define degreesToRadians(x) (M_PI * (x) / 180.0)
#define kAnimationRotateDeg 0.5
#define kAnimationTranslateX 1.0
#define kAnimationTranslateY 1.0

//startJiggling

int count = 1;
CGAffineTransform leftWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? +1 : -1 ) ));
CGAffineTransform rightWobble = CGAffineTransformMakeRotation(degreesToRadians( kAnimationRotateDeg * (count%2 ? -1 : +1 ) ));
CGAffineTransform moveTransform = CGAffineTransformTranslate(rightWobble, -kAnimationTranslateX, -kAnimationTranslateY);
CGAffineTransform conCatTransform = CGAffineTransformConcat(rightWobble, moveTransform);

    self.transform = leftWobble;  // starting point

    [UIView animateWithDuration:0.1
                          delay:(count * 0.08)
                        options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
                     animations:^{ self.transform = conCatTransform; }
                     completion:nil];

Body:
Swift 5 Easy like this

Enter this 2 functions to your UICollectionViewCell and call it when ever you want to animate/stop, ex: cell render

func shake() {
    let shakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shakeAnimation.duration = 0.05
    shakeAnimation.repeatCount = 2
    shakeAnimation.autoreverses = true
    let startAngle: Float = (-2) * 3.14159/180
    let stopAngle = -startAngle
    shakeAnimation.fromValue = NSNumber(value: startAngle as Float)
    shakeAnimation.toValue = NSNumber(value: 3 * stopAngle as Float)
    shakeAnimation.autoreverses = true
    shakeAnimation.duration = 0.15
    shakeAnimation.repeatCount = 10000
    shakeAnimation.timeOffset = 290 * drand48()

    let layer: CALayer = self.layer
    layer.add(shakeAnimation, forKey:"shaking")
}

func stopShaking() {
    let layer: CALayer = self.layer
    layer.removeAnimation(forKey: "shaking")
}

Help Source from Git