问:
Where and how to create a stored procedure in Laravel 5
I am using laravel 5.1 for my project and till now it us going perfect until I wanted to use stored procedure in it.

so far I have gathered the information as

```<code> $result = DB::select('call InsertNewApplicant(?????????????????????????)',
                    array($firstName, $middleName, $addressLine_1, $addressLine_2, $postCode, $landline, $mobile, $email,
                    $DOB, $maritalStatus, $industry, $occupation, $jobTitle, $selfEmployed, $selfAssessment, $workHome,
                    $ownTransport, $companyVehicle, $paySubs, $otherIncome, $printForms, $marketingUs, $marketingOther,
                    $agreedTNCs, $TNCVersion, $CampaignSource));
</code>```

might be using this code for the controller to update any data from mysql,
but as a beginner in Laravel, I have no idea where to define my stored procedure and in which file

I have visited many links , but all I could get is this code, not a single perfect example.

Can you please elaborate a small example on how to call a stored procedure in controller for a specific action?

and what all are prerequisite and other things that has to be taken care of

答: Yes. Put it into a controller, and keep it this way until you would like to change something. Than you can abstract it out to dedicated class that may be mocked. </p>

Body:
I am using laravel 5.1 for my project and till now it us going perfect until I wanted to use stored procedure in it.

so far I have gathered the information as

 $result = DB::select('call InsertNewApplicant(?????????????????????????)',
                    array($firstName, $middleName, $addressLine_1, $addressLine_2, $postCode, $landline, $mobile, $email,
                    $DOB, $maritalStatus, $industry, $occupation, $jobTitle, $selfEmployed, $selfAssessment, $workHome,
                    $ownTransport, $companyVehicle, $paySubs, $otherIncome, $printForms, $marketingUs, $marketingOther,
                    $agreedTNCs, $TNCVersion, $CampaignSource));

might be using this code for the controller to update any data from mysql,
but as a beginner in Laravel, I have no idea where to define my stored procedure and in which file

I have visited many links , but all I could get is this code, not a single perfect example.

Can you please elaborate a small example on how to call a stored procedure in controller for a specific action?

and what all are prerequisite and other things that has to be taken care of


来源: stackexchange

问:
GenerationType.AUTO vs GenerationType.IDENTITY in hibernate
Currently, we are using MySQL as a database and we use

@Generated Value(strategy = GenerationType.IDENTITY)

It's working perfectly in certain situations we need to migrate our database to Oracle at that time it's not working properly. If anyone knows what's the actual difference is present behind this and how it's working?

答:
Quoting Java Persistence/Identity and Sequencing:

Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.

so I prefer to use SEQUENCE instead

Sequence objects use special database objects to generate ids. Sequence objects are only supported in some databases, such as Oracle, DB2, and Postgres. Usually, a SEQUENCE object has a name, an INCREMENT, and other database object settings. Each time the .NEXTVAL is selected the sequence is incremented by the INCREMENT.

Example :

```<code>@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="EMP_SEQ")
    @SequenceGenerator(name="EMP_SEQ", sequenceName="EMP_SEQ", allocationSize=100)
    private long id;
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Quoting Java Persistence/Identity and Sequencing:

Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.

so I prefer to use SEQUENCE instead

Sequence objects use special database objects to generate ids. Sequence objects are only supported in some databases, such as Oracle, DB2, and Postgres. Usually, a SEQUENCE object has a name, an INCREMENT, and other database object settings. Each time the .NEXTVAL is selected the sequence is incremented by the INCREMENT.

Example :

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="EMP_SEQ")
    @SequenceGenerator(name="EMP_SEQ", sequenceName="EMP_SEQ", allocationSize=100)
    private long id;
    ...
}

ContentLicense: CC BY-SA 3.0


问:
How to retrieve data in a trigger from the header table that was already deleted
I have a situation where I have a Header and a Detail table. The Detail table has a foreign key relationship to the Header table with Cascade delete.

When the detail records are deleted I need to update other tables using a trigger. The problem I am having is that I need to pull some information from the Header table as well as the Detail table for the deleted records. If I delete the Detail records and then the Header record the trigger appears to run fine. However, if I delete the Header record, which in turn deletes the Detail records due to the cascading delete, then when the trigger executes the Header record is already deleted and I can't access the information I need from it.

I am rather new to triggers, so I'm wondering if there is something I just don't know and how I accomplish this.

Here is my code:

```<code>ALTER TRIGGER [Detail_Delete]
   ON [Detail]
   AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- Here is where the problem lies.
 -- No records are found here because the Header record isn't found.
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, h.UserID
 FROM deleted d
 JOIN Header h ON h.HeaderID = d.HeaderID

 EXECUTE sp_UpdateSummary
  @Table = @Table
END
</code>```

答:
I wouldn't use a cascade delete because as you've seen, the deleted parent data isn't available

A stored procedure is ideal for this. If not for whatever reason, you can use a BEFORE trigger on the Header table to do the Detail and other deletes (and of course the Header table)

```<code>ALTER TRIGGER [Header_Delete]
   ON [Header]
   INSTEAD OF DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- DELETED has data, even though Header has not yet been touched
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, d.UserID
 FROM deleted

 DELETE Detail WHERE ... (using @Table)

 DELETE Other WHERE ... (using @Table)

 DELETE Header WHERE ... (using @Table)

 EXECUTE sp_UpdateSummary
  @Table = @Table ...
END
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a situation where I have a Header and a Detail table. The Detail table has a foreign key relationship to the Header table with Cascade delete.

When the detail records are deleted I need to update other tables using a trigger. The problem I am having is that I need to pull some information from the Header table as well as the Detail table for the deleted records. If I delete the Detail records and then the Header record the trigger appears to run fine. However, if I delete the Header record, which in turn deletes the Detail records due to the cascading delete, then when the trigger executes the Header record is already deleted and I can't access the information I need from it.

I am rather new to triggers, so I'm wondering if there is something I just don't know and how I accomplish this.

Here is my code:

ALTER TRIGGER [Detail_Delete]
   ON [Detail]
   AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- Here is where the problem lies.
 -- No records are found here because the Header record isn't found.
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, h.UserID
 FROM deleted d
 JOIN Header h ON h.HeaderID = d.HeaderID

 EXECUTE sp_UpdateSummary
  @Table = @Table
END

Body:
I wouldn't use a cascade delete because as you've seen, the deleted parent data isn't available

A stored procedure is ideal for this. If not for whatever reason, you can use a BEFORE trigger on the Header table to do the Detail and other deletes (and of course the Header table)

ALTER TRIGGER [Header_Delete]
   ON [Header]
   INSTEAD OF DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- DELETED has data, even though Header has not yet been touched
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, d.UserID
 FROM deleted

 DELETE Detail WHERE ... (using @Table)

 DELETE Other WHERE ... (using @Table)

 DELETE Header WHERE ... (using @Table)

 EXECUTE sp_UpdateSummary
  @Table = @Table ...
END


问:
Accumulator within a DO loop
My goal is to create 10,000 randomly generated numbers between 0 and 1, organize them into ten bins evenly spaced between 0 and 1, and compute a frequency for each bin. This is my code so far.

```<code>program listrand
implicit none
integer :: n,p
integer :: a,b,c,d,e,f,g,h,i,j = 0
real :: xran
!real, dimension(10,2) :: bin_and_freq -- list of bins and frequency

do n = 1,10000
    call random_number(xran)
            if (xran <  0.1) then
                a = a + 1
            elseif (xran>0.1 .and. xran<0.2) then
                b = b + 1
            elseif (xran>0.2 .and. xran<0.3) then
                c = c+1
            elseif (xran>0.3 .and. xran<0.4) then
                d = d+1
            elseif (xran>0.4 .and. xran<0.5) then
                e = e + 1
            elseif (xran>0.5 .and. xran<0.6) then
                f = f+1
            elseif (xran>0.6 .and. xran<0.7) then
                g = g+1
            elseif (xran>0.7 .and. xran<0.8) then
                h=h+1
            elseif (xran>0.8 .and. xran<0.9) then
                i=i+1
            else
                j = j+1
            endif
enddo
print *, a,b,c,d,e,f,g,h,i,j
end program listrand
</code>```

I am getting an unexpected output:
    988        1036   133225987        1004         934         986        1040       33770  1406729616        1052.

Why are c,h, and i so large? Also, is there a more efficient way of going about this than using the unwieldy IF/ELSEIF block I have?

答:
In your long

```<code>integer :: a,b,c,d,e,f,g,h,i,j = 0
</code>```

You are only initialising j to be 0, all others have random numbers in them. If you add

```<code>a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
i = 0
j = 0
</code>```

before your loop, everything works well.

As for how to simplify it:

Here is my version of the program:

```<code>program listrand
implicit none
integer, parameter :: nbins = 10
integer :: n, bin
integer :: bin_hits(nbins)   ! Number of bin hits
real :: xran
real :: bin_lower(nbins)     ! Lower edge of bins
                             ! bin_lower(1) == 0.0

bin_hits = 0

! Set up equidistant bins
bin_lower = [ (real(n-1) / nbins, n = 1, size(bin_lower)) ]

do n = 1,10000
    call random_number(xran)
    bin = count(bin_lower <= xran)
    bin_hits(bin) = bin_hits(bin)+1
enddo
do n = 1, nbins-1
    print '(2(F6.2), I6)' bin_lower(n), bin_lower(n+1), bin_hits(n)
end do
print '(2(F6.2), I6)' bin_lower(nbins), 1.0, bin_hits(nbins)
end program listrand
</code>```

For the index of which bin_hits element to increment, I'm counting the number of values in bin_lower that are actually lower than xran.

EDIT

I'd like to also point to the answer from High Performance Mark a bit further down, who instead of calling RANDOM_NUMBER for each value  individually uses it to generate a whole array of random numbers.

Additionally, he's using the fact that the bins are fixed and equidistant to calculate the bin number directly from the random value instead of comparing it to each bin as in my version.

Both of these make the program faster.

Title: Accumulator within a DO loop

Body:
My goal is to create 10,000 randomly generated numbers between 0 and 1, organize them into ten bins evenly spaced between 0 and 1, and compute a frequency for each bin. This is my code so far.

program listrand
implicit none
integer :: n,p
integer :: a,b,c,d,e,f,g,h,i,j = 0
real :: xran
!real, dimension(10,2) :: bin_and_freq -- list of bins and frequency

