问:
Selenium Webdriver Timeout Exception: Expected condition failed: waiting for frame to be available
It's a CRM application where I want to close two pop-ups which are displayed once user login. I have created a method for each pop-up where I am waiting for it's frame to detect and clicking on 'Close' icon to close the pop-up. Below is the code:    </p>

```<code>package base;

import java.awt.AWTException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class TC02_VerificationOfCustomerSearchPage extends
TC01_LoginToRClaimsCRM{

@Test(priority = 0)
public void PendingEmailPopUPClose() throws InterruptedException,
AWTException{
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));

//Close Pending Email pop-up.
driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/button")).click();
driver.switchTo().frame("InlineDialog1_Iframe");
}

@Test(priority = 1)
public void MSCRMPopUPClose() throws InterruptedException, AWTException {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));

//Close MSCRM pop-up.
driver.findElement(By.xpath(".//*[@id='buttonClose']/div/img")).click();

driver.switchTo().frame("InlineDialog_Iframe");
}

@Test(priority = 2)
public void HomePageVerification() throws InterruptedException, AWTException
{
driver.switchTo().defaultContent();

driver.findElement(By.cssSelector(".homeButtonImage")).click();

System.out.println("Home page is displayed.");

Thread.sleep(100);

System.out.println("Verification of Customer Search page UI.");

driver.switchTo().frame("contentIFrame0");

//Verification of Customer Search page UI.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Main Policy Holder tab.
if(driver.findElement(By.tagName("html")).getText().contains("Main Policy Holder")){
    System.out.println("Main Policy Holder tab is displayed.");
    }else{
    System.out.println("Main Policy Holder tab is not displayed.");
    }

//SEARCH CRITERIA label.
if(driver.findElement(By.tagName("html")).getText().contains("SEARCH
CRITERIA")){
    System.out.println("SEARCH CRITERIA label is displayed.");
    }else{
    System.out.println("SEARCH CRITERIA label is not displayed.");
    }

Thread.sleep(1000);

//MPH Name text field.
if(driver.findElement(By.cssSelector("#txtCustomerName")) != null){
    System.out.println("MPH Name text field is displayed.");
    }else{
    System.out.println("MPH Name text field is not displayed.");
    }

Thread.sleep(2000);

//MPH Number text field.
if(driver.findElement(By.cssSelector("#txtCustomerNumber")) != null){
    System.out.println("MPH Number text field is displayed.");
    }else{
    System.out.println("MPH Number text field is not displayed.");
    }

Thread.sleep(1000);

//MPH Policy Number.
if(driver.findElement(By.cssSelector("#txtPolicyNo")) != null){
    System.out.println("MPH Policy Number text field is displayed.");
    }else{
    System.out.println("MPH Policy Number text field is not displayed.");
    }

Thread.sleep(1000);

//SEARCH button.
if(driver.findElement(By.tagName("html")).getText().contains("SEARCH")) {
    System.out.println("SEARCH button displayed.");
    }else{
    System.out.println("SEARCH button is not displayed.");
    }

Thread.sleep(1000);

//RESET button.
if(driver.findElement(By.tagName("html")).getText().contains("RESET")) {
    System.out.println("RESET button displayed.");
    }else{
    System.out.println("RESET button is not displayed.");
    }

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Verification Successfull - Customer Search page UI.");
}
}
</code>```

答:
Below line is causing you trouble:

```<code>WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));
</code>```

The method frameToBeAvailableAndSwitchToIt does what it says. It waits until the frame is available and then, performs driver.switchTo().frame(); method.

You provided an xpath for a frame as html/body/div[10] which is 100% incorrect.
You should provide and xpath to iframe tag OR just use driver.switchTo().frame("InlineDialog1_Iframe");

If you need to wait until frame is available, make sure InlineDialog1_Iframe is an id or nameand provide it toframeToBeAvailableAndSwitchToIt` method like this:

```<code>WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@name='InlineDialog1_Iframe or @id='InlineDialog1_Iframe']")));
</code>```

Body:
It's a CRM application where I want to close two pop-ups which are displayed once user login. I have created a method for each pop-up where I am waiting for it's frame to detect and clicking on 'Close' icon to close the pop-up. Below is the code:

package base;

import java.awt.AWTException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class TC02_VerificationOfCustomerSearchPage extends
TC01_LoginToRClaimsCRM{

@Test(priority = 0)
public void PendingEmailPopUPClose() throws InterruptedException,
AWTException{
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));

//Close Pending Email pop-up.
driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/button")).click();
driver.switchTo().frame("InlineDialog1_Iframe");
}

@Test(priority = 1)
public void MSCRMPopUPClose() throws InterruptedException, AWTException {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));

//Close MSCRM pop-up.
driver.findElement(By.xpath(".//*[@id='buttonClose']/div/img")).click();

driver.switchTo().frame("InlineDialog_Iframe");
}

@Test(priority = 2)
public void HomePageVerification() throws InterruptedException, AWTException
{
driver.switchTo().defaultContent();

driver.findElement(By.cssSelector(".homeButtonImage")).click();

System.out.println("Home page is displayed.");

Thread.sleep(100);

System.out.println("Verification of Customer Search page UI.");

driver.switchTo().frame("contentIFrame0");

//Verification of Customer Search page UI.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Main Policy Holder tab.
if(driver.findElement(By.tagName("html")).getText().contains("Main Policy Holder")){
    System.out.println("Main Policy Holder tab is displayed.");
    }else{
    System.out.println("Main Policy Holder tab is not displayed.");
    }

//SEARCH CRITERIA label.
if(driver.findElement(By.tagName("html")).getText().contains("SEARCH
CRITERIA")){
    System.out.println("SEARCH CRITERIA label is displayed.");
    }else{
    System.out.println("SEARCH CRITERIA label is not displayed.");
    }

Thread.sleep(1000);

//MPH Name text field.
if(driver.findElement(By.cssSelector("#txtCustomerName")) != null){
    System.out.println("MPH Name text field is displayed.");
    }else{
    System.out.println("MPH Name text field is not displayed.");
    }

Thread.sleep(2000);

//MPH Number text field.
if(driver.findElement(By.cssSelector("#txtCustomerNumber")) != null){
    System.out.println("MPH Number text field is displayed.");
    }else{
    System.out.println("MPH Number text field is not displayed.");
    }

Thread.sleep(1000);

//MPH Policy Number.
if(driver.findElement(By.cssSelector("#txtPolicyNo")) != null){
    System.out.println("MPH Policy Number text field is displayed.");
    }else{
    System.out.println("MPH Policy Number text field is not displayed.");
    }

Thread.sleep(1000);

//SEARCH button.
if(driver.findElement(By.tagName("html")).getText().contains("SEARCH")) {
    System.out.println("SEARCH button displayed.");
    }else{
    System.out.println("SEARCH button is not displayed.");
    }

Thread.sleep(1000);

//RESET button.
if(driver.findElement(By.tagName("html")).getText().contains("RESET")) {
    System.out.println("RESET button displayed.");
    }else{
    System.out.println("RESET button is not displayed.");
    }

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Verification Successfull - Customer Search page UI.");
}
}

Body:
Below line is causing you trouble:

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("html/body/div[10]")));

The method frameToBeAvailableAndSwitchToIt does what it says. It waits until the frame is available and then, performs driver.switchTo().frame(); method.

You provided an xpath for a frame as html/body/div[10] which is 100% incorrect.
You should provide and xpath to iframe tag OR just use driver.switchTo().frame("InlineDialog1_Iframe");

If you need to wait until frame is available, make sure InlineDialog1_Iframe is an id or nameand provide it toframeToBeAvailableAndSwitchToIt` method like this:

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@name='InlineDialog1_Iframe or @id='InlineDialog1_Iframe']")));


来源: stackexchange

问:
Zebra Stripe using CSS
I am trying to achieve the below stripe pattern, but none of the nth-child combination is working out. Any suggestion / solution to achieve this.

答:
You can do this using nth-of-type with n parameter (4n+1 and 4n+4)

.container div {
    color: #fff;
    float: left;
    width: 50%;
    background-color: blue;
}