do n = 1,10000
    call random_number(xran)
            if (xran <  0.1) then
                a = a + 1
            elseif (xran>0.1 .and. xran<0.2) then
                b = b + 1
            elseif (xran>0.2 .and. xran<0.3) then
                c = c+1
            elseif (xran>0.3 .and. xran<0.4) then
                d = d+1
            elseif (xran>0.4 .and. xran<0.5) then
                e = e + 1
            elseif (xran>0.5 .and. xran<0.6) then
                f = f+1
            elseif (xran>0.6 .and. xran<0.7) then
                g = g+1
            elseif (xran>0.7 .and. xran<0.8) then
                h=h+1
            elseif (xran>0.8 .and. xran<0.9) then
                i=i+1
            else
                j = j+1
            endif
enddo
print *, a,b,c,d,e,f,g,h,i,j
end program listrand

I am getting an unexpected output:
    988        1036   133225987        1004         934         986        1040       33770  1406729616        1052.

Why are c,h, and i so large? Also, is there a more efficient way of going about this than using the unwieldy IF/ELSEIF block I have?

Body:
In your long

integer :: a,b,c,d,e,f,g,h,i,j = 0

You are only initialising j to be 0, all others have random numbers in them. If you add

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
i = 0
j = 0

before your loop, everything works well.

As for how to simplify it:

Here is my version of the program:

program listrand
implicit none
integer, parameter :: nbins = 10
integer :: n, bin
integer :: bin_hits(nbins)   ! Number of bin hits
real :: xran
real :: bin_lower(nbins)     ! Lower edge of bins
                             ! bin_lower(1) == 0.0

bin_hits = 0

! Set up equidistant bins
bin_lower = [ (real(n-1) / nbins, n = 1, size(bin_lower)) ]

do n = 1,10000
    call random_number(xran)
    bin = count(bin_lower <= xran)
    bin_hits(bin) = bin_hits(bin)+1
enddo
do n = 1, nbins-1
    print '(2(F6.2), I6)' bin_lower(n), bin_lower(n+1), bin_hits(n)
end do
print '(2(F6.2), I6)' bin_lower(nbins), 1.0, bin_hits(nbins)
end program listrand

For the index of which bin_hits element to increment, I'm counting the number of values in bin_lower that are actually lower than xran.

EDIT

I'd like to also point to the answer from High Performance Mark a bit further down, who instead of calling RANDOM_NUMBER for each value  individually uses it to generate a whole array of random numbers.

Additionally, he's using the fact that the bins are fixed and equidistant to calculate the bin number directly from the random value instead of comparing it to each bin as in my version.

Both of these make the program faster.


问:
How to check the Azure Service Bus queue is empty?
I'm using azure service bus queues in my application and here my question is, is there a way how to check the message queue is empty so that I can shutdown my containers and vms to save cost. If there is way to get that please let me know, preferably in python.

Thanks

答:
For this, you can use Azure Service Bus Python SDK. What you would need to do is get the properties of a queue using get_queue method that will return an object of type Queue. This object exposes the total number of messages through message_count property. Please note that this count will include count for active messages, dead-letter queue messages and more.

Here's a sample code to do so:

```<code>from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
    service_namespace='namespacename',
    shared_access_key_name='RootManageSharedAccessKey',
    shared_access_key_value='accesskey')
queue = bus_service.get_queue('taskqueue1')
print queue.message_count
</code>```

Source code for Azure Service Bus SDK for Python is available on Github: https://github.com/Azure/azure-sdk-for-python/tree/master/azure-servicebus/azure/servicebus.

Body:
For this, you can use Azure Service Bus Python SDK. What you would need to do is get the properties of a queue using get_queue method that will return an object of type Queue. This object exposes the total number of messages through message_count property. Please note that this count will include count for active messages, dead-letter queue messages and more.

Here's a sample code to do so:

from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
    service_namespace='namespacename',
    shared_access_key_name='RootManageSharedAccessKey',
    shared_access_key_value='accesskey')
queue = bus_service.get_queue('taskqueue1')
print queue.message_count

Source code for Azure Service Bus SDK for Python is available on Github: https://github.com/Azure/azure-sdk-for-python/tree/master/azure-servicebus/azure/servicebus.


问:
making a php variable equal to a radio button
So what I am trying to do is making a radio button = to a php variable. So when someone clicks on the radio button and press continue they will get their pick on the website.

What I've tried:

```<code><form action="./game/index.php" method="post">
    <label id="coin1" class="coin1">
        <input type="radio" name="coin" value="<?php echo $pick; ?>"/><?php echo $pick; ?>
        <?php echo $ct; ?>
    </label>
    <label id="coin2" class="coin2">
        <input type="radio" name="coin" value="<?php echo $pick; ?>"/><?php echo $pick; ?>
        <?php echo $t; ?>
    </label>
    <button id="next">Create a Game</button>
</form>
</code>```

This is what I found when google-ing it but it doesn't really seem to work

this is what I used on the other site:

```<code><div id="player1">
    <a href="#"> <img class="img-square" src="<?php echo $steamprofile["avatarfull"]; ?>">
    <b><?php echo $steamprofile["personaname"]; ?></b><b class="caret"></b></a><br>
    <?php echo $pick; ?>
</div>
</code>```

and

```<code><div id="player2">
    <a href="#"> <img class="img-square" src="<?php echo $steamprofile["avatarfull"]; ?>">
    <b><?php echo $steamprofile["personaname"]; ?></b></a><br>
    <?php if ($pick == $ct) {
        echo $t;
    }else {
        if ($pick == $t) {
            echo $ct;
        }
    }
    ?>
</div>
</code>```

Thanks.

答:
To read the value into php you would need to use the $_POST variable. In ./game/index.php:

```<code>$coinvalue = $_POST['coin'];
</code>```

However the coins should have different values so you can tell which was selected.

Body:
So what I am trying to do is making a radio button = to a php variable. So when someone clicks on the radio button and press continue they will get their pick on the website.

What I've tried:

<form action="./game/index.php" method="post">

        <input type="radio" name="coin" value="<?php echo $pick; ?>"/><?php echo $pick; ?>
        <?php echo $ct; ?>

        <input type="radio" name="coin" value="<?php echo $pick; ?>"/><?php echo $pick; ?>
        <?php echo $t; ?>

    <button id="next">Create a Game</button>
</form>

This is what I found when google-ing it but it doesn't really seem to work

this is what I used on the other site:

     <img class="img-square" src="<?php echo $steamprofile["avatarfull"]; ?>">
    <?php echo $steamprofile["personaname"]; ?>

    <?php echo $pick; ?>

and

     <img class="img-square" src="<?php echo $steamprofile["avatarfull"]; ?>">
    <?php echo $steamprofile["personaname"]; ?>

    <?php if ($pick == $ct) {
        echo $t;
    }else {
        if ($pick == $t) {
            echo $ct;
        }
    }
    ?>

Thanks.

Body:
To read the value into php you would need to use the $_POST variable. In ./game/index.php:

$coinvalue = $_POST['coin'];

However the coins should have different values so you can tell which was selected.


问:
Is there a way to reset the app between tests in Swift XCTest UI?
Is there an API call within XCTest that I can put into the setUP() or tearDown() to reset the app between tests? I looked in the dot syntax of XCUIApplication and all I saw was the .launch()

OR is there a way to call a shell script in Swift? I could then call xcrun in-between test methods to reset the simulator.

答:
I used the @ODM answer, but modified it to work for Swift 4. NB: some S/O answers don't differentiate the Swift versions, which sometimes have fairly fundamental differences. I've tested this on an iPhone 7 simulator and an iPad Air simulator  in portrait orientation, and it worked for my app.

Swift 4

```<code>import XCTest
import Foundation

class Springboard {

let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let settings = XCUIApplication(bundleIdentifier: "com.apple.Preferences")

/**
 Terminate and delete the app via springboard
 */
func deleteMyApp() {
    XCUIApplication().terminate()

    // Resolve the query for the springboard rather than launching it
    springboard.activate()

    // Rotate back to Portrait, just to ensure repeatability here
    XCUIDevice.shared.orientation = UIDeviceOrientation.portrait
    // Sleep to let the device finish its rotation animation, if it needed rotating
    sleep(2)

    // Force delete the app from the springboard
    // Handle iOS 11 iPad 'duplication' of icons (one nested under "Home screen icons" and the other nested under "Multitasking Dock"
    let icon = springboard.otherElements["Home screen icons"].scrollViews.otherElements.icons["YourAppName"]
    if icon.exists {
        let iconFrame = icon.frame
        let springboardFrame = springboard.frame
        icon.press(forDuration: 2.5)

        // Tap the little "X" button at approximately where it is. The X is not exposed directly
        springboard.coordinate(withNormalizedOffset: CGVector(dx: ((iconFrame.minX + 3) / springboardFrame.maxX), dy:((iconFrame.minY + 3) / springboardFrame.maxY))).tap()
        // Wait some time for the animation end
        Thread.sleep(forTimeInterval: 0.5)

        //springboard.alerts.buttons["Delete"].firstMatch.tap()
        springboard.buttons["Delete"].firstMatch.tap()

        // Press home once make the icons stop wiggling
        XCUIDevice.shared.press(.home)
        // Press home again to go to the first page of the springboard
        XCUIDevice.shared.press(.home)
        // Wait some time for the animation end
        Thread.sleep(forTimeInterval: 0.5)

        // Handle iOS 11 iPad 'duplication' of icons (one nested under "Home screen icons" and the other nested under "Multitasking Dock"
        let settingsIcon = springboard.otherElements["Home screen icons"].scrollViews.otherElements.icons["Settings"]
        if settingsIcon.exists {
            settingsIcon.tap()
            settings.tables.staticTexts["General"].tap()
            settings.tables.staticTexts["Reset"].tap()
            settings.tables.staticTexts["Reset Location & Privacy"].tap()
            // Handle iOS 11 iPad difference in error button text
            if UIDevice.current.userInterfaceIdiom == .pad {
                settings.buttons["Reset"].tap()
            }
            else {
                settings.buttons["Reset Warnings"].tap()
            }
            settings.terminate()
        }
    }
  }
}
</code>```

Body:
I used the @ODM answer, but modified it to work for Swift 4. NB: some S/O answers don't differentiate the Swift versions, which sometimes have fairly fundamental differences. I've tested this on an iPhone 7 simulator and an iPad Air simulator  in portrait orientation, and it worked for my app.

Swift 4

import XCTest
import Foundation

class Springboard {

let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let settings = XCUIApplication(bundleIdentifier: "com.apple.Preferences")

/**
 Terminate and delete the app via springboard
 */
func deleteMyApp() {
    XCUIApplication().terminate()

    // Resolve the query for the springboard rather than launching it
    springboard.activate()

    // Rotate back to Portrait, just to ensure repeatability here
    XCUIDevice.shared.orientation = UIDeviceOrientation.portrait
    // Sleep to let the device finish its rotation animation, if it needed rotating
    sleep(2)

    // Force delete the app from the springboard
    // Handle iOS 11 iPad 'duplication' of icons (one nested under "Home screen icons" and the other nested under "Multitasking Dock"
    let icon = springboard.otherElements["Home screen icons"].scrollViews.otherElements.icons["YourAppName"]
    if icon.exists {
        let iconFrame = icon.frame
        let springboardFrame = springboard.frame
        icon.press(forDuration: 2.5)

        // Tap the little "X" button at approximately where it is. The X is not exposed directly
        springboard.coordinate(withNormalizedOffset: CGVector(dx: ((iconFrame.minX + 3) / springboardFrame.maxX), dy:((iconFrame.minY + 3) / springboardFrame.maxY))).tap()
        // Wait some time for the animation end
        Thread.sleep(forTimeInterval: 0.5)

        //springboard.alerts.buttons["Delete"].firstMatch.tap()
        springboard.buttons["Delete"].firstMatch.tap()

        // Press home once make the icons stop wiggling
        XCUIDevice.shared.press(.home)
        // Press home again to go to the first page of the springboard
        XCUIDevice.shared.press(.home)
        // Wait some time for the animation end
        Thread.sleep(forTimeInterval: 0.5)

        // Handle iOS 11 iPad 'duplication' of icons (one nested under "Home screen icons" and the other nested under "Multitasking Dock"
        let settingsIcon = springboard.otherElements["Home screen icons"].scrollViews.otherElements.icons["Settings"]
        if settingsIcon.exists {
            settingsIcon.tap()
            settings.tables.staticTexts["General"].tap()
            settings.tables.staticTexts["Reset"].tap()
            settings.tables.staticTexts["Reset Location & Privacy"].tap()
            // Handle iOS 11 iPad difference in error button text
            if UIDevice.current.userInterfaceIdiom == .pad {
                settings.buttons["Reset"].tap()
            }
            else {
                settings.buttons["Reset Warnings"].tap()
            }
            settings.terminate()
        }
    }
  }
}


问:
How to write custom functions for in memory HSQL
I want to write a simple function in HSQL so that it is backwards compatible with DB2 functions. In theory I should be able to write a custom function in java and hook it into HSQL. Is there any direction/documentation on just that?</p>

答:
User defined functions are documented in the HSQLDB Guide. See this section for functions written in Java.

http://hsqldb.org/doc/2.0/guide/sqlroutines-chapt.html#src_jrt_routines

You can also write your functions in SQL, which is documented in the same chapter of the Guide.


问:
Pulling dynamic data from server and displaying into PDF using TCPDF
I have been attempting to use PHP to create a dynamic PDF file which can be downloaded. I have included the code below. Document is displaying blank data and nothing on the PDF file.

```<code><?php
$output = '';
$quote = $_GET['quote'];
function fetchData(){
    include 'config.php';
    $quote = $_GET['quote'];
    $output = '';
    $query = "SELECT * FROM quote_list, quotation WHERE quote_list.quote_id = quotation.id AND quote_list.quote_id = '$quote'";
    $result = mysqli_query($connect, $query);

    if($row = mysqli_fetch_assoc($result)){

    $companyName = $row['name'];
    $email = $row['email'];

    $countQuery = "SELECT COUNT(quotation.id) AS countRow FROM quotation WHERE company_name = '$companyName'";
    $countRes = mysqli_query($connect, $countQuery);

    while($countRow = mysqli_fetch_assoc($countRes)){
        $count = $countRow['countRow'];
    }

    $quoteNum = $companyName . ' - ' .$count;

    $sqlDate = $row['date'];
    $date = strtotime($sqlDate);
    $date = date('j F Y', $date);

    $output .= "
    <div class='row'>
        <div class='col'>
            <img class='logo' src='img/logo.jpg'>
        </div>
    </div>

    <div class='row margin'>
        <div class='col'>
            <strong><h3>To:" .  $companyName . "</h3>
            Email:". $email."</strong>
        </div>
    </div>

    <div class='row margin'>
        <div class='col'>Quotation Number:".  $quoteNum ."</div>
    </div>

    <div class='row'>
        <div class='col'>Issue Date:". $date ."</div>
    </div>

    <div class='row margin'>
        <div class='col'>
            <p>Further to your enquiry, please find attached our quotation based on your discussed requirements. If you have any other queries, amendments or your requirements change please do not hesitate to contact me.</p>
            <p>Thank you for the opportunity to quote on this project.</p>
        </div>
    </div>

    <div class='row margin'>
        <div class='col'>
            <h1>Your quotation:</h1>
            <table class='table table-bordered table-striped table-condensed table-responsive'>
                <thead>
                    <tr>
                        <th>
                            Quote Details
                        </th>
                        <th class='float-right'>
                            Amount Quoted
                        </th>
                    </tr>
                </thead>
                <tbody>";

                $query = "SELECT * FROM quote_list, quotation WHERE quote_list.quote_id = quotation.id AND quote_list.quote_id = '$quote'";
                $result = mysqli_query($connect, $query);
                $total = 0;
                $discount = 0;

                while($row = mysqli_fetch_assoc($result)){
                    $title = $row['title'];
                    $price = $row['price'];
                    $discount = $row['discount'];
                    $total += $price;

                    $ouput .=
                    "
                    <tr>
                        <td>".
                            $title."
                        </td>
                        <td class='float-right'>
                            £".$price.
                            "
                        </td>
                    </tr>
                    ";
                }

                $final = $total-$discount;

                $output .= "
                    <tr>
                        <td></td>
                        <td class='float-right'><em><strong>Total: </strong></em>£".$total."</br><em><strong>Discount: </strong></em>£".$discount."</br><em><strong>Quotation Price: </strong></em>£".$final."</td>
                    </tr>
               </tbody>
                </table>
        </div>
    </div>

    <div class='row margin'>
        <div class='col'>
            <h1>Terms and Conditions</h1>
            <h2>Our Quotation</h2>
            <p>The above costs are inclusive of VAT, which will be charged where applicable. NI Flyers Print & Design quotations are valid for 30 days. Design costs are based on our understanding of your initial brief. Any additional amends/change to brief will be advised prior to invoicing. The right of design creations remains exclusively with NI Flyers Print & Design including economic and moral rights. Acceptance of this quotation includes a non-exclusive licence for the use of the works outlined above. An exclusive licence may be obtained at an additional cost.</p>

            <h2>Additional photographic or illustration-based imagery</h2>
            <p>Sourced photography or illustration this will be an additional cost to the design process. Imagery can be sourced either from stock library at £30.00 per image, or commissioned at cost, which will always be pre-quoted. If attendance to manage or art direct photoshoots is required this will be based on our standard hourly rate of £50 per hour. Additional photoshoot props or services will be charged accordingly.</p>

        </div>
    </div>
";
   }
        return $output;
   }

if(isset($_GET['viewPDF'])){
  require_once('tcpdf/tcpdf.php');
  $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  $obj_pdf->SetCreator(PDF_CREATOR);
  $obj_pdf->SetTitle("Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP");
  $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
  $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  $obj_pdf->SetDefaultMonospacedFont('helvetica');
  $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);
  $obj_pdf->setPrintHeader(false);
  $obj_pdf->setPrintFooter(false);
  $obj_pdf->SetAutoPageBreak(TRUE, 10);
  $obj_pdf->SetFont('helvetica', '', 11);
  $obj_pdf->AddPage();
  $output .= fetchData();
  $obj_pdf->writeHTML($output);
  $obj_pdf->Output('Quote_' . $quote . '.pdf', 'I');
}
 ?>
</code>```

Is there something I have done wrong in making this document? I was following a tutorial and documentation on this and cannot seem to make it load at all. Always a blank PDF document for some reason. Are there any simpler tools to be used when coming to PDF creation via PHP dynamically?

答:
It would appear that your fetchData() function is not returning anything.

If I amend:

```<code>$obj_pdf->writeHTML($output);
</code>```

To read ..

```<code>$obj_pdf->writeHTML('hello world');
</code>```

Then this correctly shows in the PDF. This would seem to confirm that your TCPDF code is correct.

When I run your code locally then I don't get anything returned by your fetchData() function. Obviously I don't have your database set-up but I think this is where your issue is.

Have a go adding some echos throughout the function and make sure that what you think is being returned is being returned.

Body:
I have been attempting to use PHP to create a dynamic PDF file which can be downloaded. I have included the code below. Document is displaying blank data and nothing on the PDF file.

<?php
$output = '';
$quote = $_GET['quote'];
function fetchData(){
    include 'config.php';
    $quote = $_GET['quote'];
    $output = '';
    $query = "SELECT * FROM quote_list, quotation WHERE quote_list.quote_id = quotation.id AND quote_list.quote_id = '$quote'";
    $result = mysqli_query($connect, $query);

    if($row = mysqli_fetch_assoc($result)){

    $companyName = $row['name'];
    $email = $row['email'];

    $countQuery = "SELECT COUNT(quotation.id) AS countRow FROM quotation WHERE company_name = '$companyName'";
    $countRes = mysqli_query($connect, $countQuery);

    while($countRow = mysqli_fetch_assoc($countRes)){
        $count = $countRow['countRow'];
    }

    $quoteNum = $companyName . ' - ' .$count;

    $sqlDate = $row['date'];
    $date = strtotime($sqlDate);
    $date = date('j F Y', $date);

    $output .= "

To:" .  $companyName . "

            Email:". $email."

Quotation Number:".  $quoteNum ."

Issue Date:". $date ."

Further to your enquiry, please find attached our quotation based on your discussed requirements. If you have any other queries, amendments or your requirements change please do not hesitate to contact me.

Thank you for the opportunity to quote on this project.

Your quotation:

                            Quote Details

                            Amount Quoted

";

                $query = "SELECT * FROM quote_list, quotation WHERE quote_list.quote_id = quotation.id AND quote_list.quote_id = '$quote'";
                $result = mysqli_query($connect, $query);
                $total = 0;
                $discount = 0;

                while($row = mysqli_fetch_assoc($result)){
                    $title = $row['title'];
                    $price = $row['price'];
                    $discount = $row['discount'];
                    $total += $price;

                    $ouput .=
                    "

                        ".
                            $title."

                            £".$price.
                            "

                    ";
                }

                $final = $total-$discount;

                $output .= "

                        Total: £".$total."
Discount: £".$discount."
Quotation Price: £".$final."

Terms and Conditions

Our Quotation

The above costs are inclusive of VAT, which will be charged where applicable. NI Flyers Print & Design quotations are valid for 30 days. Design costs are based on our understanding of your initial brief. Any additional amends/change to brief will be advised prior to invoicing. The right of design creations remains exclusively with NI Flyers Print & Design including economic and moral rights. Acceptance of this quotation includes a non-exclusive licence for the use of the works outlined above. An exclusive licence may be obtained at an additional cost.

Additional photographic or illustration-based imagery

Sourced photography or illustration this will be an additional cost to the design process. Imagery can be sourced either from stock library at £30.00 per image, or commissioned at cost, which will always be pre-quoted. If attendance to manage or art direct photoshoots is required this will be based on our standard hourly rate of £50 per hour. Additional photoshoot props or services will be charged accordingly.

";
   }
        return $output;
   }