.container div:nth-of-type(4n + 1),
.container div:nth-of-type(4n + 4) {
    background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Zebra Stripe using CSS

Body:
You can do this using nth-of-type with n parameter (4n+1 and 4n+4)

.container div {
    color: #fff;
    float: left;
    width: 50%;
    background-color: blue;
}

.container div:nth-of-type(4n + 1),
.container div:nth-of-type(4n + 4) {
    background-color: green;
}

<div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
</div>


问:
How to save an object to be re-used in Django Rest Framework Serializer Method Fields?
The situation is as follows:

2 fields in my serializer uses the Serializer Method Field function to get their respective content.

In each of these fields, I am calling the same, exact function to generate the content.

Kinda like this:

```<code>class ProductSerializer(serializers.ModelSerializer):
    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2
</code>```

As you can see, both the methods is calling the same function, with the same argument and therefore getting the exact same result. The generate_content function is very large, so I feel it would be best if I could save the content once, and use that to generate the two fields. How can I pull this off? Thanks!

答:
you can simply put the generated content within a variable, when generate_content is called check if that variable exists or not:

```<code>class ProductSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(ProductSerializer, self).__init__(*args, **kwargs)
        self.generated_content = None

    def generate_content(self, obj):
       if self.genretated_content:
           return self.genretated_content
       self.genretated_conten = 1 # gernerate here
       return self.genretated_content

    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2
</code>```

Body:
The situation is as follows:

2 fields in my serializer uses the Serializer Method Field function to get their respective content.

In each of these fields, I am calling the same, exact function to generate the content.

Kinda like this:

class ProductSerializer(serializers.ModelSerializer):
    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2

As you can see, both the methods is calling the same function, with the same argument and therefore getting the exact same result. The generate_content function is very large, so I feel it would be best if I could save the content once, and use that to generate the two fields. How can I pull this off? Thanks!

Body:
you can simply put the generated content within a variable, when generate_content is called check if that variable exists or not:

class ProductSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(ProductSerializer, self).__init__(*args, **kwargs)
        self.generated_content = None

    def generate_content(self, obj):
       if self.genretated_content:
           return self.genretated_content
       self.genretated_conten = 1 # gernerate here
       return self.genretated_content

    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2


问:
Refactoring in Vim
Of course the fact that you can refactor on IDEs is priceless for many, I hardly ever do it when I am coding but I may try to do it when editing some one else's source. How do you accomplish such a trivial task across multiple files in Vim?

I found this plugin for refactoring Ruby, but how about "any" language?

答:
Plugin YouCompleteMe (YCM) (20k stars on github)

http://ycm-core.github.io/YouCompleteMe/#the-refactorrename-new-name-subcommand

:h RefactorRename-new-name

In supported file types, this command attempts to perform a semantic
  rename of the identifier under the cursor. This includes renaming
  declarations, definitions and usages of the identifier, or any other
  language-appropriate action. The specific behavior is defined by the
  semantic engine in use.

Similar to FixIt, this command applies automatic modifications to your
  source files. Rename operations may involve changes to multiple files,
  which may or may not be open in Vim buffers at the time. YouCompleteMe
  handles all of this for you. The behavior is described in the
  following section.

Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript,
  typescript, rust, cs

By default there is no mapping.

Title: Refactoring in Vim

ContentLicense: CC BY-SA 4.0


问:
Logic Apps error "structural error in/before the first functional group"
I am reading an X12 850 from an Azure Queue and seek to get the XML representation of it, decoded by Logic Apps. Here is the sample EDI doc that I am using:

```<code>ISA*00*          *00*          *12*TEST123ZZZ     *12*ZZZ123TEST     *171010*0705*U*00401*000032485*0*P*>~
GS*PO*TEST123ZZZ*ZZZ123TEST*20171010*070547*32485*X*004010~
ST*850*32485~
BEG*00*SA*Z-5000**20171010~
REF*PG*LLL~
DTM*002*20171113~
N1*ST*SUPERLATIVE AUTO PARTS INC.*92*4500~
N3*5555 33 MILE RD.~
N4*ARMADA*MI*48005~
PO1*1*10*EA*2.27**BP*P2224*VP*L033~
PO1*2*10*EA*5.53**BP*P5544*VP*L059~
PO1*3*10*EA*4.11**BP*P1237*VP*L020~
PO1*4*20*EA*16.3**BP*P0999*VP*L006~
CTT*4*50~
SE*13*32485~
GE*1*32485~
IEA*1*000032485~
</code>```

Out of Decode, I am getting nothing in goodMessages, instead all in badMessages. It looks to me like my Agreement is being picked up and used (the only Agreement I have set up), but I am at a loss at how to respond to the exception "The interchange with id 000032485, with sender id 'TEST123ZZZ     ', receiver id 'ZZZ123TEST     ' had structural error in/before the first functional group"

```<code>"body": {
    "interchangeControlNumber": "000032485",
    "groupControlNumbers": [],
    "goodMessages": [],
    "badMessages": [
        {
            "interchangeEnvelope": {
                "ISA_Segment": "ISA*00*          *00*          *12*TEST123ZZZ     *12*ZZZ123TEST     *171010*0705*U*00401*000032485*0*P*>~\r\n",
                "isA05": "12",
                "isA06": "TEST123ZZZ     ",
                "isA07": "12",
                "isA08": "ZZZ123TEST     ",
                "isA09": "171010",
                "isA10": "0705",
                "isA11": "U",
                "isA12": "00401",
                "isA13": "000032485",
                "isA14": "0",
                "isA15": "P"
            },
            "technicalAckExpected": false,
            "functionalAckExpected": false,
            "exception": "The interchange with id '000032485', with sender id TEST123ZZZ      , receiver id ZZZ123TEST       had structural error in/before the first functional group",
            "componentSeparator": 62,
            "dataElementSeparator": 42,
            "interchangeControlNumber": "000032485",
            "payload": "77u/R1MgKiBQTyAqIFRFU1QxMjNaWlogKiBaWloxMjNURVNUICogMjAxNzEwMTAgKiAwNzA1NDcgKiAzMjQ4NSAqIFggKiAwMDQwMTB+DQpTVCAqIDg1MCAqIDMyNDg1fg0KQkVHICogMDAgKiBTQSAqIFogLSA1MDAwICogKjIwMTcxMDEwfg0KUkVGICogUEcgKiBMTEx+DQpEVE0gKiAwMDIgKiAyMDE3MTExM34NCk4xICogU1QgKiBTVVBFUkxBVElWRSBBVVRPIFBBUlRTIElOQy4qIDkyICogNDUwMH4NCk4zICogNTU1NSAzMyBNSUxFIFJELn4NCk40ICogQVJNQURBICogTUkgKiA0ODAwNX4NClBPMSAqIDEgKiAxMCAqIEVBICogMi4yNyAqICpCUCAqIFAyMjI0ICogVlAgKiBMMDMzfg0KUE8xICogMiAqIDEwICogRUEgKiA1LjUzICogKkJQICogUDU1NDQgKiBWUCAqIEwwNTl+DQpQTzEgKiAzICogMTAgKiBFQSAqIDQuMTEgKiAqQlAgKiBQMTIzNyAqIFZQICogTDAyMH4NClBPMSAqIDQgKiAyMCAqIEVBICogMTYuMyAqICpCUCAqIFAwOTk5ICogVlAgKiBMMDA2fg0KQ1RUICogNCAqIDUwfg0KU0UgKiAxMyAqIDMyNDg1fg0KR0UgKiAxICogMzI0ODV+DQpJRUEgKiAxICogMDAwMDMyNDg1fg==",
            "replacementCharacter": 0,
            "segmentTerminator": 126,
            "segmentTerminatorSuffix": "CRLF",
            "agreementName": "X12-TEST123ZZZ-ZZZ123TEST",
            "guestPartnerName": "Test-Partner",
            "hostPartnerName": "Plex-As-Host",
            "ReceiverIdentifier": "ZZZ123TEST",
            "receiverQualifier": "12",
            "SenderIdentifier": "TEST123ZZZ",
            "senderQualifier": "12"
        }
    ],
    "generatedAcks": [],
    "receivedAcks": [],
    "agreementName": "X12-TEST123ZZZ-ZZZ123TEST",
    "guestPartnerName": "Test-Partner",
    "hostPartnerName": "Plex-As-Host",
    "ReceiverIdentifier": "ZZZ123TEST",
    "receiverQualifier": "12",
    "SenderIdentifier": "TEST123ZZZ",
    "senderQualifier": "12"
}
</code>```

}

I am getting told by my EDI colleagues that "ISA02 should be 10 spaces
The total length of the ISA segment should be 106 characters" So, I am thinking I don't have the Agreement configured correctly for ISA2. Should I be putting something in the ISA2 field in the Agreement? I tried ten spaces, which it took, but I still get the same error: "The interchange with id 000032485, with sender id TEST123ZZZ, receiver id ZZZ123TEST had structural error in/before the first functional group"

答:
You ISA Segment looks fine, structurally.  ISA02/04 are most often left blank.

But looking at the other content, is there a space after all the ~'s?  That would cause problems.  Only CR and/or LF are allowed as suffex's.

Body:
I am reading an X12 850 from an Azure Queue and seek to get the XML representation of it, decoded by Logic Apps. Here is the sample EDI doc that I am using:

ISA*00*          *00*          *12*TEST123ZZZ     *12*ZZZ123TEST     *171010*0705*U*00401*000032485*0*P*>~
GS*PO*TEST123ZZZ*ZZZ123TEST*20171010*070547*32485*X*004010~
ST*850*32485~
BEG*00*SA*Z-5000**20171010~
REF*PG*LLL~
DTM*002*20171113~
N1*ST*SUPERLATIVE AUTO PARTS INC.*92*4500~
N3*5555 33 MILE RD.~
N4*ARMADA*MI*48005~
PO1*1*10*EA*2.27**BP*P2224*VP*L033~
PO1*2*10*EA*5.53**BP*P5544*VP*L059~
PO1*3*10*EA*4.11**BP*P1237*VP*L020~
PO1*4*20*EA*16.3**BP*P0999*VP*L006~
CTT*4*50~
SE*13*32485~
GE*1*32485~
IEA*1*000032485~

Out of Decode, I am getting nothing in goodMessages, instead all in badMessages. It looks to me like my Agreement is being picked up and used (the only Agreement I have set up), but I am at a loss at how to respond to the exception "The interchange with id 000032485, with sender id 'TEST123ZZZ     ', receiver id 'ZZZ123TEST     ' had structural error in/before the first functional group"

"body": {
    "interchangeControlNumber": "000032485",
    "groupControlNumbers": [],
    "goodMessages": [],
    "badMessages": [
        {
            "interchangeEnvelope": {
                "ISA_Segment": "ISA*00*          *00*          *12*TEST123ZZZ     *12*ZZZ123TEST     *171010*0705*U*00401*000032485*0*P*>~\r\n",
                "isA05": "12",
                "isA06": "TEST123ZZZ     ",
                "isA07": "12",
                "isA08": "ZZZ123TEST     ",
                "isA09": "171010",
                "isA10": "0705",
                "isA11": "U",
                "isA12": "00401",
                "isA13": "000032485",
                "isA14": "0",
                "isA15": "P"
            },
            "technicalAckExpected": false,
            "functionalAckExpected": false,
            "exception": "The interchange with id '000032485', with sender id TEST123ZZZ      , receiver id ZZZ123TEST       had structural error in/before the first functional group",
            "componentSeparator": 62,
            "dataElementSeparator": 42,
            "interchangeControlNumber": "000032485",
            "payload": "77u/R1MgKiBQTyAqIFRFU1QxMjNaWlogKiBaWloxMjNURVNUICogMjAxNzEwMTAgKiAwNzA1NDcgKiAzMjQ4NSAqIFggKiAwMDQwMTB+DQpTVCAqIDg1MCAqIDMyNDg1fg0KQkVHICogMDAgKiBTQSAqIFogLSA1MDAwICogKjIwMTcxMDEwfg0KUkVGICogUEcgKiBMTEx+DQpEVE0gKiAwMDIgKiAyMDE3MTExM34NCk4xICogU1QgKiBTVVBFUkxBVElWRSBBVVRPIFBBUlRTIElOQy4qIDkyICogNDUwMH4NCk4zICogNTU1NSAzMyBNSUxFIFJELn4NCk40ICogQVJNQURBICogTUkgKiA0ODAwNX4NClBPMSAqIDEgKiAxMCAqIEVBICogMi4yNyAqICpCUCAqIFAyMjI0ICogVlAgKiBMMDMzfg0KUE8xICogMiAqIDEwICogRUEgKiA1LjUzICogKkJQICogUDU1NDQgKiBWUCAqIEwwNTl+DQpQTzEgKiAzICogMTAgKiBFQSAqIDQuMTEgKiAqQlAgKiBQMTIzNyAqIFZQICogTDAyMH4NClBPMSAqIDQgKiAyMCAqIEVBICogMTYuMyAqICpCUCAqIFAwOTk5ICogVlAgKiBMMDA2fg0KQ1RUICogNCAqIDUwfg0KU0UgKiAxMyAqIDMyNDg1fg0KR0UgKiAxICogMzI0ODV+DQpJRUEgKiAxICogMDAwMDMyNDg1fg==",
            "replacementCharacter": 0,
            "segmentTerminator": 126,
            "segmentTerminatorSuffix": "CRLF",
            "agreementName": "X12-TEST123ZZZ-ZZZ123TEST",
            "guestPartnerName": "Test-Partner",
            "hostPartnerName": "Plex-As-Host",
            "ReceiverIdentifier": "ZZZ123TEST",
            "receiverQualifier": "12",
            "SenderIdentifier": "TEST123ZZZ",
            "senderQualifier": "12"
        }
    ],
    "generatedAcks": [],
    "receivedAcks": [],
    "agreementName": "X12-TEST123ZZZ-ZZZ123TEST",
    "guestPartnerName": "Test-Partner",
    "hostPartnerName": "Plex-As-Host",
    "ReceiverIdentifier": "ZZZ123TEST",
    "receiverQualifier": "12",
    "SenderIdentifier": "TEST123ZZZ",
    "senderQualifier": "12"
}

}

I am getting told by my EDI colleagues that "ISA02 should be 10 spaces
The total length of the ISA segment should be 106 characters" So, I am thinking I don't have the Agreement configured correctly for ISA2. Should I be putting something in the ISA2 field in the Agreement? I tried ten spaces, which it took, but I still get the same error: "The interchange with id 000032485, with sender id TEST123ZZZ, receiver id ZZZ123TEST had structural error in/before the first functional group"


问:
Task status not changing to Cancelled when in the middle of execution
I was reading a book on Parallel Programming and I coded the following scenario which worked as expected (Task.Status == TaskStatus.Canceled):

It’s possible for a task to end in TaskStatus.Canceled. For this
  to occur, you must pass a CancellationToken as an argument to the
  factory method that created the task. If that token signals a request
  for cancellation before the task begins to execute, the task won’t be
  allowed to run. The task’s Status property will transition directly to
  TaskStatus.Canceled without ever invoking the task’s user delegate.

But I couldn't get expected result (Task.Status != TaskStatus.Canceled) for the following:

If the token signals a cancellation request after the task begins to
  execute, the task’s Status property will only transition to
  TaskStatus.Canceled if the user delegate throws an Operation
  CanceledException and that exception’s CancellationToken property
  contains the token that was given when the task was created.

Code

```<code>  public void DoWork(int millisec, CancellationToken token, int n )
    {
        ParallelOptions option = new ParallelOptions { CancellationToken = token };

        Parallel.For(0, n, option, (i) =>
        {
           // Thread.Sleep(millisec);
            token.ThrowIfCancellationRequested();
        });
    }

private void btnSearch_Click(object sender, EventArgs e)
{
   CancellationToken token = cts.Token;

   t1 = Task.Factory.StartNew(() => DoWork(700, token, 99999999), token);
   t2 = Task.Factory.StartNew(() => DoWork(5, token, 1), token);

   Task[] tasks = new Task[] { t1,t2 };

   int completedTaskIndex = Task.WaitAny(tasks);
   lblMsg.Text = "Task No." + ++completedTaskIndex + " has been completed.\n";

   cts.Cancel();
        Thread.Sleep(5000); // Updated
   lblMsg.Text += "Rest of the tasks have been cancelled.\n";

   try
   {
       lblMsg.Text += "Task 1 Status: " + t1.Status + "\n";
       lblMsg.Text += "Task 2 Status: " + t2.Status + "\n";

       Task.WaitAll(tasks);
       lblMsg.Text += "No exceptions has been reported yet.\n";
   }
   catch(AggregateException ae)
   {

           ae.Flatten().Handle((ex) =>
           {
          // if you debug to see the token handle it is the same as passed to Task.Factory.StartNew()
               if (ex is OperationCanceledException)
           {
               CancellationToken tok = ((OperationCanceledException)ex).CancellationToken;
               return true;
           }
           else
           {
               return false;
           }
       }
       );
   }
   finally
   {
     if(cts!= null)
         cts.Dispose();

     cts = null;
   }
}
</code>```

Result

Before Update:

After Update:

Dicussion

Task 1 is the task which is cancelled so its Status should have been Cancelled instead of Running as shown in figure above.

Question

Is there any understanding gap that I could not get desired result? Where did i lose the track?

Updated (Issue Resolved)

The problem was that I was reading the status of task 1 before it was updated to Cancelled. So I wrote Thread.Sleep(5000); just after cts.Cancel(); so that there's enough time for the task to be cancelled and the status be updated appropriately. That let the status of task 1 to show "Cancelled".

答:
Taking a look at the program flow, in comments, assuming it takes 1ms to process each line:

```<code>   int completedTaskIndex = Task.WaitAny(tasks); //Time T=0
   lblMsg.Text = "Task No." + ++completedTaskIndex + " has been completed.\n"; //time T=5, because we waited 5ms for task 2, right?

   cts.Cancel(); //Time T=6, task 1 is sleeping for another 694 ms
   lblMsg.Text += "Rest of the tasks have been cancelled.\n"; //Time T=7

   try
   {
       lblMsg.Text += "Task 1 Status: " + t1.Status + "\n";//Time T = 8, task1 is sleeping for another 692 ms, current status is "running"
       lblMsg.Text += "Task 2 Status: " + t2.Status + "\n";//Time T=9

       Task.WaitAll(tasks);//Time T=701, task 1 has finished sleeping, and finds out it is cancelled
       lblMsg.Text += "No exceptions has been reported yet.\n";//we probably don't hit this line/see it in label, because cancellation exception is thrown by task 1
   }
   catch(AggregateException ae) //what's task1's status now?
</code>```

Ultimately I think this is one fo those cases where if you'd jsut coded up the real world task, the UI that has a "go" button that changes to "cancel" before you start your thousand db queries or whatever, then things would have worked out.. but this artificial test you've arranged isn't really representative of the real life cancellation scenario

Body:
I was reading a book on Parallel Programming and I coded the following scenario which worked as expected (Task.Status == TaskStatus.Canceled):

It’s possible for a task to end in TaskStatus.Canceled. For this
  to occur, you must pass a CancellationToken as an argument to the
  factory method that created the task. If that token signals a request
  for cancellation before the task begins to execute, the task won’t be
  allowed to run. The task’s Status property will transition directly to
  TaskStatus.Canceled without ever invoking the task’s user delegate.

But I couldn't get expected result (Task.Status != TaskStatus.Canceled) for the following:

If the token signals a cancellation request after the task begins to
  execute, the task’s Status property will only transition to
  TaskStatus.Canceled if the user delegate throws an Operation
  CanceledException and that exception’s CancellationToken property
  contains the token that was given when the task was created.

Code

  public void DoWork(int millisec, CancellationToken token, int n )
    {
        ParallelOptions option = new ParallelOptions { CancellationToken = token };

        Parallel.For(0, n, option, (i) =>
        {
           // Thread.Sleep(millisec);
            token.ThrowIfCancellationRequested();
        });
    }

private void btnSearch_Click(object sender, EventArgs e)
{
   CancellationToken token = cts.Token;

   t1 = Task.Factory.StartNew(() => DoWork(700, token, 99999999), token);
   t2 = Task.Factory.StartNew(() => DoWork(5, token, 1), token);

   Task[] tasks = new Task[] { t1,t2 };

   int completedTaskIndex = Task.WaitAny(tasks);
   lblMsg.Text = "Task No." + ++completedTaskIndex + " has been completed.\n";

   cts.Cancel();
        Thread.Sleep(5000); // Updated
   lblMsg.Text += "Rest of the tasks have been cancelled.\n";

   try
   {
       lblMsg.Text += "Task 1 Status: " + t1.Status + "\n";
       lblMsg.Text += "Task 2 Status: " + t2.Status + "\n";

       Task.WaitAll(tasks);
       lblMsg.Text += "No exceptions has been reported yet.\n";
   }
   catch(AggregateException ae)
   {

           ae.Flatten().Handle((ex) =>
           {
          // if you debug to see the token handle it is the same as passed to Task.Factory.StartNew()
               if (ex is OperationCanceledException)
           {
               CancellationToken tok = ((OperationCanceledException)ex).CancellationToken;
               return true;
           }
           else
           {
               return false;
           }
       }
       );
   }
   finally
   {
     if(cts!= null)
         cts.Dispose();

     cts = null;
   }
}

Result

Before Update:

After Update:

Dicussion

Task 1 is the task which is cancelled so its Status should have been Cancelled instead of Running as shown in figure above.

Question

Is there any understanding gap that I could not get desired result? Where did i lose the track?

Updated (Issue Resolved)

The problem was that I was reading the status of task 1 before it was updated to Cancelled. So I wrote Thread.Sleep(5000); just after cts.Cancel(); so that there's enough time for the task to be cancelled and the status be updated appropriately. That let the status of task 1 to show "Cancelled".