if(isset($_GET['viewPDF'])){
  require_once('tcpdf/tcpdf.php');
  $obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  $obj_pdf->SetCreator(PDF_CREATOR);
  $obj_pdf->SetTitle("Generate HTML Table Data To PDF From MySQL Database Using TCPDF In PHP");
  $obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
  $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  $obj_pdf->SetDefaultMonospacedFont('helvetica');
  $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  $obj_pdf->SetMargins(PDF_MARGIN_LEFT, '10', PDF_MARGIN_RIGHT);
  $obj_pdf->setPrintHeader(false);
  $obj_pdf->setPrintFooter(false);
  $obj_pdf->SetAutoPageBreak(TRUE, 10);
  $obj_pdf->SetFont('helvetica', '', 11);
  $obj_pdf->AddPage();
  $output .= fetchData();
  $obj_pdf->writeHTML($output);
  $obj_pdf->Output('Quote_' . $quote . '.pdf', 'I');
}
 ?>

Is there something I have done wrong in making this document? I was following a tutorial and documentation on this and cannot seem to make it load at all. Always a blank PDF document for some reason. Are there any simpler tools to be used when coming to PDF creation via PHP dynamically?

Body:
It would appear that your fetchData() function is not returning anything.

If I amend:

$obj_pdf->writeHTML($output);

To read ..

$obj_pdf->writeHTML('hello world');

Then this correctly shows in the PDF. This would seem to confirm that your TCPDF code is correct.

When I run your code locally then I don't get anything returned by your fetchData() function. Obviously I don't have your database set-up but I think this is where your issue is.

Have a go adding some echos throughout the function and make sure that what you think is being returned is being returned.


问:
Adding random items on a canvas view
I'm trying to add some items from a csv file into my canvas view. I'm making a game where you "dig" a hole and get some loot. Like a minesweeper type of game. But I'm not sure how to add the items at random on the canvas. All my items are in an arraylist, but not sure how to add them on the game. Then update my score whenever loot has been found.

My code:

```<code>// List of items from CSV file.
private ArrayList<ItemObject> mLoot;
private String itemSize;

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    // Let the view know that we want to draw.
    setWillNotDraw(false);

    getHolder().addCallback(this);

    Resources res = getResources();

    // background image
    mBackground = BitmapFactory.decodeResource(res, R.drawable.field);
    mBlackPaint = new Paint();

    // Score text
    mScoreTextPaint = new Paint();
    mScoreTextPaint.setColor(Color.WHITE);
    mScoreTextPaint.setTextSize(60.0f);
    mScoreTextPaint.setTextAlign(Paint.Align.CENTER);

    // Show hole image
    mHole = BitmapFactory.decodeResource(res, R.drawable.hole);

    mPoints = new ArrayList<>();

    // Get CSV items
    InputStream inputStream = getResources().openRawResource(R.raw.items);
    GetCSVFile csvFile = new GetCSVFile(inputStream);
    mLoot = csvFile.read();

    itemSize = String.valueOf(mLoot.size());

    for(ItemObject itemData:mLoot ) {

        //TODO: add a random x,y position for loot?

        // itemData.getLoot() - "gold"
        // itemData.getValue() - "50"

    }
</code>```

My onDraw method:

```<code>@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // Clear the canvas by drawing a single color.
    canvas.drawColor(Color.BLACK);

    // Draw image to cover all dimensions of the screen.
    canvas.drawBitmap(mBackground, null, mDimensions, mBlackPaint);

    // Draw a circle at each touch.
    for(Point p: mPoints){
        // show hole's image when a player touches the screen
        canvas.drawBitmap(mHole,p.x,p.y,null);

    }

    // Draw text in middle of screen.
    canvas.drawText("Hidden Treasure: " + itemSize,
            mDimensions.width() / 2.0f,
            mDimensions.height() / 15.0f,
            mScoreTextPaint);

} // end onDraw
</code>```

答:
If you are using the entire screen then get the screen width and height:

```<code>DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int maxHeight = displayMetrics.heightPixels;
int maxWidth = displayMetrics.widthPixels;
</code>```

Otherwise determine the maxX and maxY values you need.

Create a little method to get a random position;

```<code>private int randomPosition(int min, int max)
{
    int range = (max - min) + 1;
    return (int)(Math.random() * range) + min;
}
</code>```

In your "ItemObject" you should add the setters and getters for the object coordinates:

```<code>String item = "";
int x = 0;
int y = 0;

public void setItem(String item) { this.item = item; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }

public String getItem() { return this.item; }
public int getX() { return this.x; }
public int getY() { return this.y; }
</code>```

After you get the content of your csv File as a string you can call a split on the delimiter:

```<code>String myDelimiter = ","; // Or what ever your delimiter is
String[] lines = csvData.Split(myDelimiter);
</code>```

Now loop through the lines and get he random positions;

```<code>for(String s : lines ) {
    // if 0 is the smallest x coordinates
    int x = random(0, maxWidth);
    int y = random(0, maxHeight);
    ItemObject item = new ItemObject();
    item.setItem(s)
    item.setX(x);
    item.setY(y);
    mLoot.add(item);
}
</code>```

In your drawing routine just use step through "mLoot" and draw the objects.

Title: Adding random items on a canvas view

Body:
I'm trying to add some items from a csv file into my canvas view. I'm making a game where you "dig" a hole and get some loot. Like a minesweeper type of game. But I'm not sure how to add the items at random on the canvas. All my items are in an arraylist, but not sure how to add them on the game. Then update my score whenever loot has been found.

My code:

// List of items from CSV file.
private ArrayList<ItemObject> mLoot;
private String itemSize;

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    // Let the view know that we want to draw.
    setWillNotDraw(false);

    getHolder().addCallback(this);

    Resources res = getResources();

    // background image
    mBackground = BitmapFactory.decodeResource(res, R.drawable.field);
    mBlackPaint = new Paint();

    // Score text
    mScoreTextPaint = new Paint();
    mScoreTextPaint.setColor(Color.WHITE);
    mScoreTextPaint.setTextSize(60.0f);
    mScoreTextPaint.setTextAlign(Paint.Align.CENTER);

    // Show hole image
    mHole = BitmapFactory.decodeResource(res, R.drawable.hole);

    mPoints = new ArrayList<>();

    // Get CSV items
    InputStream inputStream = getResources().openRawResource(R.raw.items);
    GetCSVFile csvFile = new GetCSVFile(inputStream);
    mLoot = csvFile.read();

    itemSize = String.valueOf(mLoot.size());

    for(ItemObject itemData:mLoot ) {

        //TODO: add a random x,y position for loot?

        // itemData.getLoot() - "gold"
        // itemData.getValue() - "50"

    }

My onDraw method:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // Clear the canvas by drawing a single color.
    canvas.drawColor(Color.BLACK);

    // Draw image to cover all dimensions of the screen.
    canvas.drawBitmap(mBackground, null, mDimensions, mBlackPaint);

    // Draw a circle at each touch.
    for(Point p: mPoints){
        // show hole's image when a player touches the screen
        canvas.drawBitmap(mHole,p.x,p.y,null);

    }

    // Draw text in middle of screen.
    canvas.drawText("Hidden Treasure: " + itemSize,
            mDimensions.width() / 2.0f,
            mDimensions.height() / 15.0f,
            mScoreTextPaint);

} // end onDraw

Body:
If you are using the entire screen then get the screen width and height:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int maxHeight = displayMetrics.heightPixels;
int maxWidth = displayMetrics.widthPixels;

Otherwise determine the maxX and maxY values you need.

Create a little method to get a random position;

private int randomPosition(int min, int max)
{
    int range = (max - min) + 1;
    return (int)(Math.random() * range) + min;
}

In your "ItemObject" you should add the setters and getters for the object coordinates:

String item = "";
int x = 0;
int y = 0;

public void setItem(String item) { this.item = item; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }

public String getItem() { return this.item; }
public int getX() { return this.x; }
public int getY() { return this.y; }

After you get the content of your csv File as a string you can call a split on the delimiter:

String myDelimiter = ","; // Or what ever your delimiter is
String[] lines = csvData.Split(myDelimiter);

Now loop through the lines and get he random positions;

for(String s : lines ) {
    // if 0 is the smallest x coordinates
    int x = random(0, maxWidth);
    int y = random(0, maxHeight);
    ItemObject item = new ItemObject();
    item.setItem(s)
    item.setX(x);
    item.setY(y);
    mLoot.add(item);
}

In your drawing routine just use step through "mLoot" and draw the objects.


问:
Why not volatile on System.Double and System.Long?
A question like mine has been asked, but mine is a bit different.  The question is, "Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

On first blush, I answered my colleague, "Well, on a 32-bit machine, those types take at least two ticks to even enter the processor, and the .Net framework has the intention of abstracting away processor-specific details like that."  To which he responds, "It's not abstracting anything if it's preventing you from using a feature because of a processor-specific problem!"

He's implying that a processor-specific detail should not show up to a person using a framework that "abstracts" details like that away from the programmer.  So, the framework (or C#) should abstract away those and do what it needs to do to offer the same guarantees for System.Double, etc. (whether that's a Semaphore, memory barrier, or whatever).  I argued that the framework shouldn't add the overhead of a Semaphore on volatile, because the programmer isn't expecting such overhead with such a keyword, because a Semaphore isn't necessary for the 32-bit types.  The greater overhead for the 64-bit types might come as a surprise, so, better for the .Net framework to just not allow it, and make you do your own Semaphore on larger types if the overhead is acceptable.

That led to our investigating what the volatile keyword is all about.  (see this page).  That page states, in the notes:

In C#, using the volatile modifier on a field guarantees that all access to that field uses VolatileRead or VolatileWrite.