Body:
Taking a look at the program flow, in comments, assuming it takes 1ms to process each line:

   int completedTaskIndex = Task.WaitAny(tasks); //Time T=0
   lblMsg.Text = "Task No." + ++completedTaskIndex + " has been completed.\n"; //time T=5, because we waited 5ms for task 2, right?

   cts.Cancel(); //Time T=6, task 1 is sleeping for another 694 ms
   lblMsg.Text += "Rest of the tasks have been cancelled.\n"; //Time T=7

   try
   {
       lblMsg.Text += "Task 1 Status: " + t1.Status + "\n";//Time T = 8, task1 is sleeping for another 692 ms, current status is "running"
       lblMsg.Text += "Task 2 Status: " + t2.Status + "\n";//Time T=9

       Task.WaitAll(tasks);//Time T=701, task 1 has finished sleeping, and finds out it is cancelled
       lblMsg.Text += "No exceptions has been reported yet.\n";//we probably don't hit this line/see it in label, because cancellation exception is thrown by task 1
   }
   catch(AggregateException ae) //what's task1's status now?

Ultimately I think this is one fo those cases where if you'd jsut coded up the real world task, the UI that has a "go" button that changes to "cancel" before you start your thousand db queries or whatever, then things would have worked out.. but this artificial test you've arranged isn't really representative of the real life cancellation scenario


问:
Spring XML databinding not in Controller
I want to move the Validation Logic from the Spring Controller to a ServletFilter and I would like to implement DataBinding in the ServletFilter so I can get automatic parsing of my XML data into my POJO and I can use BindingResult object in my filter.

Is that possible or I can take advantage of DataBinding and BindingResult only into my Controller?

Anyway, this is my controller's request mapping now:

```<code>@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value="Verifica Ordine")
public Object listaVerificaOrdine(@Valid @RequestBody VerificaOrdineRequestModel requestModel, BindingResult result) throws RemoteException{
  if(result.hasErrors()){
    return "Errori: " + result.toString();
  }
  ...
}
</code>```

答:
It's possible to use Databinding and JSR-303 Validation outside the Controller by using the same libraries that our Spring Controller is using (but in the Controller they result "hidden" behind the Spring Framework). In particular:

for databinding from XML I use JAXB library

for JSR-303 validation I use javax.validation library.

Let's see how to di that:

```<code>try {
        Object model = JAXB.unmarshal(new StringReader(xmlString), classe);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(model);

        for(ConstraintViolation violation : violations){
            responseError.append("Errore al percorso '" + violation.getPropertyPath() +"': ");
            responseError.append(" il valore trovato e' '" + violation.getInvalidValue() + "' ");
            responseError.append(", mentre il valore atteso deve rispettare il seguente criterio: '" + violation.getMessage() + "'. \n\n");
        }
    } catch (Exception e) {
        responseError.append("Eccezione nel parsing dell'oggetto: " + e.toString() + ". Probabilmente il file XML di input non e' ben formato. Controllare i tag di apertura e di chiusura.  \n\n");
    }
</code>```

Body:
I want to move the Validation Logic from the Spring Controller to a ServletFilter and I would like to implement DataBinding in the ServletFilter so I can get automatic parsing of my XML data into my POJO and I can use BindingResult object in my filter.

Is that possible or I can take advantage of DataBinding and BindingResult only into my Controller?

Anyway, this is my controller's request mapping now:

@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value="Verifica Ordine")
public Object listaVerificaOrdine(@Valid @RequestBody VerificaOrdineRequestModel requestModel, BindingResult result) throws RemoteException{
  if(result.hasErrors()){
    return "Errori: " + result.toString();
  }
  ...
}

Body:
It's possible to use Databinding and JSR-303 Validation outside the Controller by using the same libraries that our Spring Controller is using (but in the Controller they result "hidden" behind the Spring Framework). In particular:

for databinding from XML I use JAXB library

for JSR-303 validation I use javax.validation library.

Let's see how to di that:

try {
        Object model = JAXB.unmarshal(new StringReader(xmlString), classe);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(model);

        for(ConstraintViolation violation : violations){
            responseError.append("Errore al percorso '" + violation.getPropertyPath() +"': ");
            responseError.append(" il valore trovato e' '" + violation.getInvalidValue() + "' ");
            responseError.append(", mentre il valore atteso deve rispettare il seguente criterio: '" + violation.getMessage() + "'. \n\n");
        }
    } catch (Exception e) {
        responseError.append("Eccezione nel parsing dell'oggetto: " + e.toString() + ". Probabilmente il file XML di input non e' ben formato. Controllare i tag di apertura e di chiusura.  \n\n");
    }


问:
Delete Column with JavaScript shorter way
Hi there can someone please help me with this, I have this code:

```<code> $(document).on('click', 'button[id=delete_column]', function () {

    if (col_number > 1) {
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      --col_number;
        }
     });
</code>```

I need to delete the entire column and this ways it works how can I simplify this code not to repeat so many times, I tried something like this:

```<code>  $(document).on('click', 'button[id=delete_column]', function () {
      for (i = 0; i < 4; i++) {
        console.log(i);
    if (col_number > 1) {
      $('#column' + col_number[i]).remove();

    }
      --col_number;
        }
     });

});
</code>```

But does not work..

答:
Try Below Code :</p>

```<code>$(document).on('click', 'button[id=delete_column]', function () {
    if (col_number > 1) {
    for (var i=0; i<col_number; i++) {
         $('#column' + i).remove();
    };
  }
});
</code>```

Body:
Hi there can someone please help me with this, I have this code:

 $(document).on('click', 'button[id=delete_column]', function () {

    if (col_number > 1) {
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      $('#column' + col_number).remove();
      --col_number;
        }
     });

I need to delete the entire column and this ways it works how can I simplify this code not to repeat so many times, I tried something like this:

  $(document).on('click', 'button[id=delete_column]', function () {
      for (i = 0; i < 4; i++) {
        console.log(i);
    if (col_number > 1) {
      $('#column' + col_number[i]).remove();

    }
      --col_number;
        }
     });

});

But does not work..

Body:
Try Below Code :

$(document).on('click', 'button[id=delete_column]', function () {
    if (col_number > 1) {
    for (var i=0; i<col_number; i++) {
         $('#column' + i).remove();
    };
  }
});


问:
psd to html dimensions
I am starting learning html 5 and css3 and recently i tried to convert one of my designs in Photoshop to html  and modify with CSS.

Everything went well except of dimension on the full screen. My psd file has dimension of 1020px x 1834px . Now when I put it on full screen on my 27" screen it has a lot of space between the edges psd design

htm/css design

Is there any specific command for different screens or monitoring. I have also used

<meta name="viewport" content="width=device-width, initial-scale=1">
and putted on my body in css the dimensions of psd
Any ideas?

答: You will have to change your design a little in your psd. A regular container on many websites has a width of 1440 pixels. Since your design is only 1020px wide, it's looking narrow when converted to HTML. Looking at your PSD design, I suggest let your original psd be at least 1640px wide, leaving a gap of 100px on each side.</p>

Title: psd to html dimensions


问:
ngIf not working if value contains hyphen(-) between text
*ngIf not comparing value properly if value/data contains a hyphen(-) symbol i.e. 'Pick-list' in my example.

If I remove the hyphen(-) symbol then it's work.
So how to compare string which contains a hyphen(-) symbol?

not working:

<ng-container *ngIf="fieldInfo.FieldType=='Pick-list'">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>working:

<ng-container *ngIf="fieldInfo.FieldType=='Checklist'">
       <h1>Check list</h1>
</ng-container></code>```

答:
Try to assign the string 'Pick-list' to a variable in your .ts file.

```<code>let pickList = 'Pick-list';
</code>```

Then compare with the variable:

```<code><ng-container *ngIf="fieldInfo.FieldType==pickList">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>
</code>```

Body:
*ngIf not comparing value properly if value/data contains a hyphen(-) symbol i.e. 'Pick-list' in my example.

If I remove the hyphen(-) symbol then it's work.
So how to compare string which contains a hyphen(-) symbol?

not working:

<ng-container *ngIf="fieldInfo.FieldType=='Pick-list'">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>

working:

<ng-container *ngIf="fieldInfo.FieldType=='Checklist'">

Check list

</ng-container>

Body:
Try to assign the string 'Pick-list' to a variable in your .ts file.

let pickList = 'Pick-list';

Then compare with the variable:

<ng-container *ngIf="fieldInfo.FieldType==pickList">
       <select class="form-control" required="">
       <option></option>
       <option> Lorem ipsum dolor sit amet </option>
       <option> Donec imperdiet sit amet </option>
       </select>
</ng-container>


问:
How to read inline styling of an element?
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

```<code><div id="foo" style="width: 100px; height: 100px; background: green;"></div>
</code>```

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

```<code>var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'
</code>```

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

答:
Updated to work with IE

You could try something like this

```<code>function hasInlineStyle(obj, style) {
    var attrs = obj.getAttribute('style');
    if(attrs === null) return false;
    if(typeof attrs == 'object') attrs = attrs.cssText;
    var styles = attrs.split(';');
    for(var x = 0; x < styles.length; x++) {
        var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
        if(attr == style) {
            return true;
        }
    }
    return false;
}
</code>```

So if you have an element like this:

```<code><span id='foo' style='color: #000; line-height:20px;'></span>
</code>```

That also has a stylesheet like this:

```<code>#foo { background-color: #fff; }
</code>```

The function would return...

```<code>var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false
</code>```

OwnerDisplayName: sam

Body:
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

Body:
Updated to work with IE

You could try something like this

function hasInlineStyle(obj, style) {
    var attrs = obj.getAttribute('style');
    if(attrs === null) return false;
    if(typeof attrs == 'object') attrs = attrs.cssText;
    var styles = attrs.split(';');
    for(var x = 0; x < styles.length; x++) {
        var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
        if(attr == style) {
            return true;
        }
    }
    return false;
}

So if you have an element like this:

<span id='foo' style='color: #000; line-height:20px;'></span>

That also has a stylesheet like this:

#foo { background-color: #fff; }

The function would return...

var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false

OwnerDisplayName: Paolo Bergantino

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Paolo Bergantino


问:
putting clojure code in a loop
```<code>(def throws 10)

(defn r-squared [x y]
 (+ (* (- 0.5 x) (- 0.5 x))
    (* (- 0.5 y) (- 0.5 y))))

(loop [hits 0]
  (let [x (rand)
        y (rand)]
    ; still inside the let
    (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
        (recur (inc hits))
        (* 4 (/ hits throws)))))
</code>```

I got that code working and running until the if condition is true. How can I rewrite it so it takes X as parameter and runs X times?

I basically want to call (r-squared 100) and get how many hits I got as return value.

Title: putting clojure code in a loop

Body:
(def throws 10)

(defn r-squared [x y]
 (+ (* (- 0.5 x) (- 0.5 x))
    (* (- 0.5 y) (- 0.5 y))))

(loop [hits 0]
  (let [x (rand)
        y (rand)]
    ; still inside the let
    (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
        (recur (inc hits))
        (* 4 (/ hits throws)))))

I got that code working and running until the if condition is true. How can I rewrite it so it takes X as parameter and runs X times?

I basically want to call (r-squared 100) and get how many hits I got as return value.

Body:
(defn r-squared [x y]
 (+ (* (- 0.5 x) (- 0.5 x))
    (* (- 0.5 y) (- 0.5 y))))

(defn hit[]
  (let [x (rand) y (rand)]
    (< (r-squared x y) 0.25)))

(frequencies (for [i (range 1000)] (hit))) ; {true 787, false 213}


问:
Extract Substring from string using Batch
I need to extract substring(numeric with underscore) from a string using batch file. For example :

I have AbC_d1344_454_78a.
or
 Deg_e23_74_67.

I want to extract substring 1344_454_78 and 23_74_67.

答:
Using powershell you could use

```<code>$regex = [regex] '(?m)\d[\d_]*'
$matchdetails = $regex.Match("AbC_d1344_454_78a. or Deg_e23_74_67")
while ($matchdetails.Success) {
    $matchdetails.Value
    $matchdetails = $matchdetails.NextMatch()
}
</code>```

This searches for a number followed by any number of numbers or underscores

Body:
Using powershell you could use

$regex = [regex] '(?m)\d[\d_]*'
$matchdetails = $regex.Match("AbC_d1344_454_78a. or Deg_e23_74_67")
while ($matchdetails.Success) {
    $matchdetails.Value
    $matchdetails = $matchdetails.NextMatch()
}

This searches for a number followed by any number of numbers or underscores


问:
how to remove ffmpeg debug message
I'm building the ffmpeg source on my Linux board. With no options, I built it like this:

./configuration

make && make install

If you build with this and run the program using C ++, you will see the following ffmpeg error message in the console window (the program runs normally, but ffmpeg itself error code [eg decode_slick_header error])

[h264 @ 0x10c0ff0] non-existing PPS 0 referenced

[h264 @ 0x10c0ff0] non-existing PPS 0 referenced

[h264 @ 0x10c0ff0] decode_slice_header error

[h264 @ 0x10c0ff0] no frame!

[h264 @ 0x10c0ff0] non-existing PPS 0 referenced

...

I do not want to output these messages to the console window.

So we refer to the configuration document and build as follows.

./configuration --disable-logging --disable-debug
make && make install

However, the output of the build also produces an error message.

How would you like to build ffmpeg debug messages like this?

Thanks a lot for your help.

答:
Add this parameter to your system("/path/ffmpeg ..."); line (or whatever you use) when calling ffmpeg executable: -loglevel quiet

Hope that helps.

Title: how to remove ffmpeg debug message


问:
How do I resolve individual promise from a centralized listener?
I have an event listener, which will receive event (from server) whenever a specific task is done. I desire each task to be encapsulated in a promise, so that I can construct complex ordered workflow in a clean manner.

How would I resolve each task promise (by id) from a global listener?
Here's an conceptual example of what I am trying to achieve.

```<code>// list of all tasks
var tasks = {}
tasks['id-1'] = getTask('id-1')
tasks['id-2'] = getTask('id-2')

// do task in order
// each task will issue request to server, and wait for reply
tasks['id-1'].startPromise()
  .then(function(result) {

    // start second task from first task's data
    return tasks['id-2'].startPromise(result);
  })
  .then(function() {
    // finalized task works
    return true;
  });

// listen to task finish
client.listen('onReceive', function(event) {
  if(event.is('taskFinished')) {
    var id = event.taskId;
    tasks[id].resolve(event.result); //How do I resolve task from listener??
  }
});
</code>```

答:
Yes, you'd need a global mapping from ids to resolver functions.

```<code>const tasks = new Map;
function runTask(id, data) {
    return new Promise(resolve => {
        // if (tasks.has(id)) throw new Error("cannot run multiple "+id+" at once");
        tasks.set(id, resolve);
        client.fire('start', id, data); // or whatever you need to trigger the task
    })
}
client.on('taskFinished', event => { // or however you get notified of finished tasks
    const id = event.taskId;
    if (tasks.has(id)) {
        tasks.get(id)(event.result);
        tasks.delete(id);
    }
});
</code>```

You can also use a plain object instead of the ES6 Map if you prefer (or need ES5 compatibility), and you might write the listener so that it is only active when the mapping is not empty.

You would use this like

```<code>runTask('id-1').then(result =>
    runTask('id-2', result)
).then(() => {
    console.log("both done");
    return true;
})
</code>```

Body:
I have an event listener, which will receive event (from server) whenever a specific task is done. I desire each task to be encapsulated in a promise, so that I can construct complex ordered workflow in a clean manner.

How would I resolve each task promise (by id) from a global listener?
Here's an conceptual example of what I am trying to achieve.

// list of all tasks
var tasks = {}
tasks['id-1'] = getTask('id-1')
tasks['id-2'] = getTask('id-2')

// do task in order
// each task will issue request to server, and wait for reply
tasks['id-1'].startPromise()
  .then(function(result) {

    // start second task from first task's data
    return tasks['id-2'].startPromise(result);
  })
  .then(function() {
    // finalized task works
    return true;
  });

// listen to task finish
client.listen('onReceive', function(event) {
  if(event.is('taskFinished')) {
    var id = event.taskId;
    tasks[id].resolve(event.result); //How do I resolve task from listener??
  }
});

Body:
Yes, you'd need a global mapping from ids to resolver functions.

const tasks = new Map;
function runTask(id, data) {
    return new Promise(resolve => {
        // if (tasks.has(id)) throw new Error("cannot run multiple "+id+" at once");
        tasks.set(id, resolve);
        client.fire('start', id, data); // or whatever you need to trigger the task
    })
}
client.on('taskFinished', event => { // or however you get notified of finished tasks
    const id = event.taskId;
    if (tasks.has(id)) {
        tasks.get(id)(event.result);
        tasks.delete(id);
    }
});

You can also use a plain object instead of the ES6 Map if you prefer (or need ES5 compatibility), and you might write the listener so that it is only active when the mapping is not empty.

You would use this like

runTask('id-1').then(result =>
    runTask('id-2', result)
).then(() => {
    console.log("both done");
    return true;
})


问:
How to log a custom event with parms using Facebook analytics using swift
I know this a basic question, but I can't work out how to log a custom event with custom parameters using facebook analytics. For example, I would like to log the following:

song played

title

artist

Please see the below code (which does not work):

```<code>    let dict = AppEvent.ParametersDictionary(AppEventParameterName.Custom("title), AppEventParameterName.Custom("artist"))

    AppEvent.ViewedContent(contentType: "test", contentId: "test", extraParameters: dict)
</code>```

I get the error message:

"Cannot invoke value of type 'ParametersDictionary.Type' (aka 'Dictionary.Type') with argument list '(AppEventParameterName, AppEventParameterName)"

I have also tried:

```<code>let dict = AppEvent.ParametersDictionary(AppEventParameterName.Custom("title"), "test")
</code>```

Any help would be greatly appreciated.

答:
Addition to Daniel's answer

For Swift 4:

```<code>let fbParams: [AppEventParameterName : AppEventParameterValueType] = [AppEventParameterName.init("id") : id]
</code>```

Body:
I know this a basic question, but I can't work out how to log a custom event with custom parameters using facebook analytics. For example, I would like to log the following:

song played

title

artist

Please see the below code (which does not work):

    let dict = AppEvent.ParametersDictionary(AppEventParameterName.Custom("title), AppEventParameterName.Custom("artist"))

    AppEvent.ViewedContent(contentType: "test", contentId: "test", extraParameters: dict)

I get the error message:

"Cannot invoke value of type 'ParametersDictionary.Type' (aka 'Dictionary.Type') with argument list '(AppEventParameterName, AppEventParameterName)"

I have also tried:

let dict = AppEvent.ParametersDictionary(AppEventParameterName.Custom("title"), "test")

Any help would be greatly appreciated.

Body:
Addition to Daniel's answer

For Swift 4:

let fbParams: [AppEventParameterName : AppEventParameterValueType] = [AppEventParameterName.init("id") : id]


问:
Check if element is clicked before removal
I have the following jquery code:

```<code>$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});
</code>```

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

答:
Without knowing more about this UI the only thing we have to work with is what is shown. There may be better ways to accomplish your needs but based on what little is known you could add a setTimeout to delay the removal. Also add a class in the click event handler that the removal code checks for

```<code>var delay = 500;// adjust according to preference. Can even set it to zero