Hmmm.....VolatileRead and VolatileWrite both support our 64-bit types!! My question, then, is,

"Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

答:
He's implying that a processor-specific detail should not show up to a person using a framework that "abstracts" details like that away from the programmer.

If you are using low-lock techniques like volatile fields, explicit memory barriers, and the like, then you are entirely in the world of processor-specific details. You need to understand at a deep level precisely what the processor is and is not allowed to do as far as reordering, consistency, and so on, in order to write correct, portable, robust programs that use low-lock techniques.

The point of this feature is to say "I am abandoning the convenient abstractions guaranteed by single-threaded programming and embracing the performance gains possible by having a deep implementation-specific knowledge of my processor."  You should expect less abstractions at your disposal when you start using low-lock techniques, not more abstractions.

You're going "down to the metal" for a reason, presumably; the price you pay is having to deal with the quirks of said metal.


问:
Microservice project structure using Spring boot and Spring Cloud
I am trying to convert a normal monolithic web application into microservices structure using Spring Boot and Spring Cloud. I am actually trying to create Angular 2 front-end application and calls these my developed microservices in the cloud. And I am already started to break the modules into independent process's structure for microservice architecture.

Here my doubt is that, when designing the flow of control and microservice structure architecture, can I use only one single Spring Boot project using different controller for this entire web application back end process?

Somewhere I found that when I am reading develop all microservices using 2 different Spring Boot project. I am new to Spring and Spring Cloud. Is it possible to create all services in single project by using different modules?

答:
Actually, it doesn't matter to package all those services into ONE project. But in micro-service's opinion, you should separate them into many independent projects. There are several questions you can ask yourself before transforming original architecture.

Is your application critical? Can user be tolerant of downtime while you must re-deploying whole package for updating only one service?

If there is no any dependency between services, why you want to put them together? Isn't it hard to develop or maintain?

Is the usage rate of each service the same? Maybe you can isolate those services and deploy them which are often to be invoked to a strong server.

Try to read this article Adopting Microservices at Netflix: Lessons for Architectural Design to understand the best practices for designing a microservices architecture. And for developing with Spring Cloud, you can also read this post Spring Cloud Netflix to know which components you should use in your architecture.


问:
Axios Paypal Token Issue
As a precursor I don't understand why if the token expires one would want to use CURL or Postman to get the token rather than a ajax call that would continously get the updated token before sending payment.

Anyway I was able to use Postman to get a token, but I have tried several axios requests with none successfully obtaining a token. I am getting a 401 unauthorized error. My understanding is by using auth: { username: '', password: '' } that it enables basic auth. My axios attempt is below however instead of empty strings I have strings of my client id and secret. Any help would be greatly appreciated

```<code>axios.post('https://api.sandbox.paypal.com/v1/oauth2/token', {
  grant_type: 'client_credentials',
  auth: {username: '',
    password: ''
  },
  headers:{
    'Content-Type':'x-www-form-urlencoded'
  }}
).then((result)=>{
    console.log('resultis',result)
  }).catch((err)=>{console.log("err",err)})
</code>```

答: One easy solution is to use the node SDK rather than actaully making the HTTP request yourself.</p>

Title: Axios Paypal Token Issue

Body:
As a precursor I don't understand why if the token expires one would want to use CURL or Postman to get the token rather than a ajax call that would continously get the updated token before sending payment.

Anyway I was able to use Postman to get a token, but I have tried several axios requests with none successfully obtaining a token. I am getting a 401 unauthorized error. My understanding is by using auth: { username: '', password: '' } that it enables basic auth. My axios attempt is below however instead of empty strings I have strings of my client id and secret. Any help would be greatly appreciated

axios.post('https://api.sandbox.paypal.com/v1/oauth2/token', {
  grant_type: 'client_credentials',
  auth: {username: '',
    password: ''
  },
  headers:{
    'Content-Type':'x-www-form-urlencoded'
  }}
).then((result)=>{
    console.log('resultis',result)
  }).catch((err)=>{console.log("err",err)})


问:
Prevent script running with same arguments twice
We are looking into building a logcheck script that will tail a given log file and email when the given arguments are found.  I am having trouble accurately determining if another version of this script is running with at least one of the same arguments against the same file.  Script can take the following:

```<code>logcheck -i <filename(s)> <searchCriterion> <optionalEmailAddresses>
</code>```

I have tried to use ps aux with a series of grep, sed, and cut, but it always ends up being more code than the script itself and seldom works very efficiently.  Is there an efficient way to tell if another version of this script is running with the same filename and search criteria? A few examples of input:

```<code>EX1 .\logcheck -i file1,file2,file3 "foo string 0123" email@address.com
EX2 .\logcheck -s file1 Hello,World,Foo
EX3 .\logcheck -i file3 foo email@address1.com,email@address2.com
</code>```

In this case 3 should not run because 1 is already running with parameters file3 and foo.

答:
There are many solutions for your problem, I would recommend creating a lock file, with the following format:

```<code>arg1Ex1 PID#(Ex1)
arg2Ex1 PID#(Ex1)
arg3Ex1 PID#(Ex1)
arg4Ex1 PID#(Ex1)
arg1Ex2 PID#(Ex2)
arg2Ex2 PID#(Ex2)
arg3Ex2 PID#(Ex2)
arg4Ex2 PID#(Ex2)
</code>```

when your script starts:

It will search in the file for all the arguments it has received (awk command or grep)

If one of the arguments is present in the list, fetch the process PID (awk 'print $2' for example) to check if it is still running (ps) (double check for concurrency and in case of process ended abnormally previously garbage might remain inside the file)

If the PID is still there, the script will not run

Else append the arguments to the lock file with the current process PID and run the script.

At the end, of the execution you remove the lines that contains the arguments that have been used by the script, or remove all lines with its PID.

Body:
We are looking into building a logcheck script that will tail a given log file and email when the given arguments are found.  I am having trouble accurately determining if another version of this script is running with at least one of the same arguments against the same file.  Script can take the following:

logcheck -i <filename(s)> <searchCriterion> <optionalEmailAddresses>

I have tried to use ps aux with a series of grep, sed, and cut, but it always ends up being more code than the script itself and seldom works very efficiently.  Is there an efficient way to tell if another version of this script is running with the same filename and search criteria? A few examples of input:

EX1 .\logcheck -i file1,file2,file3 "foo string 0123" email@address.com
EX2 .\logcheck -s file1 Hello,World,Foo
EX3 .\logcheck -i file3 foo email@address1.com,email@address2.com

In this case 3 should not run because 1 is already running with parameters file3 and foo.

Body:
There are many solutions for your problem, I would recommend creating a lock file, with the following format:

arg1Ex1 PID#(Ex1)
arg2Ex1 PID#(Ex1)
arg3Ex1 PID#(Ex1)
arg4Ex1 PID#(Ex1)
arg1Ex2 PID#(Ex2)
arg2Ex2 PID#(Ex2)
arg3Ex2 PID#(Ex2)
arg4Ex2 PID#(Ex2)

when your script starts:

It will search in the file for all the arguments it has received (awk command or grep)

If one of the arguments is present in the list, fetch the process PID (awk 'print $2' for example) to check if it is still running (ps) (double check for concurrency and in case of process ended abnormally previously garbage might remain inside the file)

If the PID is still there, the script will not run

Else append the arguments to the lock file with the current process PID and run the script.

At the end, of the execution you remove the lines that contains the arguments that have been used by the script, or remove all lines with its PID.


问:
Trouble Using Java Command-Line Arguments in NetBeans
I have looked at every tutorial on using command-line arguments in NetBeans known to man and I am starting to think it's not me (famous last words)!

This image is from right-clicking on the project and going to the run tab. I set my main class appropriately, put in my arguments, but I'm still always hitting the line that says that the length of my arguments is less than 4. In fact, when I try to print args[0] I get a IndexOutOfBoundsException. Any thoughts?

Here is the top of my Java file, as requested!

Also, here is another more simple example with it still not working as I would expect. I've tried to include all the steps I took:

Womp.

答:
I am unable to reproduce your issue in my environment, however the most likely cause is that:

Your main class is WordCloudGenerator, and from what I can tell the code in the image you have shown is not from WordCloudGenerator class.

You need to make sure that your main class is set correctly in the properties window shown in the first image in your question. Or if you do want two classes with main methods, then WordCloudGenerator needs to forward those args onto your other class like so:

```<code>public class WordCloudGenerator
{

    public static void main(String[] args)
    {
        myOtherClass.main(args);
    }
}
</code>```

Now your main method in the other class should function correctly.

Body:
I am unable to reproduce your issue in my environment, however the most likely cause is that:

Your main class is WordCloudGenerator, and from what I can tell the code in the image you have shown is not from WordCloudGenerator class.

You need to make sure that your main class is set correctly in the properties window shown in the first image in your question. Or if you do want two classes with main methods, then WordCloudGenerator needs to forward those args onto your other class like so:

public class WordCloudGenerator
{

    public static void main(String[] args)
    {
        myOtherClass.main(args);
    }
}

Now your main method in the other class should function correctly.


问:
Unable to create file in Google Drive with node.js and OAuth tokens
Everything I've looked at suggests my code should work, and the logs in Firebase Functions console shows that it returns
Function execution took 6 ms, finished with status: 'ok'
I've based my code off this sample: https://github.com/firebase/functions-samples/tree/master/google-sheet-sync
From which I get in the logs Function execution took 296 ms, finished with status: 'ok'

After I got the google-sheets example working, I basicaly copy/pasted it and change a few lines but no matter what I do I can't seem to get Google Drive working.

Here's the code I've come up with (if you check the google-sheets example you'll see how they're basically the same).

```<code>exports.makenewfolder = functions.database.ref(`${CONFIG_DATA_PATH}/{ITEM}`).onWrite(
      event => {
        // Since we're not dealing with the data from the DB, don't need the spreadsheets info
        // Just need to return the promise with auth included
        /*var fileMetadata = {
          'name': 'test folder',
          'mimeType': 'application/vnd.google-apps.folder'
        };*/

        var fileMetadata = {
          name: 'Test',
          mimeType: 'text/plain'
        }
        return drivePromise(this.fileMetadata);
      }
    )

    function drivePromise(requestWithoutAuth) {
      return new Promise((resolve, reject) => {
        getAuthorizedClient().then(client => {
          const service = google.drive({ version: 'v3', auth: client });
          const request = requestWithoutAuth;
          request.auth = client;

          service.files.create({
            resource: {
              name: 'Test',
              mimeType: 'text/plain'
            },
            media: {
              mimeType: 'text/plain',
              body: 'Hello World'
            }
          }, (err, file) => {
            if (err) {
              // handle error
              console.error(err);
            } else {
              console.log('Folder id: ', file.id);
            }
          }
        );
        }).catch(() => reject());
      })
    }
</code>```