$(document).on('focusout', '#element_a', function(e) {
  setTimeout(function() {
    // only remove if it doesn't have selected class
    $('#element_b').not('.selected').remove();
  }, delay);
});
$(document).on('click', '#element_b', function(e) {
  $(this).addClass('selected');
  // do other stuff here
});
</code>```

Body:
I have the following jquery code:

$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

Body:
Without knowing more about this UI the only thing we have to work with is what is shown. There may be better ways to accomplish your needs but based on what little is known you could add a setTimeout to delay the removal. Also add a class in the click event handler that the removal code checks for

var delay = 500;// adjust according to preference. Can even set it to zero

$(document).on('focusout', '#element_a', function(e) {
  setTimeout(function() {
    // only remove if it doesn't have selected class
    $('#element_b').not('.selected').remove();
  }, delay);
});
$(document).on('click', '#element_b', function(e) {
  $(this).addClass('selected');
  // do other stuff here
});


问:
JQuery - Disable scroll wheel until animation is completed

I am trying to disable mousewheel on mousewheel event and only enable it after the action is completed.

```<code>$(window).on('DOMMouseScroll mousewheel', function (event) {

    //disable mousewhell until the following animation is complete

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500);

    //enable mousewhell

    return false;
});
</code>```

I would also like the code to ignore every scroll after the first one, until the animation is complete. In this particular case, I want the animation to complete only once, even if the user scrolls for more than one tick on mouse wheel. Basically in this case, I want the mouse wheel to be disabled for 500 milliseconds after a single mouse scroll "tick", and not register the remaining "ticks" ever (if the user scrolls for 10 ticks during these 500 milliseconds, I only want one animation, while the rest are ignored). After 500 milliseconds, I want the mousewheel to be enabled once again.

I thank you in advance.

答:
I did originally close this question as a duplicate but was told it only answer half the question. I re-openend it to add a suggested solution for not processing the event again until the animation is done.

Using animate complete as suggested in this SO post

You should be able to do something similar to this:

```<code>var animating = false;

$(window).on('DOMMouseScroll mousewheel', function (event) {
    if(animating){
        return false;
    }

   animating = true;

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500, function(){
        animating = false;
    });
});
</code>```

Body:
I am trying to disable mousewheel on mousewheel event and only enable it after the action is completed.

$(window).on('DOMMouseScroll mousewheel', function (event) {

    //disable mousewhell until the following animation is complete

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500);

    //enable mousewhell

    return false;
});

I would also like the code to ignore every scroll after the first one, until the animation is complete. In this particular case, I want the animation to complete only once, even if the user scrolls for more than one tick on mouse wheel. Basically in this case, I want the mouse wheel to be disabled for 500 milliseconds after a single mouse scroll "tick", and not register the remaining "ticks" ever (if the user scrolls for 10 ticks during these 500 milliseconds, I only want one animation, while the rest are ignored). After 500 milliseconds, I want the mousewheel to be enabled once again.

I thank you in advance.

Body:
I did originally close this question as a duplicate but was told it only answer half the question. I re-openend it to add a suggested solution for not processing the event again until the animation is done.

Using animate complete as suggested in this SO post

You should be able to do something similar to this:

var animating = false;

$(window).on('DOMMouseScroll mousewheel', function (event) {
    if(animating){
        return false;
    }

   animating = true;

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500, function(){
        animating = false;
    });
});


问:
Ideas to implement "vote" ContentType-based app
I want to create an app to allow the voting of any model (thumbs up and thumbs down, pretty much like SO in it's questions and answers), using ContentTypes (like the comments framework or the tags examples in docs).

I just set up the models and templatetags, it's possible to get the count of votes and etc.
What bugs me is what should be the best way to make voting possible.

This is the vote class:

```<code>class Vote(models.Model):
    TYPES_VOTE = (
        ( 'POS', 'Positive' ),
        ( 'NEG', 'Negative' ),
    )

    type            = models.CharField(max_length=3, choices=TYPES_VOTE, default=None)
    content_type    = models.ForeignKey(ContentType)
    object_id       = models.PositiveIntegerField(db_index=True)
</code>```

I wrote a simple view that receives the content-type, object id and type of vote (up or down). But I don't know the best way to call this view. Some possibilities:

Vote by just GET request, urls.py will catch the request and pass the right content-type(example: url(r'^question/(?P<question_id>)/vote/(?P<vote_type>)/$', voting_views.vote, {'content_type' : ContentType.objects.get_for_model(Question()) }, name='vote_question'),)

Vote by POST request, creating a form for the vote that has the ContentType for the object and type of vote. I'm not sure how do implement this, without having two forms for each model in the template that can be voted.

Any ideas?

答:
You can check http://code.google.com/p/django-voting/

It's pretty similar to what you try to do: http://code.google.com/p/django-voting/source/browse/trunk/voting/models.py

Body:
I want to create an app to allow the voting of any model (thumbs up and thumbs down, pretty much like SO in it's questions and answers), using ContentTypes (like the comments framework or the tags examples in docs).

I just set up the models and templatetags, it's possible to get the count of votes and etc.
What bugs me is what should be the best way to make voting possible.

This is the vote class:

class Vote(models.Model):
    TYPES_VOTE = (
        ( 'POS', 'Positive' ),
        ( 'NEG', 'Negative' ),
    )

    type            = models.CharField(max_length=3, choices=TYPES_VOTE, default=None)
    content_type    = models.ForeignKey(ContentType)
    object_id       = models.PositiveIntegerField(db_index=True)

I wrote a simple view that receives the content-type, object id and type of vote (up or down). But I don't know the best way to call this view. Some possibilities:

Vote by just GET request, urls.py will catch the request and pass the right content-type(example: url(r'^question/(?P<question_id>)/vote/(?P<vote_type>)/$', voting_views.vote, {'content_type' : ContentType.objects.get_for_model(Question()) }, name='vote_question'),)

Vote by POST request, creating a form for the vote that has the ContentType for the object and type of vote. I'm not sure how do implement this, without having two forms for each model in the template that can be voted.

Any ideas?


问:
PHP7: mcrypt_cbc not work
please help to solve the problem.

how to make it work for on php 7 ?

```<code>function decr($string) {
    $key="";
    $iv = mcrypt_create_iv(mcrypt_get_block_size (MCRYPT_CAST_32, MCRYPT_MODE_CFB), MCRYPT_DEV_RANDOM);
    $string = base64_decode(trim($string));
    $dec =  mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT, $iv);
    return $dec;
}
</code>```

答:
I had recently this problem in an app, i did not use mcrypt_encrypt() as suggested because of :

Warning
  This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

I did it using openssl (php-openssl) this way :

```<code>function _encrypt($data){
    $initialVector = openssl_random_pseudo_bytes(16, $secure);
    $secretKey = '<SECRET_KEY>'; // string : 16 length
    return  openssl_encrypt($data, "aes-128-cbc", $secretKey, OPENSSL_RAW_DATA, $initialVector);
}

function _decrypt($data){
    $initialVector = openssl_random_pseudo_bytes(16, $secure);
    $secretKey = '<SECRET_KEY>'; // string : 16 length
    return  openssl_decrypt($data, "aes-128-cbc", $secretKey, OPENSSL_RAW_DATA, $initialVector);
}
</code>```

Note : initial vector/secret key generated this way is just for example

Title: PHP7: mcrypt_cbc not work

Body:
please help to solve the problem.

how to make it work for on php 7 ?

function decr($string) {
    $key="";
    $iv = mcrypt_create_iv(mcrypt_get_block_size (MCRYPT_CAST_32, MCRYPT_MODE_CFB), MCRYPT_DEV_RANDOM);
    $string = base64_decode(trim($string));
    $dec =  mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT, $iv);
    return $dec;
}

Body:
I had recently this problem in an app, i did not use mcrypt_encrypt() as suggested because of :

Warning
  This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

I did it using openssl (php-openssl) this way :

function _encrypt($data){
    $initialVector = openssl_random_pseudo_bytes(16, $secure);
    $secretKey = '<SECRET_KEY>'; // string : 16 length
    return  openssl_encrypt($data, "aes-128-cbc", $secretKey, OPENSSL_RAW_DATA, $initialVector);
}

function _decrypt($data){
    $initialVector = openssl_random_pseudo_bytes(16, $secure);
    $secretKey = '<SECRET_KEY>'; // string : 16 length
    return  openssl_decrypt($data, "aes-128-cbc", $secretKey, OPENSSL_RAW_DATA, $initialVector);
}

Note : initial vector/secret key generated this way is just for example


问:
Xcode 6- SWIFT- Cast CMTime as Float
```<code>var songs = MPMediaQuery()
var localSongs = songs.items
songList = NSMutableArray(array: localSongs)

tableView.reloadData()

var song = MPMediaItem(coder: songList[0] as NSCoder)

var currentItem = AVPlayerItem(URL: song.valueForProperty(MPMediaItemPropertyAssetURL) as NSURL)

player.replaceCurrentItemWithPlayerItem(currentItem)

player.play()

var songTitle: AnyObject! = song.valueForProperty(MPMediaItemPropertyTitle)

songName.text = songTitle as? String

sliderOutlet.value = Float(player.currentTime()) // <<-Error here
</code>```

I'm building a music player and I want a slider to show the duration of the song, but I get this error

Could not find an overload for 'init' that accepts the supplied arguments

I think the problem is converting CMTime to Float.

答:
CMTime is a structure, containing a value, timescale, flags and epoch. So you cannot just "cast" it to a floating point value.

You can use the value by directly writing

```<code>sliderOutlet.value = Float(player.currentTime().value)
</code>```

But this will only give the value of the player which is in milliseconds. To get the value in seconds you use this:

```<code>sliderOutlet.value = Float(CMTimeGetSeconds(player.currentTime()))
</code>```

Mind well this might also won't be the correct way you should have the value of your slider.

Title: Xcode 6- SWIFT- Cast CMTime as Float

Body:
var songs = MPMediaQuery()
var localSongs = songs.items
songList = NSMutableArray(array: localSongs)

tableView.reloadData()

var song = MPMediaItem(coder: songList[0] as NSCoder)

var currentItem = AVPlayerItem(URL: song.valueForProperty(MPMediaItemPropertyAssetURL) as NSURL)

player.replaceCurrentItemWithPlayerItem(currentItem)

player.play()

var songTitle: AnyObject! = song.valueForProperty(MPMediaItemPropertyTitle)

songName.text = songTitle as? String

sliderOutlet.value = Float(player.currentTime()) // <<-Error here

I'm building a music player and I want a slider to show the duration of the song, but I get this error

Could not find an overload for 'init' that accepts the supplied arguments

I think the problem is converting CMTime to Float.

Body:
CMTime is a structure, containing a value, timescale, flags and epoch. So you cannot just "cast" it to a floating point value.

You can use the value by directly writing

sliderOutlet.value = Float(player.currentTime().value)

But this will only give the value of the player which is in milliseconds. To get the value in seconds you use this:

sliderOutlet.value = Float(CMTimeGetSeconds(player.currentTime()))

Mind well this might also won't be the correct way you should have the value of your slider.


问:
Select corresponding to row from the same table SQL Server
I want to get some column based on another column

Example table:

```<code>| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 1.00        | 1           | 360         |
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | -32.94      | 2           | 360         |
| 5510     | bbb           | 1.00        | 1           | 360         |
| 5510     | bbb           | 36.37       | 3           | 3600        |
</code>```

but I want to get the rows where BillVersion is max for every BlilCode is max

Expected result

```<code>| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | 36.37       | 3           | 3600        |
</code>```

My current query is:

```<code>SELECT
    [BlilCode], [BlilShortName],
    BatchWeigth, (BillVersion) AS BillVersion, [BlilMaxTime]
FROM
    [CVfeedDB].[dbo].[constants.Blil]
WHERE
    BlilActive = 1 AND BatchWeigth IS NOT NULL
ORDER BY
    BlilCode
</code>```

答:
I'm not really smart from your description, however, the result can be achieved using the following query

```<code>select your_table.*
from your_table
join
(
  select BlilShortName, max(billversion) bmax
  from your_table
  group by BlilShortName
) t on your_table.billversion = t.bmax and your_table.BlilShortName = t.BlilShortName
</code>```

From my experience it can be faster in some cases when compared to row_number solution which always uses sequential scan.

PERFORMANCE BONUS

Since there is a discussion regarding the efficiency I dare to add simple test

```<code>IF OBJECT_ID('dbo.GTable', 'U') IS NOT NULL  DROP TABLE dbo.GTable
SELECT TOP 1000000
      NEWID() id,
      ABS(CHECKSUM(NEWID())) % 100 group_id,
      ABS(CHECKSUM(NEWID())) % 10000 orderby
 INTO GTable
FROM    sys.sysobjects
CROSS JOIN sys.all_columns

SET STATISTICS TIME on
-- GROUP BY version
select t1.*
from gtable t1
join
    (
      SELECT group_id, max(orderby) gmax
      from gtable
      group by group_id
    ) t2 on t1.group_id = t2.group_id and t1.orderby = t2.gmax

-- WINDOW FUNCTION version
select t.id, t.group_id, t.orderby
from
(
select *,
       dense_rank() over (partition by group_id order by orderby desc) rn
from gtable
) t
where t.rn = 1
</code>```

If I run this on my server then the performance of GROUP BY version is more than twice better than the window function version. Moreover, if I create index

```<code>CREATE NONCLUSTERED INDEX ix_gtable_groupid_orderby
    ON [dbo].[GTable] (group_id,orderby) INCLUDE (id)
</code>```

then the performance is even more than three times better, whereas the performance of window function solution is the same since it uses sequential scan despite the index.

Body:
I want to get some column based on another column

Example table:

| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 1.00        | 1           | 360         |
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | -32.94      | 2           | 360         |
| 5510     | bbb           | 1.00        | 1           | 360         |
| 5510     | bbb           | 36.37       | 3           | 3600        |

but I want to get the rows where BillVersion is max for every BlilCode is max

Expected result

| BlilCode | BlilShortName | BatchWeigth | BillVersion | BlilMaxTime |
+----------+---------------+-------------+-------------+-------------+
| 5502     | aaa           | 2.00        | 2           | 240         |
| 5510     | bbb           | 36.37       | 3           | 3600        |

My current query is:

SELECT
    [BlilCode], [BlilShortName],
    BatchWeigth, (BillVersion) AS BillVersion, [BlilMaxTime]
FROM
    [CVfeedDB].[dbo].[constants.Blil]
WHERE
    BlilActive = 1 AND BatchWeigth IS NOT NULL
ORDER BY
    BlilCode

Body:
I'm not really smart from your description, however, the result can be achieved using the following query

select your_table.*
from your_table
join
(
  select BlilShortName, max(billversion) bmax
  from your_table
  group by BlilShortName
) t on your_table.billversion = t.bmax and your_table.BlilShortName = t.BlilShortName

From my experience it can be faster in some cases when compared to row_number solution which always uses sequential scan.

PERFORMANCE BONUS

Since there is a discussion regarding the efficiency I dare to add simple test

IF OBJECT_ID('dbo.GTable', 'U') IS NOT NULL  DROP TABLE dbo.GTable
SELECT TOP 1000000
      NEWID() id,
      ABS(CHECKSUM(NEWID())) % 100 group_id,
      ABS(CHECKSUM(NEWID())) % 10000 orderby
 INTO GTable
FROM    sys.sysobjects
CROSS JOIN sys.all_columns

SET STATISTICS TIME on
-- GROUP BY version
select t1.*
from gtable t1
join
    (
      SELECT group_id, max(orderby) gmax
      from gtable
      group by group_id
    ) t2 on t1.group_id = t2.group_id and t1.orderby = t2.gmax

-- WINDOW FUNCTION version
select t.id, t.group_id, t.orderby
from
(
select *,
       dense_rank() over (partition by group_id order by orderby desc) rn
from gtable
) t
where t.rn = 1

If I run this on my server then the performance of GROUP BY version is more than twice better than the window function version. Moreover, if I create index

CREATE NONCLUSTERED INDEX ix_gtable_groupid_orderby
    ON [dbo].[GTable] (group_id,orderby) INCLUDE (id)

then the performance is even more than three times better, whereas the performance of window function solution is the same since it uses sequential scan despite the index.


问:
Print a two-dimensional array into a table in AngularJS
I have a two-dimensional array received from controller which I can access in html like this: $ctrl.myTable.

All sub-arrays have the same length but there can a changeable number of sub-arrays.

It has this form:

```<code>$ctrl.myTable = [[111, 222, 333, 444, ...],
                 [123, 234, 345, 456, ...],
                 ...
                ];