Why does this not work? It should be working because the SCOPE is for https://www.googleapis.com/auth/drive instead of /auth/spreadsheets so it shouldn't be able to modify the spreadsheet anymore except through the fact that the spreadsheet is in Google Drive. When I run the code which includes the rest of the code from the sample, the spreadsheet still gets updated. The logs show that these functions are being called, but nothing happens in Google Drive. How do I fix this?

答: return drivePromise(this.fileMetadata); doesn't work apparently. return drivePromise(fileMetadata); does. Sigh.

Body:
Everything I've looked at suggests my code should work, and the logs in Firebase Functions console shows that it returns
Function execution took 6 ms, finished with status: 'ok'
I've based my code off this sample: https://github.com/firebase/functions-samples/tree/master/google-sheet-sync
From which I get in the logs Function execution took 296 ms, finished with status: 'ok'

After I got the google-sheets example working, I basicaly copy/pasted it and change a few lines but no matter what I do I can't seem to get Google Drive working.

Here's the code I've come up with (if you check the google-sheets example you'll see how they're basically the same).

exports.makenewfolder = functions.database.ref(`${CONFIG_DATA_PATH}/{ITEM}`).onWrite(
      event => {
        // Since we're not dealing with the data from the DB, don't need the spreadsheets info
        // Just need to return the promise with auth included
        /*var fileMetadata = {
          'name': 'test folder',
          'mimeType': 'application/vnd.google-apps.folder'
        };*/

        var fileMetadata = {
          name: 'Test',
          mimeType: 'text/plain'
        }
        return drivePromise(this.fileMetadata);
      }
    )

    function drivePromise(requestWithoutAuth) {
      return new Promise((resolve, reject) => {
        getAuthorizedClient().then(client => {
          const service = google.drive({ version: 'v3', auth: client });
          const request = requestWithoutAuth;
          request.auth = client;

          service.files.create({
            resource: {
              name: 'Test',
              mimeType: 'text/plain'
            },
            media: {
              mimeType: 'text/plain',
              body: 'Hello World'
            }
          }, (err, file) => {
            if (err) {
              // handle error
              console.error(err);
            } else {
              console.log('Folder id: ', file.id);
            }
          }
        );
        }).catch(() => reject());
      })
    }

Why does this not work? It should be working because the SCOPE is for https://www.googleapis.com/auth/drive instead of /auth/spreadsheets so it shouldn't be able to modify the spreadsheet anymore except through the fact that the spreadsheet is in Google Drive. When I run the code which includes the rest of the code from the sample, the spreadsheet still gets updated. The logs show that these functions are being called, but nothing happens in Google Drive. How do I fix this?


问:
What does "#NOQA" mean inside `__init__.py` file in Chainer library?
I am reading Chainer source code and noticed at https://github.com/chainer/chainer/blob/master/chainer/init.py#L7

```<code>from chainer import configuration  # NOQA
from chainer import cuda  # NOQA
from chainer import dataset  # NOQA
from chainer import datasets  # NOQA
</code>```

What does #NOQA mean?

Thanks

答: # NOQA is an instruction for a linter to ignore checks on that line. Flake8/pep8 will not report on errors from lines ending with this. See the flake8 documentation on ignoring violations for some more details.

Body:
I am reading Chainer source code and noticed at https://github.com/chainer/chainer/blob/master/chainer/init.py#L7

from chainer import configuration  # NOQA
from chainer import cuda  # NOQA
from chainer import dataset  # NOQA
from chainer import datasets  # NOQA

What does #NOQA mean?

Thanks


问:
Trying to set up Cloud Firestore security rules using request.path
I am struggling to get my head around some Firestore security concepts. I want to set up a rule based on the request.path property.

My rule is this:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.path[0]=='appUsers';
    }
  }
}
</code>```

...and I then use AngularFire2 to add a document like this...

```<code>this.myAngularFirestore.doc('/appUsers/'+this.auth.auth.currentUser.uid).set({name: this.auth.auth.currentUser.displayName})
      .then(()=>console.log('Added user'))
      .catch(err=>console.log('Could not add user:', err.message));
</code>```

I thought this should be simple based on the docs but all I ever get is the error - Missing or insufficient permissions.

I know I am logged in correctly and I know the query works if I open up the security with allow read,write: if true; so what am I not getting here?
Shouldn't request.path[0] evaluate to the string appUsers here and so allow the data to be written?

Any ideas gratefully accepted as I'm not finding these rules much fun to out together so far.

Cheers all

答:
I'd recommend using the built-in path matcher version of this:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /appUsers {
      allow read, write;
    }
  }
}
</code>```

Or, if you really want to specify in the condition:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{pathSegment} {
      allow read, write: if pathSegment == "appUsers";
    }
  }
}
</code>```

request.path is the full path (e.g. /projects/<projectId>/databases/(default)/documents/appUsers, which means you'd actually want request.path[5] (hence why we provide easier, more readable ways of doing this).

Edit (4/2/18): request.path supports both List and Map access:

List: request.path[5] == "appUsers"

Map: request.path['pathSegment'] == "appUsers", though note that it only works on wildcarded (e.g. {name}) values

Body:
I am struggling to get my head around some Firestore security concepts. I want to set up a rule based on the request.path property.

My rule is this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.path[0]=='appUsers';
    }
  }
}

...and I then use AngularFire2 to add a document like this...

this.myAngularFirestore.doc('/appUsers/'+this.auth.auth.currentUser.uid).set({name: this.auth.auth.currentUser.displayName})
      .then(()=>console.log('Added user'))
      .catch(err=>console.log('Could not add user:', err.message));

I thought this should be simple based on the docs but all I ever get is the error - Missing or insufficient permissions.

I know I am logged in correctly and I know the query works if I open up the security with allow read,write: if true; so what am I not getting here?
Shouldn't request.path[0] evaluate to the string appUsers here and so allow the data to be written?

Any ideas gratefully accepted as I'm not finding these rules much fun to out together so far.

Cheers all

Body:
I'd recommend using the built-in path matcher version of this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /appUsers {
      allow read, write;
    }
  }
}

Or, if you really want to specify in the condition:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{pathSegment} {
      allow read, write: if pathSegment == "appUsers";
    }
  }
}

request.path is the full path (e.g. /projects/<projectId>/databases/(default)/documents/appUsers, which means you'd actually want request.path[5] (hence why we provide easier, more readable ways of doing this).

Edit (4/2/18): request.path supports both List and Map access:

List: request.path[5] == "appUsers"

Map: request.path['pathSegment'] == "appUsers", though note that it only works on wildcarded (e.g. {name}) values


问:
unordered_map collision with buckets
I am working with the unordered_map library in C++11 and I am a bit confused about how buckets work. It is clear to me that they do not work as I thought they would, per the documents on the cplusplus website.

I expected that the keys in my pairs would be hashed into the same bucket. For example:

```<code>#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
  unordered_map<string, string> map;
  map.emplace("abc", "bca");
  map.emplace("abc", "bac");
  cout << map.bucket_size(map.bucket("abc")) << endl;
  cout << map.bucket_count() << endl;
  return 0;
}
</code>```

My expectation here was that the output would be

```<code>2
1
</code>```

However, it was

```<code>1
2
</code>```

I understand that what was output is much more ideal than my expectation, and having as little chaining as possible is the goal, but for my purposes I want this chaining and collision to happen so that I can carry out the computations I need to for my program. Am I missing the step to accomplish this?

答:
A couple of things come up - one is that you're putting the same key in twice. What ends up happening is that the second emplace actually fails because with any of the map data structures, you only get one value per key. If you look, you'll find that the bucket containing "abc" has the value of "bca" to go with it.

As to bucket_count, there's no guarantee that it be any particular value and it's likely implementation defined. It could, for instance, be that your implementation always creates at least 2 buckets if it creates any. It could also have created the second bucket on insert of the second item before deciding that the item is discarded.

Title: unordered_map collision with buckets

Body:
I am working with the unordered_map library in C++11 and I am a bit confused about how buckets work. It is clear to me that they do not work as I thought they would, per the documents on the cplusplus website.

I expected that the keys in my pairs would be hashed into the same bucket. For example:

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
  unordered_map<string, string> map;
  map.emplace("abc", "bca");
  map.emplace("abc", "bac");
  cout << map.bucket_size(map.bucket("abc")) << endl;
  cout << map.bucket_count() << endl;
  return 0;
}

My expectation here was that the output would be

2
1

However, it was

1
2

I understand that what was output is much more ideal than my expectation, and having as little chaining as possible is the goal, but for my purposes I want this chaining and collision to happen so that I can carry out the computations I need to for my program. Am I missing the step to accomplish this?


问:
How to run a search query on the youtube api, recieving error
I am writing my first React application, and I am having issues with the Youtube API. I have written a seperate Youtube search function like:

```<code>var searchYouTube = (options, callback) => {
  $.get('https://www.googleapis.com/youtube/v3/search', {
    key: window.YOUTUBE_API_KEY,
    q: options.query,
    maxResults: options.max,
  }).done(function(data) {
    console.log(data);
    callback(data);
  });
};

window.searchYouTube = searchYouTube;
</code>```

It is triggered every time there is a change in the search input. You can see this component in my app.jsx:

```<code>class App extends React.Component {
  constructor() {
    super();
    this.state = {
      videos: exampleVideoData,
      currentVideo: exampleVideoData[0]
    };
  }

  renderSearch(term) {
    console.log($(term.target).val());
    this.setState({
      videos: searchYouTube({query:$(term.target).val(),max:5})
    });
  }

  setVideo(video) {
    this.setState({
      currentVideo: video
    });
  }

  render() {
    return (
      <div>
        <nav className="navbar">
          <div className="col-md-6 offset-md-3">
            <div><Search renderSearch={this.renderSearch.bind(this)}/></div>
          </div>
        </nav>
        <div className="row">
          <div className="col-md-7">
            <div><VideoPlayer currentVideo={this.state.currentVideo}/></div>
          </div>
          <div className="col-md-5">
            <div><VideoList videos={this.state.videos} setVideo={this.setVideo.bind(this)}/></div>
          </div>
        </div>
      </div>
    );
  }
}

// In the ES6 spec, files are "modules" and do not share a top-level scope
// `var` declarations will only exist globally where explicitly defined
window.App = App;
</code>```

Finally, the error I get is:

```<code>    {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: part",
    "locationType": "parameter",
    "location": "part"
   }
  ],
  "code": 400,
  "message": "Required parameter: part"
 }
}
</code>```

Any suggestions on what I need to retool? I believe it the structure of the searchYoutube function. Maybe I am missing a parameter?

答:
The console log is clear :

```<code>"message": "Required parameter: part",
</code>```

Means you have to add part in your options. And I suggest to add the following:

```<code>var searchYouTube = (options, callback) => {
  $.get('https://www.googleapis.com/youtube/v3/search', {
    key: window.YOUTUBE_API_KEY,
    q: options.query,
    part: 'snippet', //  this one was missing
    maxResults: options.max,
  }).done(function(data) {
    console.log(data);
    callback(data);
  });
};
</code>```

It will work. Don't worry! and demo is below :

const { Component } = React;

class SearchBar extends Component {
  state = { term: '' };

  render() {
    return (

        <input
          value={this.state.term}
          onChange={event => this.onInputChange(event.target.value)}
        />

    );
  }

  onInputChange = term => {
    this.setState({ term });
    this.props.onSearchTermChange(term);
  };
}

const VideoDetail = ({ video }) => {
  if (!video) {
    return
Loading...
;
  }

  const videoId = video.id.videoId;
  const url = `https://www.youtube.com/embed/${videoId}`;

  return (

          {video.snippet.title}

          {video.snippet.description}

  );
};

const VideoListItem = ({ video, onVideoSelect }) => {
  const imageUrl = video.snippet.thumbnails.default.url;

  return (

 onVideoSelect(video)} className="list-group-item">

            {video.snippet.title}

  );
};

const VideoList = props => {
  const videoItems = props.videos.map(video => {
    return (
      <VideoListItem
        onVideoSelect={props.onVideoSelect}
        key={video.etag}
        video={video}
      />
    );
  });

  return (

      {videoItems}

  );
};

const InvalidApiKey = () => (
Sorry you do not give a valid YOUTUBE API key. Refresh the page or Run the snippet again and give a valid API key.
)

class App extends Component {
  state = {
    videos: [],
    selectedVideo: null,
    error: false
  };
  componentDidMount() {
    this.videoSearch('Sport');
  }

  searchYouTube(options, callback) {
    $.get('https://www.googleapis.com/youtube/v3/search', {
      key: this.props.youtubeApiKey,
      q: options.query,
      part: 'snippet',
      maxResults: options.max
    }).done(function(data) {
      callback(data);
    }).fail(() => this.setState({error: true}))
  }
  videoSearch = (term) => {
    this.searchYouTube({ key: this.props.youtubeApiKey, term: term }, data => {
      this.setState({
        videos: data.items,
        selectedVideo: data.items[1]
      });
    });
  }

  render() {
    // const videoSearch = _.debounce(term => {
    //   this.videoSearch(term);
    // }, 300);
    if (this.state.error) return  <InvalidApiKey />

    return (

        <SearchBar onSearchTermChange={this.videoSearch} />
        <VideoDetail video={this.state.selectedVideo} />
        <VideoList
          onVideoSelect={selectedVideo => this.setState({ selectedVideo })}
          videos={this.state.videos}
        />

    );
  }
}

const youtubeApiKey = prompt(
  'Give a valid YOUTUBE API KEY and everything should work: '
);

ReactDOM.render(
  youtubeApiKey
    ? <App youtubeApiKey={youtubeApiKey} />
    : <InvalidApiKey />,
  document.querySelector('#app')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.search-bar {
  margin: 20px;
  text-align: center;
}

.search-bar input {
  width: 75%;
}

.video-item img {
  max-width: 64px;
}

.video-detail .details {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.list-group-item {
  cursor: pointer;
}

.list-group-item:hover {
  background-color: #eee;
}</code>```

```

Body:
I am writing my first React application, and I am having issues with the Youtube API. I have written a seperate Youtube search function like:

var searchYouTube = (options, callback) => {
  $.get('https://www.googleapis.com/youtube/v3/search', {
    key: window.YOUTUBE_API_KEY,
    q: options.query,
    maxResults: options.max,
  }).done(function(data) {
    console.log(data);
    callback(data);
  });
};

window.searchYouTube = searchYouTube;

It is triggered every time there is a change in the search input. You can see this component in my app.jsx:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      videos: exampleVideoData,
      currentVideo: exampleVideoData[0]
    };
  }

  renderSearch(term) {
    console.log($(term.target).val());
    this.setState({
      videos: searchYouTube({query:$(term.target).val(),max:5})
    });
  }

  setVideo(video) {
    this.setState({
      currentVideo: video
    });
  }

  render() {
    return (

<Search renderSearch={this.renderSearch.bind(this)}/>

<VideoPlayer currentVideo={this.state.currentVideo}/>

<VideoList videos={this.state.videos} setVideo={this.setVideo.bind(this)}/>

    );
  }
}

// In the ES6 spec, files are "modules" and do not share a top-level scope
// `var` declarations will only exist globally where explicitly defined
window.App = App;

Finally, the error I get is:

    {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: part",
    "locationType": "parameter",
    "location": "part"
   }
  ],
  "code": 400,
  "message": "Required parameter: part"
 }
}

Any suggestions on what I need to retool? I believe it the structure of the searchYoutube function. Maybe I am missing a parameter?

Body:
The console log is clear :

"message": "Required parameter: part",

Means you have to add part in your options. And I suggest to add the following:

var searchYouTube = (options, callback) => {
  $.get('https://www.googleapis.com/youtube/v3/search', {
    key: window.YOUTUBE_API_KEY,
    q: options.query,
    part: 'snippet', //  this one was missing
    maxResults: options.max,
  }).done(function(data) {
    console.log(data);
    callback(data);
  });
};

It will work. Don't worry! and demo is below :

const { Component } = React;

class SearchBar extends Component {
  state = { term: '' };

  render() {
    return (
      <div className="search-bar">
        <input
          value={this.state.term}
          onChange={event => this.onInputChange(event.target.value)}
        />
      </div>
    );
  }

  onInputChange = term => {
    this.setState({ term });
    this.props.onSearchTermChange(term);
  };
}

const VideoDetail = ({ video }) => {
  if (!video) {
    return <div>Loading...</div>;
  }

  const videoId = video.id.videoId;
  const url = `https://www.youtube.com/embed/${videoId}`;

  return (
    <div className="video-detail col-md-8">
      <div className="embed-responsive embed-responsive-16by9">
        <iframe className="embed-responsive-item" src={url} />
      </div>
      <div className="details">
        <div>
          {video.snippet.title}
        </div>
        <div>
          {video.snippet.description}
        </div>
      </div>
    </div>
  );
};

const VideoListItem = ({ video, onVideoSelect }) => {
  const imageUrl = video.snippet.thumbnails.default.url;

  return (
    <li onClick={() => onVideoSelect(video)} className="list-group-item">
      <div className="video-list media">
        <div className="media-left">
          <img className="media-object" src={imageUrl} />
        </div>
        <div className="media-body">
          <div className="media-heading">
            {video.snippet.title}
          </div>
        </div>
      </div>
    </li>
  );
};

const VideoList = props => {
  const videoItems = props.videos.map(video => {
    return (
      <VideoListItem
        onVideoSelect={props.onVideoSelect}
        key={video.etag}
        video={video}
      />
    );
  });

  return (
    <ul className="col-md-4 list-group">
      {videoItems}
    </ul>
  );
};

const InvalidApiKey = () => (<h1>Sorry you do not give a valid YOUTUBE API key. Refresh the page or Run the snippet again and give a valid API key. </h1>)

class App extends Component {
  state = {
    videos: [],
    selectedVideo: null,
    error: false
  };
  componentDidMount() {
    this.videoSearch('Sport');
  }

  searchYouTube(options, callback) {
    $.get('https://www.googleapis.com/youtube/v3/search', {
      key: this.props.youtubeApiKey,
      q: options.query,
      part: 'snippet',
      maxResults: options.max
    }).done(function(data) {
      callback(data);
    }).fail(() => this.setState({error: true}))
  }
  videoSearch = (term) => {
    this.searchYouTube({ key: this.props.youtubeApiKey, term: term }, data => {
      this.setState({
        videos: data.items,
        selectedVideo: data.items[1]
      });
    });
  }

  render() {
    // const videoSearch = _.debounce(term => {
    //   this.videoSearch(term);
    // }, 300);
    if (this.state.error) return  <InvalidApiKey />

    return (
      <div>
        <SearchBar onSearchTermChange={this.videoSearch} />
        <VideoDetail video={this.state.selectedVideo} />
        <VideoList
          onVideoSelect={selectedVideo => this.setState({ selectedVideo })}
          videos={this.state.videos}
        />
      </div>
    );
  }
}

const youtubeApiKey = prompt(
  'Give a valid YOUTUBE API KEY and everything should work: '
);

ReactDOM.render(
  youtubeApiKey
    ? <App youtubeApiKey={youtubeApiKey} />
    : <InvalidApiKey />,
  document.querySelector('#app')
);

.search-bar {
  margin: 20px;
  text-align: center;
}

.search-bar input {
  width: 75%;
}

.video-item img {
  max-width: 64px;
}