</code>```

I want to put it into a table. I managed to put the table header (which is an one-dimensional array with same length as the sub-arrays of the first one) but I don't know how to put each value on a separate row.

```<code><div>

            <table class="table table-striped">
                <thead>
                    <tr>
                        <th ng-repeat="label in $ctrl.tableTitle">{{label}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr><td ng-repeat="label in $ctrl.tableTitle">{{$ctrl.myTable[0]}}</td></tr>
                </tbody>
            </table>

</div>
</code>```

Like this I only have the first sub-array as the first element on a row.

My goal it to have it like this:

```<code>name1 name2 name3 name4
111     123   ...  ...
222     234   ...  ...
333     345   ...  ...
444     456   ...  ...
...     ...   ...  ...
</code>```

Do you have any idea how to go through the array to make it like that?

答:
Replace your tbody code by:

```<code><tbody>
    <tr ng-repeat="rows in $ctrl.myTable[0]">
        <td ng-repeat="label in $ctrl.tableTitle">{{$ctrl.myTable[$index][$parent.$index]}}</td>
    </tr>
</tbody>
</code>```

Body:
I have a two-dimensional array received from controller which I can access in html like this: $ctrl.myTable.

All sub-arrays have the same length but there can a changeable number of sub-arrays.

It has this form:

$ctrl.myTable = [[111, 222, 333, 444, ...],
                 [123, 234, 345, 456, ...],
                 ...
                ];

I want to put it into a table. I managed to put the table header (which is an one-dimensional array with same length as the sub-arrays of the first one) but I don't know how to put each value on a separate row.

                        {{label}}

{{$ctrl.myTable[0]}}

Like this I only have the first sub-array as the first element on a row.

My goal it to have it like this:

name1 name2 name3 name4
111     123   ...  ...
222     234   ...  ...
333     345   ...  ...
444     456   ...  ...
...     ...   ...  ...

Do you have any idea how to go through the array to make it like that?

Body:
Replace your tbody code by:

<tbody>
    <tr ng-repeat="rows in $ctrl.myTable[0]">
        <td ng-repeat="label in $ctrl.tableTitle">{{$ctrl.myTable[$index][$parent.$index]}}</td>
    </tr>
</tbody>


问:
ReactJS - Href Triggered DELETE Method
I'm determining the correct method for triggering my DELETE route through the use of href and node-fetch. I had originally thought that passing a function in my stateful component as an attribute on my stateless component and then using that as the link location would trigger the function, but it doesn't appear to work and now I am left second guessing my approach. Is there a better solution to what I have attempted?

Here is my stateful component:

```<code>class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    commentInformation(e){
        //e.preventDefault();
        console.log("commentInformation function triggered");
        this.deleteComment(this.props.recordIdHash, this.recordCommentId);
    }

    deleteComment(recordId, recordCommentId){
        var body = { recordId: recordId, recordCommentId: recordCommentId };
        var route = 'http://localhost:3000/app/record/' + recordId + '/comment/' + recordCommentId;
        fetch(route,
            {
                method: 'DELETE',
                body: JSON.stringify(body),
                headers: {
                    'X-CSRF-Token': 'csrfToken',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.props.updateComments(data)
                this.setState({'flash': 'success'});
            })
            .catch(err => {
                console.log(err);
                this.setState({'flash': 'error'});
            });
    }

    render(){
        return (
            <div className="record-comment__record">
                <div className="row">
                    <div className="col-md-12">
                        <div className="record-comment__meta">
                            <div className="row">
                                <div className="col-md-8 record-comment__profile">
                                    <img src={this.props.app.picture} className="profile__picture profile__picture--small"/>
                                    <p className="record-comment__info"><b>{this.props.app.fullNameSlug}</b> | <i>{this.props.createdAtDateSlug}</i></p>
                                    <DeleteComment commentUserId={this.props.app.userId} userId={this.props.currentUserId} recordId={this.props.recordIdHash} deleteComment={this.commentInformation} commentId={this.props.recordCommentId}/>
                                </div>
                            </div>
                        </div>
                        <div className="record-comment__body">
                            <div className="row">
                                <div className="col-md-12">
                                    <p>{this.props.comment}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
</code>```

Here is my <DeleteComment> component which maps the comment user id to the logged in user id and if they are the same, then show the delete href:

```<code>const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
            <a href={props.deleteComment} className="record-comment__delete"> | Delete</a>
        )
    } else {
        return null;
    }
}
</code>```

答:
In you DeleteComment-component you are passing a function to a href.. That is not correct, since href expects a string.

You could use onClick instead, and change your href to href="#" or use a <button />

Title: ReactJS - Href Triggered DELETE Method

Body:
I'm determining the correct method for triggering my DELETE route through the use of href and node-fetch. I had originally thought that passing a function in my stateful component as an attribute on my stateless component and then using that as the link location would trigger the function, but it doesn't appear to work and now I am left second guessing my approach. Is there a better solution to what I have attempted?

Here is my stateful component:

class Comment extends React.Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    commentInformation(e){
        //e.preventDefault();
        console.log("commentInformation function triggered");
        this.deleteComment(this.props.recordIdHash, this.recordCommentId);
    }

    deleteComment(recordId, recordCommentId){
        var body = { recordId: recordId, recordCommentId: recordCommentId };
        var route = 'http://localhost:3000/app/record/' + recordId + '/comment/' + recordCommentId;
        fetch(route,
            {
                method: 'DELETE',
                body: JSON.stringify(body),
                headers: {
                    'X-CSRF-Token': 'csrfToken',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })
            .then(data => {
                console.log(data);
                this.props.updateComments(data)
                this.setState({'flash': 'success'});
            })
            .catch(err => {
                console.log(err);
                this.setState({'flash': 'error'});
            });
    }

    render(){
        return (

{this.props.app.fullNameSlug} | {this.props.createdAtDateSlug}

                                    <DeleteComment commentUserId={this.props.app.userId} userId={this.props.currentUserId} recordId={this.props.recordIdHash} deleteComment={this.commentInformation} commentId={this.props.recordCommentId}/>

{this.props.comment}

        )
    }
}

Here is my <DeleteComment> component which maps the comment user id to the logged in user id and if they are the same, then show the delete href:

const DeleteComment = props => {
    if(props.commentUserId == props.userId){
        return (
             | Delete
        )
    } else {
        return null;
    }
}


问:
Javascript inheritance with super() call
I had some pseudoclasses that shared a large part of their initialization. I decided to take this initialization out and create a base class, from which they'll inherit.

```<code>function BaseClass(param1, param2) {
    ...
}

function SubClassA(param1) {
    ...
}

function SubClassB(param1) {
    ...
}
</code>```

I want SubClass1 and SubClass2 to inherit from BaseClass in the following manner:

SubClassA(param1) constructor calls BaseClass(param1, "I am A.")

SubClassB(param1) constructor calls BaseClass(param1, "I am B.")

so BaseClass adds some properties to them. Then both subclasses do some initialization of their own.

Now I can't just do SubClassA.prototype = new BaseClass(), because I want the super constructor to take parameters. How to do this elegantly?

答:
Add an area method to Rectangle's prototype.Create a Square class that satisfies the following:

It is a subclass of Rectangle.

It contains a constructor and no other methods.

It can use the Rectangle class' area method to print the area of a Square

```<code>class Rectangle {

  constructor(w, h) {
   this.w = w;
    this.h = h;
  }
}
Rectangle.prototype.area = function()
{
  var a = this.w * this.h;
  return a;
 }
 class Square extends Rectangle{
     constructor(r) {
        super(r, r)
       }
  }

  const rec = new Rectangle(3, 4);
  const sqr = new Square(3);

  console.log(rec.area());
  console.log(sqr.area());
</code>```

Body:
I had some pseudoclasses that shared a large part of their initialization. I decided to take this initialization out and create a base class, from which they'll inherit.

function BaseClass(param1, param2) {
    ...
}

function SubClassA(param1) {
    ...
}

function SubClassB(param1) {
    ...
}

I want SubClass1 and SubClass2 to inherit from BaseClass in the following manner:

SubClassA(param1) constructor calls BaseClass(param1, "I am A.")

SubClassB(param1) constructor calls BaseClass(param1, "I am B.")

so BaseClass adds some properties to them. Then both subclasses do some initialization of their own.

Now I can't just do SubClassA.prototype = new BaseClass(), because I want the super constructor to take parameters. How to do this elegantly?

Body:
Add an area method to Rectangle's prototype.Create a Square class that satisfies the following:

It is a subclass of Rectangle.

It contains a constructor and no other methods.

It can use the Rectangle class' area method to print the area of a Square

class Rectangle {

  constructor(w, h) {
   this.w = w;
    this.h = h;
  }
}
Rectangle.prototype.area = function()
{
  var a = this.w * this.h;
  return a;
 }
 class Square extends Rectangle{
     constructor(r) {
        super(r, r)
       }
  }

  const rec = new Rectangle(3, 4);
  const sqr = new Square(3);

  console.log(rec.area());
  console.log(sqr.area());


问:
How to get the exact week number if the week is starting with specified weekday on moment js?
Example:

Week day is starting from

moment().weekYear(yearValue).week(weekNumber).startOf('week').weekday(2)

which is Tuesday.

First week on 2017 the days are,

```<code>[3-Jan-2017, 4-Jan-2017, 5-Jan-2017, 6-Jan-2017, 7-Jan-2017, 8-Jan-2017, 9-Jan-2017]
</code>```

How to get the exact week number for 1-Jan-2017?

答:
```<code>var weeknumber = moment("1-Jan-2017").week();
</code>```

In my application I've served the locale globally depending on what language the user has logged in with, so I wouldn't worry about that.

Body:
Example:

Week day is starting from

moment().weekYear(yearValue).week(weekNumber).startOf('week').weekday(2)

which is Tuesday.

First week on 2017 the days are,

[3-Jan-2017, 4-Jan-2017, 5-Jan-2017, 6-Jan-2017, 7-Jan-2017, 8-Jan-2017, 9-Jan-2017]

How to get the exact week number for 1-Jan-2017?

Body:
var weeknumber = moment("1-Jan-2017").week();

In my application I've served the locale globally depending on what language the user has logged in with, so I wouldn't worry about that.


答:
Another Powershell

```<code>$entries = @('AbC_d1344_454_78a', 'Deg_e23_74_67') #example
$entries | %{[System.Text.RegularExpressions.Regex]::Match($_, '(\d[\d_]+\d)').Value}
</code>```

Depending on the formatting of the input data, you may wish to go to more or less strict regexp, e.g. (\d[\d_]*) or something more specific. I advice to use http://regexr.com to experiment with the regexp.

Title: Extract Substring from string using Batch

Body:
I need to extract substring(numeric with underscore) from a string using batch file. For example :

I have AbC_d1344_454_78a.
or
 Deg_e23_74_67.

I want to extract substring 1344_454_78 and 23_74_67.

Body:
Another Powershell

$entries = @('AbC_d1344_454_78a', 'Deg_e23_74_67') #example
$entries | %{[System.Text.RegularExpressions.Regex]::Match($_, '(\d[\d_]+\d)').Value}

Depending on the formatting of the input data, you may wish to go to more or less strict regexp, e.g. (\d[\d_]*) or something more specific. I advice to use http://regexr.com to experiment with the regexp.


问:
appcompat-v7:27.0.1 Issue with play-services-maps
I have this gradle

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.estimote:sdk:1.4.0'
    compile 'com.android.support:appcompat-v7:27.0.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.5.0'

    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

}
</code>```

I have problem with appcompat-v7:27.0.1 and the google play services.
if I use the 26.0.1 there is not problem with the google play services but cant use the afollestand 0.9.5.0.
I need the afollestand 0.9.5.0 that works with appcompat-v7:27

UPDATE:
Gradle image

答:
I've had the same problem. What user raghunandan suggested helps.

Using ./gradlew app:dependencies in your Apps folder ( or ./gradlew.bat app:dependencies on Windows), you get the dependency tree of all the packages.

There you can see that 'play-services-maps' requires some support packages with version 25.2.0, but most of them get upgraded to 27.0.2. But not all for some reason. You can do this manually though, by including them directly! (They will be part of your APK anyway)

```<code>compile 'com.android.support:support-v4:27.0.2'
</code>```

add that in your apps build.gradle alongside support-v7 and it'll work.

Body:
I have this gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.estimote:sdk:1.4.0'
    compile 'com.android.support:appcompat-v7:27.0.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.5.0'

    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

}

I have problem with appcompat-v7:27.0.1 and the google play services.
if I use the 26.0.1 there is not problem with the google play services but cant use the afollestand 0.9.5.0.
I need the afollestand 0.9.5.0 that works with appcompat-v7:27

UPDATE:
Gradle image

Body:
I've had the same problem. What user raghunandan suggested helps.

Using ./gradlew app:dependencies in your Apps folder ( or ./gradlew.bat app:dependencies on Windows), you get the dependency tree of all the packages.

There you can see that 'play-services-maps' requires some support packages with version 25.2.0, but most of them get upgraded to 27.0.2. But not all for some reason. You can do this manually though, by including them directly! (They will be part of your APK anyway)

compile 'com.android.support:support-v4:27.0.2'

add that in your apps build.gradle alongside support-v7 and it'll work.


问:
SQL modification to adjust depending on values
I insert some data from one table to another table. Just simple query with part i am intrested:

```<code>INSERT INTO column1value*100*column2value,
            column4value
...
</code>```

How to make if column1value value is either NULL or empty SQL trade that as:

```<code>INSERT INTO 100*column2value,
            column4value
...
</code>```

if column2value is either NULL or empty to be:

```<code>column1value*100
INSERT INTO 100*column2value,
            column4value
...
</code>```

答:
Your code makes no sense.  But the logic you want would seem to be coalesce():

```<code>SELECT COALESCE(column1value, 1) * 100 * COALESCE(column2value, 1),
       column4value
</code>```

You can use the same expression in a VALUES() clause.

Body:
I insert some data from one table to another table. Just simple query with part i am intrested:

INSERT INTO column1value*100*column2value,
            column4value
...

How to make if column1value value is either NULL or empty SQL trade that as:

INSERT INTO 100*column2value,
            column4value
...

if column2value is either NULL or empty to be:

column1value*100
INSERT INTO 100*column2value,
            column4value
...

Body:
Your code makes no sense.  But the logic you want would seem to be coalesce():

SELECT COALESCE(column1value, 1) * 100 * COALESCE(column2value, 1),
       column4value

You can use the same expression in a VALUES() clause.