.video-detail .details {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.list-group-item {
  cursor: pointer;
}

.list-group-item:hover {
  background-color: #eee;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app" />


问:
How to format the content of a Java Properties object when using a Stream?
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

```<code>        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);
</code>```

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

答:
If you would like to try a single statement, you may try:

```<code>    AtomicInteger len = new AtomicInteger();
    System.getProperties()
          .entrySet()
          .stream()
          .sorted((e1, e2) -> Integer.compare(e2.getKey().toString().length(), e1.getKey().toString().length()))
          .peek(e -> len.set(Math.max(len.get(), e.getKey().toString().length())))
          .map(e -> String.format("%-" + len.get() + "s: %s", e.getKey(), e.getValue()))
          .sorted()
          .forEach(System.out::println);
</code>```

It involves 2 sorts, so the elements will go through the peek to find the maximum length first.

It is not impossible to do so, but I do not recommended indeed, as an unnecessary sort is introduced.

Body:
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

Body:
If you would like to try a single statement, you may try:

    AtomicInteger len = new AtomicInteger();
    System.getProperties()
          .entrySet()
          .stream()
          .sorted((e1, e2) -> Integer.compare(e2.getKey().toString().length(), e1.getKey().toString().length()))
          .peek(e -> len.set(Math.max(len.get(), e.getKey().toString().length())))
          .map(e -> String.format("%-" + len.get() + "s: %s", e.getKey(), e.getValue()))
          .sorted()
          .forEach(System.out::println);

It involves 2 sorts, so the elements will go through the peek to find the maximum length first.

It is not impossible to do so, but I do not recommended indeed, as an unnecessary sort is introduced.


问:
Get input inside same
How can I get previous input inside the same ?

I have the following table:

```<code>start-loop
    <td>...</td>
    <td>...</td>
    <td align=center>
            <input type="hidden" id="ContactPW" name="ContactPW" value="#UserPW#" />
            <input type="hidden" id="ContactEmail" name="ContactEmail" value="#UserEmail#" />
            <input type="hidden" id="ContacName" name="ContactName" value="#UserName#" />
            <input class="btn btn-primary" type="button" onclick="test();" value="Login" />
    </td>
end- loop
</code>```

I would like to get in my test() function the values for "ContactPW", "ContactEmail", and "ContactName", but using $("#ContactPW").val() I just get the first item in the loop, not the row that I click the button.

Does anyone know how I can do it?

Thanks

答:
in your test function, you can use jquery .parent().find() which means, your btn elem will look for parent and find the child with the name that you define. function as sample below,

html

```<code><input class="btn btn-primary" type="button" onclick="test(this);" value="Login" />
</code>```

javascript

```<code>function test(e){
   $(e).parent().find("[name='ContactPW']").val();
}
</code>```

Title: Get input inside same <td>

Body:
How can I get previous input inside the same ?

I have the following table:

start-loop
    ...
    ...

            <input type="hidden" id="ContactPW" name="ContactPW" value="#UserPW#" />
            <input type="hidden" id="ContactEmail" name="ContactEmail" value="#UserEmail#" />
            <input type="hidden" id="ContacName" name="ContactName" value="#UserName#" />
            <input class="btn btn-primary" type="button" onclick="test();" value="Login" />

end- loop

I would like to get in my test() function the values for "ContactPW", "ContactEmail", and "ContactName", but using $("#ContactPW").val() I just get the first item in the loop, not the row that I click the button.

Does anyone know how I can do it?

Thanks

Body:
in your test function, you can use jquery .parent().find() which means, your btn elem will look for parent and find the child with the name that you define. function as sample below,

html

<input class="btn btn-primary" type="button" onclick="test(this);" value="Login" />

javascript

function test(e){
   $(e).parent().find("[name='ContactPW']").val();
}


问:
Stack exchange oauth response unreadable
Hello I am trying to set up an authorization oauth client based on Java and apache Oltu library for stack exchange api.

The response i received looks like this when printed in console
      u��n�0���"+���tU��l��*k��lۄ��{BԨM����s�h�W�#��ڇWj@ٹ�F*P�����������N��р���=ѹ�\k��

In browser the response is nicely printed in READABLE format. My problem is exactly similar as
Http request to stackexchange api returns unreadable json
but as the accepted answer suggests the response stream is gziped JSON. When I try to unzip the response my program says "Not in GZIP format" format. I tried following:
new GZIPInputStream(response)

If i convert the response to hex i get the following:

0x1FEFBFBD080000000000040075EFBFBDEFBFBD6EEFBFBD3010EFBFBD5FEFBFBDEFBFBD222B140CEFBFBDEFBFBDEFBFBD7455EFBFBDEFBFBD6CEFBFBDEFBFBD2A6BEFBFBD07EFBFBD156C13DB84EFBFBDEFBFBD7B0742D4A84DEFBFBDEFBFBDEFBFBDEFBFBD73EFBFBD68EFBFBD57EFBFBD23EFBFBDEFBFBDDA8757EFBFBD086A40D9B9EFBFBD462A50EFBFBDEFBFBDEFBFBDEFBFBDEFBFBD1216EFBFBDEFBFBDEFBFBDEFBFBDEFBFBD3C61EFBFBD1B1505D78441EFBFBDDF95EFBFBDEFBFBDCE8B2627EFBFBDEFBFBD4433EFBFBD6E45EFBFBDEFBFBD610CEFBFBDEFBFBD1142EFBFBDEFBFBD29EFBFBD6B545241EFBFBD44455EEFBFBD4DEFBFBD45797052EFBFBD10EFBFBD69C99B42E49C8BEFBFBD79EFBFBDEFBFBD08513B2BEFBFBD0B58EFBFBDEFBFBD22EFBFBDEFBFBDEFBFBD33EFBFBD3CEFBFBDEFBFBDEFBFBDEFBFBDEFBFBDEFBFBD71365EEFBFBD600BEFBFBDEFBFBD1748EFBFBDEFBFBD0F616DEFBFBDEFBFBDEFBFBDEFBFBDDBB5EFBFBD7321442EEFBFBD66EFBFBD3C07EFBFBD32EFBFBD13EFBFBDEFBFBD6BD0813CEFBFBD6207EFBFBD1756EFBFBDCDA9EFBFBDEFBFBD2DEFBFBD14EFBFBDEFBFBD35EFBFBD6D1BEFBFBD3B66EFBFBD1FEFBFBDEFBFBDEFBFBDEFBFBD1D7A0376EFBFBDEFBFBD515BEFBFBDEFBFBD2E314EEFBFBD4DEFBFBD10EFBFBD7B72EFBFBD30EFBFBDEFBFBDEFBFBDCE9974EFBFBD0FE9A1BD67474CCD9377EFBFBD1E516A03037E5059EFBFBDEFBFBD76EFBFBDEFBFBD0211EFBFBD2EEFBFBD16EFBFBD45EFBFBDEFBFBDEFBFBDEFBFBD2EEFBFBD38EFBFBD42EFBFBD05EFBFBD725E6156EFBFBDE9B1A8EFBFBDEFBFBD7B38677973EFBFBDEFBFBD5AEFBFBDEFBFBDEFBFBD73EFBFBDC69FEFBFBDEFBFBD68EFBFBDEFBFBD611A61EFBFBD16EFBFBD36E8A38DEFBFBDCF845D20EFBFBD4BEFBFBDEFBFBDEFBFBDEFBFBD797611EFBFBDEFBFBD5FEFBFBD164EEFBFBDEFBFBDD180EFBFBDEFBFBD0EEFBFBD3DD1B9EFBFBD015C1A6BEFBFBDEFBFBD020000

So my issue now is that I can not read the JSON directly and can not unzip it using GZIP. What can I do now to process the data? Any ideas ? Thank you for your time.

答:
You can try OkHttp. Here is an example works for me. It automatically solves that decompression problem for me.

```<code>    UriComponents uriComponents =
            UriComponentsBuilder.newInstance()
                    .scheme("https")
                    .host("api.stackexchange.com")
                    .path("/2.2/users")
                    .queryParam("order", "desc")
                    .queryParam("sort", "reputation")
                    .queryParam("inname", fullName)
                    .queryParam("site", "stackoverflow")
                    .build()
                    .encode();

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(uriComponents.toUriString())
            .get()
            .addHeader("cache-control", "no-cache")
            .build();

    Response response = client.newCall(request).execute();
    return new JSONObject(response.body().string());
</code>```

Maven dependency

```<code>    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>okhttp</artifactId>
        <version>2.7.5</version>
    </dependency>
</code>```

Body:
You can try OkHttp. Here is an example works for me. It automatically solves that decompression problem for me.

    UriComponents uriComponents =
            UriComponentsBuilder.newInstance()
                    .scheme("https")
                    .host("api.stackexchange.com")
                    .path("/2.2/users")
                    .queryParam("order", "desc")
                    .queryParam("sort", "reputation")
                    .queryParam("inname", fullName)
                    .queryParam("site", "stackoverflow")
                    .build()
                    .encode();

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(uriComponents.toUriString())
            .get()
            .addHeader("cache-control", "no-cache")
            .build();

    Response response = client.newCall(request).execute();
    return new JSONObject(response.body().string());

Maven dependency

    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>okhttp</artifactId>
        <version>2.7.5</version>
    </dependency>


问:
Getting unexpected semicolon error when using PlugNPay PHP Library
When I try to use the third-party PHP library for Plug N Pay (a credit card authorization library), I get the following error:

```<code>Parse error: syntax error, unexpected ';' in /authtest/PnP.php on line 391
</code>```

Line 391 reads:

```<code>    $http_query = str_replace("&", "&", (http_build_query( $post_args ) );
</code>```

Removing this line runs the script but obviously returns another error as $http_query is not set. I've replaced the default user/pass with my specific PnP user/pass, for what it's worth.

Googling turns up not much, and this server is running PHP5. Any ideas?

答:
Your are missing a closing ) before the ;  and/or have an unnecessary (,

depending on how you look at it.

```<code>$http_query = str_replace("&", "&", (http_build_query( $post_args ) );
</code>```

should be

```<code>$http_query = str_replace("&", "&", (http_build_query( $post_args ) ) );
</code>```

or even better

```<code>$http_query = str_replace("&", "&", http_build_query( $post_args ) );
</code>```

Body:
When I try to use the third-party PHP library for Plug N Pay (a credit card authorization library), I get the following error:

Parse error: syntax error, unexpected ';' in /authtest/PnP.php on line 391

Line 391 reads:

    $http_query = str_replace("&", "&", (http_build_query( $post_args ) );

Removing this line runs the script but obviously returns another error as $http_query is not set. I've replaced the default user/pass with my specific PnP user/pass, for what it's worth.

Googling turns up not much, and this server is running PHP5. Any ideas?

Body:
Your are missing a closing ) before the ;  and/or have an unnecessary (,

depending on how you look at it.

$http_query = str_replace("&amp;", "&", (http_build_query( $post_args ) );

should be

$http_query = str_replace("&amp;", "&", (http_build_query( $post_args ) ) );

or even better

$http_query = str_replace("&amp;", "&", http_build_query( $post_args ) );


答:
By creating your modules in different projects you create a more flexible solution.

You could even use different languages and technologies in a service in particular. E.g. one of your services could be NodeJS and the rest Java/Spring.

Title: Microservice project structure using Spring boot and Spring Cloud

Body:
I am trying to convert a normal monolithic web application into microservices structure using Spring Boot and Spring Cloud. I am actually trying to create Angular 2 front-end application and calls these my developed microservices in the cloud. And I am already started to break the modules into independent process's structure for microservice architecture.

Here my doubt is that, when designing the flow of control and microservice structure architecture, can I use only one single Spring Boot project using different controller for this entire web application back end process?

Somewhere I found that when I am reading develop all microservices using 2 different Spring Boot project. I am new to Spring and Spring Cloud. Is it possible to create all services in single project by using different modules?