问:
When is subscribe method of Angular Http module called
I have a component class and service class. I have the logic of flipping a flag when http 200 status code is received. Based on the response received, I flip the flag using an if condition.

```<code>Requests(data:Array<String>):Observable<any>{
    return this.http.post(this.Url,data)
      .map(
        (res:Response) => {
          if(res.status === 200 || res.status===201) {
            return res.json()
          }
        }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }
</code>```

The component file goes like this.

```<code>methodName(selectedData){

    this.service.Requests(Id).subscribe((Response => {
      this.rResponse = Response;

    }));
    if(rResponse){
    // My logic to flip the flag
        }
      }
    }
    }
</code>```

So based on the response received from service, I will flip the flag.

But when I run my code in debugger tools, the logic to flip the flag is never called even if there is a value in rResponse variable. Infact, when methodName function is called, the code flow tries to check for the value of rResponse under if loop first and then calls the subscribe method at the end.

If you could please suggest the flow in which subscribe method works. Why is the if condition called before the actual subscribe method is called.

This is not a duplicate because I want to understand why the flow does not go to my if loop. There is nothing undefined. I am getting values from the service

答:
What I understand is you want to do some logic upon receiving value in rResponse.

As you might know that subscribe method call is asynchronous in nature i.e once request it made execution resumes to next lines.

So, as you have written if condition outside subscribe method, if condition gets executed immediately before completion of service call. Which results in empty response.

So, you need to place the if condition in the same block where you are assigning the this.rResponse = Response;

```<code>methodName (selectedData) {
    this.service.Requests(Id).subscribe((Response => {
        this.rResponse = Response;
        if(this.rResponse) {
            // My logic to flip the flag
        }
    }));
}
</code>```

Body:
I have a component class and service class. I have the logic of flipping a flag when http 200 status code is received. Based on the response received, I flip the flag using an if condition.

Requests(data:Array<String>):Observable<any>{
    return this.http.post(this.Url,data)
      .map(
        (res:Response) => {
          if(res.status === 200 || res.status===201) {
            return res.json()
          }
        }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }

The component file goes like this.

methodName(selectedData){

    this.service.Requests(Id).subscribe((Response => {
      this.rResponse = Response;

    }));
    if(rResponse){
    // My logic to flip the flag
        }
      }
    }
    }

So based on the response received from service, I will flip the flag.

But when I run my code in debugger tools, the logic to flip the flag is never called even if there is a value in rResponse variable. Infact, when methodName function is called, the code flow tries to check for the value of rResponse under if loop first and then calls the subscribe method at the end.

If you could please suggest the flow in which subscribe method works. Why is the if condition called before the actual subscribe method is called.

This is not a duplicate because I want to understand why the flow does not go to my if loop. There is nothing undefined. I am getting values from the service

Body:
What I understand is you want to do some logic upon receiving value in rResponse.

As you might know that subscribe method call is asynchronous in nature i.e once request it made execution resumes to next lines.

So, as you have written if condition outside subscribe method, if condition gets executed immediately before completion of service call. Which results in empty response.

So, you need to place the if condition in the same block where you are assigning the this.rResponse = Response;

methodName (selectedData) {
    this.service.Requests(Id).subscribe((Response => {
        this.rResponse = Response;
        if(this.rResponse) {
            // My logic to flip the flag
        }
    }));
}


来源: stackexchange

问:
Trying to display previous visit date against each record
I have a set of visit records that I am trying work out some additional information based on the same data set:

I am trying to add a column on each row that gives the date previous to the current record based on the Actual Date so the second row would report the first rows actual date, the third the second etc... I would expect the first to report NULL

I have already created columns for First Visit and Last Visit using the following SQL

```<code>(SELECT TOP 1 v2.ACTUALDATE
from VISITS v2
   LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID
WHERE tv2.TRAINEEID = trv.TRAINEEID
ORDER BY v2.ACTUALDATE) as FirstVisit,

(SELECT TOP 1 v2.ACTUALDATE
 from VISITS v2
   LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID
 WHERE tv2.TRAINEEID = trv.TRAINEEID
 ORDER BY v2.ACTUALDATE DESC) as LASTVisit,
</code>```

EDIT* This is using MS SQL Server 2012, there are two tables involved in generating the data

Table 1 TRVISIT contains the following:
TRAINEEID, VISID

Table 2 VISITS contains the following:
VISID, VISITTYPE, PLANDATE, PLANEDNDATE, ACTUALDATE, ACTUALENDDATE, NOTES

I am trying to create a view that allows me to report for each TRAINEEID a list of visits with the individual data for each visit plus additional columns:
-VisitCount a count of visits for each Trainee
-ReviewCount a count of specific Visit type for each Trainee
-FirstVisit the date the first visit happened
-Lastvisit the date the last visit happened
-Previous Visit the date of the visit happened prior to the visit in the current record.

FULL CODE:

```<code>SELECT

--Link Data
trv.TRAINEEID,

--Visit Data
trv.VISID,
v.VISITTYPE,
v.PLANDATE,
v.PLANENDDATE,
v.ACTUALDATE,
v.ACTUALENDDATE,

v.NOTES,

(SELECT COUNT(*) FROM TRVISIT t2 WHERE t2.TRAINEEID = trv.TRAINEEID) AS VisitCount,
(SELECT COUNT(case WHEN v2.VISITTYPE = 'R' then 1 else null end) FROM TRVISIT tv2 LEFT JOIN VISITS v2 ON tv2.VISID = v2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID) AS ReviewCount,
(SELECT TOP 1 v2.ACTUALDATE from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID ORDER BY v2.ACTUALDATE) as FirstVisit,
(SELECT TOP 1 v2.ACTUALDATE from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID ORDER BY v2.ACTUALDATE DESC) as LASTVisit,
(SELECT LAG(v2.ACTUALDATE, 1) OVER(PARTITION BY tv2.TRAINEEID ORDER BY v2.ACTUALDATE ASC) from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID) as PrevVist,

COUNT(*) OVER () as Total_Rows

FROM TRVISIT trv
LEFT JOIN VISITS v on trv.VISID = v.VISID

ORDER BY v.ACTUALDATE
</code>```

答:
There are a whole bunch of window functions that use the over clause, not limited to just the lag function. You can leverage those instead of resorting to multiple subqueries for each aggregation that you want.

The below answer should get you everything you're looking for.

```<code>select tv.traineeid
, v.plandate
, v.planenddate
, v.actualdate
, v.actualenddate
, count(v.visid) over (partition by tv.traineeid) as VisitCount
, sum(case when tv.visittype = 'R' then 1 else 0 end) over (partition by tv.traineeid) as ReviewCount
, min(v.actualdate) over (partition by tv.traineeid) as FirstVisit
, max(v.actualdate) over (partition by tv.traineeid) as LastVisit
, lag(v.actualdate, 1, NULL) over (partition by tv.traineeid order by v.actualdate asc) as PrevVisit
from trvisit as tv
left join visits as v on tv.visid = v.visid
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a set of visit records that I am trying work out some additional information based on the same data set:

I am trying to add a column on each row that gives the date previous to the current record based on the Actual Date so the second row would report the first rows actual date, the third the second etc... I would expect the first to report NULL

I have already created columns for First Visit and Last Visit using the following SQL

(SELECT TOP 1 v2.ACTUALDATE
from VISITS v2
   LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID
WHERE tv2.TRAINEEID = trv.TRAINEEID
ORDER BY v2.ACTUALDATE) as FirstVisit,

(SELECT TOP 1 v2.ACTUALDATE
 from VISITS v2
   LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID
 WHERE tv2.TRAINEEID = trv.TRAINEEID
 ORDER BY v2.ACTUALDATE DESC) as LASTVisit,

EDIT* This is using MS SQL Server 2012, there are two tables involved in generating the data

Table 1 TRVISIT contains the following:
TRAINEEID, VISID

Table 2 VISITS contains the following:
VISID, VISITTYPE, PLANDATE, PLANEDNDATE, ACTUALDATE, ACTUALENDDATE, NOTES

I am trying to create a view that allows me to report for each TRAINEEID a list of visits with the individual data for each visit plus additional columns:
-VisitCount a count of visits for each Trainee
-ReviewCount a count of specific Visit type for each Trainee
-FirstVisit the date the first visit happened
-Lastvisit the date the last visit happened
-Previous Visit the date of the visit happened prior to the visit in the current record.

FULL CODE:

SELECT

--Link Data
trv.TRAINEEID,

--Visit Data
trv.VISID,
v.VISITTYPE,
v.PLANDATE,
v.PLANENDDATE,
v.ACTUALDATE,
v.ACTUALENDDATE,

v.NOTES,

(SELECT COUNT(*) FROM TRVISIT t2 WHERE t2.TRAINEEID = trv.TRAINEEID) AS VisitCount,
(SELECT COUNT(case WHEN v2.VISITTYPE = 'R' then 1 else null end) FROM TRVISIT tv2 LEFT JOIN VISITS v2 ON tv2.VISID = v2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID) AS ReviewCount,
(SELECT TOP 1 v2.ACTUALDATE from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID ORDER BY v2.ACTUALDATE) as FirstVisit,
(SELECT TOP 1 v2.ACTUALDATE from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID ORDER BY v2.ACTUALDATE DESC) as LASTVisit,
(SELECT LAG(v2.ACTUALDATE, 1) OVER(PARTITION BY tv2.TRAINEEID ORDER BY v2.ACTUALDATE ASC) from VISITS v2 LEFT JOIN TRVISIT tv2 ON v2.VISID = tv2.VISID WHERE tv2.TRAINEEID = trv.TRAINEEID) as PrevVist,

COUNT(*) OVER () as Total_Rows

FROM TRVISIT trv
LEFT JOIN VISITS v on trv.VISID = v.VISID

ORDER BY v.ACTUALDATE

Body:
There are a whole bunch of window functions that use the over clause, not limited to just the lag function. You can leverage those instead of resorting to multiple subqueries for each aggregation that you want.

The below answer should get you everything you're looking for.

select tv.traineeid
, v.plandate
, v.planenddate
, v.actualdate
, v.actualenddate
, count(v.visid) over (partition by tv.traineeid) as VisitCount
, sum(case when tv.visittype = 'R' then 1 else 0 end) over (partition by tv.traineeid) as ReviewCount
, min(v.actualdate) over (partition by tv.traineeid) as FirstVisit
, max(v.actualdate) over (partition by tv.traineeid) as LastVisit
, lag(v.actualdate, 1, NULL) over (partition by tv.traineeid order by v.actualdate asc) as PrevVisit
from trvisit as tv
left join visits as v on tv.visid = v.visid


问:
Javascript - Are DOM redraw methods synchronous?
In my question, DOM redraw methods are those that modifies the DOM and cause browser to redraw the page. For example:

```<code>const newChildNode = /*...*/;

document.body.appendChild(newChildNode);

const newHeight = document.body.scrollHeight;
</code>```

This code works fine under normal circumstances, but I am not so sure how it behaves under high pressure conditions, like when there are so many request to redraw the page. Can I assume that when document.body.scrollHeight is executed, newChildNode is already visible on screen?

答:
We can divide this "redraw" process in 3 parts, DOM update, Reflow, Repaint.

All these operations do not follow the same rules:

DOM update: Always synchronous. The DOM is just an other js object, and its manipulations methods are all synchronous.

Reflow: That's the strange beast you stumbled upon. This is the recalculation of all box positions of the elements on the page.

Generally, browsers will wait until you finished all DOM modifications, and thus, the end of the js stream, before triggering it.

But some DOM methods will force this operation, synchronously. e.g, all the HTMLElement.offsetXXX and alike properties, or Element.getBoundingClientRect,  or accessing in-doc's Node.innerText or accessing some properties of getComputedStyle returned object (, and probably others)  will trigger a synchronous reflow, in order to have the updated values. So beware when you use these methods/properties.

Repaint: When things are actually passed to the rendering engines.  Nothing in the specs says when this should happen. Most browsers will wait the next screen refresh, but it's not said it will always behave like that. e.g. Chrome is known for not triggering it when you blocked the scripts execution with alert(), while Firefox will.

Body:
In my question, DOM redraw methods are those that modifies the DOM and cause browser to redraw the page. For example:

const newChildNode = /*...*/;

document.body.appendChild(newChildNode);

const newHeight = document.body.scrollHeight;

This code works fine under normal circumstances, but I am not so sure how it behaves under high pressure conditions, like when there are so many request to redraw the page. Can I assume that when document.body.scrollHeight is executed, newChildNode is already visible on screen?


问:
Printing from a method
```<code>public class Simple2DArray {

    public static void main(String[] args) {

    }
    public static void fill()
    {
        int[][] grid = new int[5][5];
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                grid[r][c] = (int)(Math.random()*100);
            }
        }
    }
    public static int biggest(int[][] grid, int big)
    {
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                if(grid[r][c]> big)
                {
                    big = grid[r][c];
                }
            }
        }
        System.out.println(big);
        return big;
    }
}
</code>```

I would like for it to print big. How do I do this? I tried putting System.out.println(biggest(null,big) in the main method but that did not work.

答:
The following corrections need to be made:

fill needs to return grid.

biggest doesn't need big as a parameter (it makes little sense). It should start out as Integer.MIN_VALUE.

There's no need to print big within biggest.

In your for loop that loops through values of c, you should have c++ instead of r++.

public static int[][] fill()
{
    int[][] grid = new int[5][5];
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            grid[r][c] = (int)(Math.random()*100);
        }
    }
    return grid;
}

public static int biggest(int[][] grid)
{
    int big = Integer.MIN_VALUE;
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            if(grid[r][c]> big)
            {
                big = grid[r][c];
            }
        }
    }
    return big;
}
```

<p>Then you can call <code>biggest</code> on an actual two-dimensional array (<code>null</code> isn't an actual two-dimensional array):</p>

<pre class="lang-java prettyprint-override"><code>public static void main(String[] args)
{
    int[][] array = fill();
    System.out.println(biggest(array));
}
</code>```

Title: Printing from a method

Body:
public class Simple2DArray {

    public static void main(String[] args) {

    }
    public static void fill()
    {
        int[][] grid = new int[5][5];
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                grid[r][c] = (int)(Math.random()*100);
            }
        }
    }
    public static int biggest(int[][] grid, int big)
    {
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                if(grid[r][c]> big)
                {
                    big = grid[r][c];
                }
            }
        }
        System.out.println(big);
        return big;
    }
}

I would like for it to print big. How do I do this? I tried putting System.out.println(biggest(null,big) in the main method but that did not work.

Body:
The following corrections need to be made:

fill needs to return grid.

biggest doesn't need big as a parameter (it makes little sense). It should start out as Integer.MIN_VALUE.

There's no need to print big within biggest.

In your for loop that loops through values of c, you should have c++ instead of r++.

public static int[][] fill()
{
    int[][] grid = new int[5][5];
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            grid[r][c] = (int)(Math.random()*100);
        }
    }
    return grid;
}

public static int biggest(int[][] grid)
{
    int big = Integer.MIN_VALUE;
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            if(grid[r][c]> big)
            {
                big = grid[r][c];
            }
        }
    }
    return big;
}

Then you can call biggest on an actual two-dimensional array (null isn't an actual two-dimensional array):

public static void main(String[] args)
{
    int[][] array = fill();
    System.out.println(biggest(array));
}


问:
How to Execute AfterMehtod for only one Test method
I have to Test methods in my code and I wan to execute AfterMehtod for only one. Anybody have any idea how do this?

Here is My code:

```<code>package Demo;

import java.util.concurrent.TimeUnit;

import library.Utility;

import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import Pages.custom_actions_page;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class Custom_Actions extends start {

    ExtentReports report;
    ExtentTest logger;
    String driverPath = "D:\\geckodriver-v0.16.1-win64\\geckodriver.exe";

    @Test()
    public void signin() throws Exception {

        // To Locate the Username field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("username")).sendKeys("admin");

        // To locate the Password field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("password")).sendKeys("admin123");

        // Click on Login button
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("submit")).click();

    }

    @Test(dependsOnMethods = { "signin" })
    public void create_custom_action() {
        report = new ExtentReports("D:/Reports/Report.html");

        logger = report.startTest("Create Custom Action");

        new custom_actions_page(driver).submit();

        new custom_actions_page(driver).admin();

        new custom_actions_page(driver).custom_ac();

        new custom_actions_page(driver).createnew();

        new custom_actions_page(driver).nameAs("fortesting").descriptionAs(
                "description");

        new custom_actions_page(driver).category();

        new custom_actions_page(driver).assetsubtype();

        new custom_actions_page(driver).assettype();

        new custom_actions_page(driver).flintnameAs("hello:example.rb");

        new custom_actions_page(driver).submit_butto();

        new custom_actions_page(driver).Save_Button();

        logger.log(LogStatus.PASS, "Custom Action Created Successfully");
    }

    @AfterMethod()
    public void tearDown(ITestResult result) {

        // Here will compare if test is failing then only it will enter into if
        // condition
        if (ITestResult.FAILURE == result.getStatus()) {
            try {

                Utility.captureScreenshot(driver, "CustomActionFail.png");

            } catch (Exception e) {
                System.out.println("Exception while taking screenshot "
                        + e.getMessage());
            }
        }

        report.endTest(logger);
        report.flush();
        driver.close();
    }}
</code>```

答:
There are a couple of ways of doing it using what is called as Native Injection within TestNG. For more details on what is the possible combinations for native injection in TestNG please refer here.

The simplest way would be to inspect the name of the @Test method that is about to be executed, from within your @AfterMethod annotated method, and if it matches the name of the method for which you need special execution, you proceed further, else you skip executing the @AfterMethod.
But this is a primitive approach, because if you refactor your test method's name to something else, your approach gets broken.

The other approach is to basically work with a marker interface and do the same logic as described above

Here's a sample that shows all this in action.

The marker annotation would look like below

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(java.lang.annotation.ElementType.METHOD)
public @interface NeedsSpecialSetup {
}
```

<p>Now your test class would look like below</p>

<p></p>

```import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.lang.reflect.Method;

public class SampleTestClass {

    @NeedsSpecialSetup
    @Test
    public void testMethod1() {
        System.err.println("Executing testMethod1()");
    }

    @Test
    public void testMethod2() {
        System.err.println("Executing testMethod2()");
    }

    @AfterMethod
    public void afterMethod(Method method) {
        NeedsSpecialSetup needsSpecialSetup = method.getAnnotation(NeedsSpecialSetup.class);
        if (needsSpecialSetup == null) {
            //Don't execute this setup because the method doesn't have the
            //special setup annotation.
            return;
        }
        System.err.println("Running special setup for " + method.getName() + "()");
    }
}
```

<p>Notice how we have added the annotation <code>@NeedsSpecialSetup</code> only for the method <code>testMethod1()</code> to indicate that we need the <code>@AfterMethod</code> to be executed only for <code>testMethod1()</code>.</p>

<p>Here's the output</p>

```Executing testMethod1()

Running special setup for testMethod1()
Executing testMethod2()

===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
```

Body:
I have to Test methods in my code and I wan to execute AfterMehtod for only one. Anybody have any idea how do this?

Here is My code:

package Demo;

import java.util.concurrent.TimeUnit;

import library.Utility;

import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import Pages.custom_actions_page;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class Custom_Actions extends start {

    ExtentReports report;
    ExtentTest logger;
    String driverPath = "D:\\geckodriver-v0.16.1-win64\\geckodriver.exe";

    @Test()
    public void signin() throws Exception {

        // To Locate the Username field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("username")).sendKeys("admin");

        // To locate the Password field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("password")).sendKeys("admin123");

        // Click on Login button
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("submit")).click();

    }

    @Test(dependsOnMethods = { "signin" })
    public void create_custom_action() {
        report = new ExtentReports("D:/Reports/Report.html");

        logger = report.startTest("Create Custom Action");

        new custom_actions_page(driver).submit();

        new custom_actions_page(driver).admin();

        new custom_actions_page(driver).custom_ac();

        new custom_actions_page(driver).createnew();

        new custom_actions_page(driver).nameAs("fortesting").descriptionAs(
                "description");

        new custom_actions_page(driver).category();

        new custom_actions_page(driver).assetsubtype();

        new custom_actions_page(driver).assettype();

        new custom_actions_page(driver).flintnameAs("hello:example.rb");

        new custom_actions_page(driver).submit_butto();

        new custom_actions_page(driver).Save_Button();

        logger.log(LogStatus.PASS, "Custom Action Created Successfully");
    }

    @AfterMethod()
    public void tearDown(ITestResult result) {

        // Here will compare if test is failing then only it will enter into if
        // condition
        if (ITestResult.FAILURE == result.getStatus()) {
            try {

                Utility.captureScreenshot(driver, "CustomActionFail.png");

            } catch (Exception e) {
                System.out.println("Exception while taking screenshot "
                        + e.getMessage());
            }
        }

        report.endTest(logger);
        report.flush();
        driver.close();
    }}

Body:
There are a couple of ways of doing it using what is called as Native Injection within TestNG. For more details on what is the possible combinations for native injection in TestNG please refer here.

The simplest way would be to inspect the name of the @Test method that is about to be executed, from within your @AfterMethod annotated method, and if it matches the name of the method for which you need special execution, you proceed further, else you skip executing the @AfterMethod.
But this is a primitive approach, because if you refactor your test method's name to something else, your approach gets broken.

The other approach is to basically work with a marker interface and do the same logic as described above

Here's a sample that shows all this in action.

The marker annotation would look like below

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(java.lang.annotation.ElementType.METHOD)
public @interface NeedsSpecialSetup {
}

Now your test class would look like below

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.lang.reflect.Method;

public class SampleTestClass {

    @NeedsSpecialSetup
    @Test
    public void testMethod1() {
        System.err.println("Executing testMethod1()");
    }

    @Test
    public void testMethod2() {
        System.err.println("Executing testMethod2()");
    }

    @AfterMethod
    public void afterMethod(Method method) {
        NeedsSpecialSetup needsSpecialSetup = method.getAnnotation(NeedsSpecialSetup.class);
        if (needsSpecialSetup == null) {
            //Don't execute this setup because the method doesn't have the
            //special setup annotation.
            return;
        }
        System.err.println("Running special setup for " + method.getName() + "()");
    }
}

Notice how we have added the annotation @NeedsSpecialSetup only for the method testMethod1() to indicate that we need the @AfterMethod to be executed only for testMethod1().

Here's the output

Executing testMethod1()

Running special setup for testMethod1()
Executing testMethod2()

===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================


问:
Collection to 2d list in Python
I am trying to pass a MongoDB collection to a python 2d list. I need for each sublist to contain only the values of each key within the document. For example, if the MongoDB documents are:

```<code>{
   _id: ObjectId("5099803df3f4948bd2f98392"),
   name: 'marie',
   age: '23',
   gender: 'female'
}
</code>```

and

```<code>{
   _id: ObjectId("5099803df3f4948bd2f98391"),
   name: 'john',
   age: '43',
   gender: 'male'
}
</code>```

I need to get something like:

```<code>[
  [ObjectId("5099803df3f4948bd2f98392"), 'marie', '23', 'female],
  [ObjectId("5099803df3f4948bd2f98391"), 'john', '43', 'male']
]
</code>```

I am new to MongoDB and PyMongo. For now, the closest I have been able to do is something like this:

```<code>people = mongo.db.population
people_key_list = ['_id', 'name', 'age', 'gender']
people_list = []

for item in people.find():
    people_list.append(item)
</code>```

But the structure of the results are not really what I need:

```<code>[
  ['ObjectId("5099803df3f4948bd2f98392")','ObjectId("5099803df3f4948bd2f98391")'],
  ['marie','john'],['23','43'],['female','male']
]
</code>```

I could rotate the 2d list, but I am sure there should be a way to generate the structure I need efficiently from the start... but can't figure out how.

答:
You already have people_key_list defined with the names of the keys, so just do a map over that list and extract the values:

```<code>from pymongo import MongoClient
from bson import ObjectId

data = [
  {
    '_id': ObjectId("5099803df3f4948bd2f98392"),
    'name': 'marie',
    'age': '23',
    'gender': 'female'
  },
  {
    '_id': ObjectId("5099803df3f4948bd2f98391"),
    'name': 'john',
    'age': '43',
    'gender': 'male'
  }
]

client = MongoClient();
db = client['test']

db.population.remove({})
db.population.insert_many(data)

people_key_list = ['_id', 'name', 'age', 'gender']
people_list = []

for person in db.population.find():
  people_list.append(map(lambda k: person[k],people_key_list))

print(people_list)
</code>```

Or even just nest the map for that matter:

```<code>people_list = map(lambda person:
  map(lambda k: person[k],people_key_list),
  db.population.find()
)
</code>```

Either would return:

```<code>[
  [ObjectId('5099803df3f4948bd2f98392'), u'marie', u'23', u'female'],
  [ObjectId('5099803df3f4948bd2f98391'), u'john', u'43', u'male']
]
</code>```

Title: Collection to 2d list in Python

Body:
I am trying to pass a MongoDB collection to a python 2d list. I need for each sublist to contain only the values of each key within the document. For example, if the MongoDB documents are:

{
   _id: ObjectId("5099803df3f4948bd2f98392"),
   name: 'marie',
   age: '23',
   gender: 'female'
}

and

{
   _id: ObjectId("5099803df3f4948bd2f98391"),
   name: 'john',
   age: '43',
   gender: 'male'
}

I need to get something like:

[
  [ObjectId("5099803df3f4948bd2f98392"), 'marie', '23', 'female],
  [ObjectId("5099803df3f4948bd2f98391"), 'john', '43', 'male']
]

I am new to MongoDB and PyMongo. For now, the closest I have been able to do is something like this:

people = mongo.db.population
people_key_list = ['_id', 'name', 'age', 'gender']
people_list = []

for item in people.find():
    people_list.append(item)

But the structure of the results are not really what I need:

[
  ['ObjectId("5099803df3f4948bd2f98392")','ObjectId("5099803df3f4948bd2f98391")'],
  ['marie','john'],['23','43'],['female','male']
]

I could rotate the 2d list, but I am sure there should be a way to generate the structure I need efficiently from the start... but can't figure out how.

Body:
You already have people_key_list defined with the names of the keys, so just do a map over that list and extract the values:

from pymongo import MongoClient
from bson import ObjectId

data = [
  {
    '_id': ObjectId("5099803df3f4948bd2f98392"),
    'name': 'marie',
    'age': '23',
    'gender': 'female'
  },
  {
    '_id': ObjectId("5099803df3f4948bd2f98391"),
    'name': 'john',
    'age': '43',
    'gender': 'male'
  }
]

client = MongoClient();
db = client['test']

db.population.remove({})
db.population.insert_many(data)

people_key_list = ['_id', 'name', 'age', 'gender']
people_list = []

for person in db.population.find():
  people_list.append(map(lambda k: person[k],people_key_list))

print(people_list)

Or even just nest the map for that matter:

people_list = map(lambda person:
  map(lambda k: person[k],people_key_list),
  db.population.find()
)

Either would return:

[
  [ObjectId('5099803df3f4948bd2f98392'), u'marie', u'23', u'female'],
  [ObjectId('5099803df3f4948bd2f98391'), u'john', u'43', u'male']
]


问:
Get name of currently executing test in JUnit 4
In JUnit 3, I could get the name of the currently running test like this:

```<code>public class MyTest extends TestCase
{
    public void testSomething()
    {
        System.out.println("Current test is " + getName());
        ...
    }
}
</code>```

which would print "Current test is testSomething".

Is there any out-of-the-box or simple way to do this in JUnit 4?

Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.

答: JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).</p>

OwnerDisplayName: Dave Ray

ContentLicense: CC BY-SA 4.0

Body:
In JUnit 3, I could get the name of the currently running test like this:

public class MyTest extends TestCase
{
    public void testSomething()
    {
        System.out.println("Current test is " + getName());
        ...
    }
}

which would print "Current test is testSomething".

Is there any out-of-the-box or simple way to do this in JUnit 4?

Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.

LastEditorDisplayName: Dave Ray

ContentLicense: CC BY-SA 2.5


问:
Passing custom class objects using parcelable
How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

```<code>class A implements Parcelable{
      private CustomClass B;
}
</code>```

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module

答:
In your comment you say that CustomClass is made of 4 integer variables. You could therefore do something like this:

```<code>class A implements Parcelable {

    private CustomClass B;

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(B.getFirst());
        dest.writeInt(B.getSecond());
        dest.writeInt(B.getThird());
        dest.writeInt(B.getFourth());
    }

    private A(Parcel in) {
        B = new CustomClass();
        B.setFirst(dest.readInt());
        B.setSecond(dest.readInt());
        B.setThird(dest.readInt());
        B.setFourth(dest.readInt());
    }
}
</code>```

Body:
How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

class A implements Parcelable{
      private CustomClass B;
}

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module

Body:
In your comment you say that CustomClass is made of 4 integer variables. You could therefore do something like this:

class A implements Parcelable {

    private CustomClass B;

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(B.getFirst());
        dest.writeInt(B.getSecond());
        dest.writeInt(B.getThird());
        dest.writeInt(B.getFourth());
    }

    private A(Parcel in) {
        B = new CustomClass();
        B.setFirst(dest.readInt());
        B.setSecond(dest.readInt());
        B.setThird(dest.readInt());
        B.setFourth(dest.readInt());
    }
}


问:
Is it possible to generate Typescript interfaces from files with a webpack loader?
I am attempting to create a webpack loader that converts a file containing a description of API data structures into a set of TypeScript interfaces.

In my concrete case, the file is JSON, but this should be ultimately irrelevant — the file is only a shared source of data describing the interaction between web application backend(s) and frontend(s). In my MCVE below, you can see that the JSON file contains an empty object to underscore how the type and contents of the file do not matter to the problem.

My current attempt reports two errors (I assume the second is caused by the first):

[at-loader]: Child process failed to process the request:  Error: Could not find file: '/private/tmp/ts-loader/example.api'.
```

<pre class="lang-none prettyprint-override"><code>ERROR in ./example.api
Module build failed: Error: Final loader didn't return a Buffer or String
</code>```

How can I generate TypeScript code using a webpack loader?

package.json

```<code>{
  "name": "so-example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}
</code>```

webpack.config.js

```<code>const path = require('path');

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'output.js',
  },
  resolveLoader: {
    alias: {
      'my-own-loader': path.resolve(__dirname, "my-own-loader.js"),
    },
  },
  module: {
    rules: [
      {
        test: /\.api$/,
        exclude: /node_modules/,
        use: ["awesome-typescript-loader", "my-own-loader"],
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: "awesome-typescript-loader",
      },
    ]
  },
};
</code>```

my-own-loader.js

```<code>module.exports = function(source) {
  return `
interface DummyContent {
    name: string;
    age?: number;
}
`;
};
</code>```

index.ts

```<code>import * as foo from './example';

console.log(foo);
</code>```

example.api

```<code>{}
</code>```

I recognize that there are other code generation techniques. For example, I could convert my JSON files to TypeScript with some build tool and check them in. I'm looking for a more dynamic solution.

my-own-loader.js does not export json but string.

That's correct, much like loading an image file doesn't always export binary data but sometimes outputs a JavaScript data structure representing metadata about the image.

Why you need to define the typescript interfaces from json file? Would the interfaces be used for typescript compilation?

Yes. I want to import a file that describes my API data structures and automatically generate corresponding TypeScript interfaces. Having a shared file allows the frontend(s) and backend(s) to always agree on what data will be present.

答:
First off, kudos for providing an MCVE.  This is a really interesting question.  The code I worked with to put this answer together is based on said MCVE, and is available here.

Missing File?

This is a most unhelpful error message indeed. The file is clearly in that location, but TypeScript will refuse to load anything that doesn't have an acceptable extension.

This error is essentially hiding the real error, which is

TS6054: File 'c:/path/to/project/example.api' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'.
```

<p>This can be verified by hacking into <code>typescript.js</code>, and manually adding the file.  It's ugly, as detective work often is (starts at line 95141 in v2.6.1):</p>

```for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
    var fileName = rootFileNames_1[_i];
    this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
}
this.createEntry("c:/path/to/project/example.api", ts.toPath("c:/path/to/project/example.api", this.currentDirectory, getCanonicalFileName));
```

<p>Conceptually, you're just passing a string between loaders, but it turns out the file name <strong>is</strong> important here.</p>

<p><strong>A possible fix</strong></p>

<p>I didn't see a way to do this with <code>awesome-typescript-loader</code>, but if you're willing to use <code>ts-loader</code> instead, you can certainly generate TypeScript from files with arbitrary extensions, compile that TypeScript, and inject it into your <code>output.js</code>.</p>

<p><code>ts-loader</code> has an <code>appendTsSuffixTo</code> option, that can be used to work around the well-known file extension pain.  Your webpack config might look something like this if you went that route:</p>

```rules: [
  {
    test: /\.api$/,
    exclude: /node_modules/,
    use: [
      { loader: "ts-loader" },
      { loader: "my-own-loader" }
    ]
  },
  {
    test: /\.tsx?$/,
    exclude: /node_modules/,
    loader: "ts-loader",
    options: {
      appendTsSuffixTo: [/\.api$/]
    }
  }
]
```

<p><strong>Note on interfaces and DX</strong></p>

<p>Interfaces are erased by the compiler.  This can be demonstrated by running <code>tsc</code> against something like this</p>

```interface DummyContent {
    name: string;
    age?: number;
}
```

<p>vs. this</p>

```interface DummyContent {
    name: string;
    age?: number;
}

class DummyClass {
    printMessage = () => {
        console.log("message");
    }
}

var dummy = new DummyClass();
dummy.printMessage();
```

In order to provide a nice developer experience, you may need to write these interfaces to a file in the dev environment only.  You don't need to write them out for a production build, and you don't need (or want) to check them into version control.

Developers probably need to have them written out so their IDE has something to sink its teeth into.  You might add *.api.ts to .gitignore, and keep them out of the repository, but I suspect they'll need to exist in the developers' workspaces.

For example, in my sample repo, a new developer would have to run npm install (as usual) and npm run build (to generate the interfaces in their local environment) to get rid of all their red squigglies.

Body:
I am attempting to create a webpack loader that converts a file containing a description of API data structures into a set of TypeScript interfaces.

In my concrete case, the file is JSON, but this should be ultimately irrelevant — the file is only a shared source of data describing the interaction between web application backend(s) and frontend(s). In my MCVE below, you can see that the JSON file contains an empty object to underscore how the type and contents of the file do not matter to the problem.

My current attempt reports two errors (I assume the second is caused by the first):

[at-loader]: Child process failed to process the request:  Error: Could not find file: '/private/tmp/ts-loader/example.api'.

ERROR in ./example.api
Module build failed: Error: Final loader didn't return a Buffer or String

How can I generate TypeScript code using a webpack loader?

package.json

{
  "name": "so-example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'output.js',
  },
  resolveLoader: {
    alias: {
      'my-own-loader': path.resolve(__dirname, "my-own-loader.js"),
    },
  },
  module: {
    rules: [
      {
        test: /\.api$/,
        exclude: /node_modules/,
        use: ["awesome-typescript-loader", "my-own-loader"],
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: "awesome-typescript-loader",
      },
    ]
  },
};

my-own-loader.js

module.exports = function(source) {
  return `
interface DummyContent {
    name: string;
    age?: number;
}
`;
};

index.ts

import * as foo from './example';

console.log(foo);

example.api

{}

I recognize that there are other code generation techniques. For example, I could convert my JSON files to TypeScript with some build tool and check them in. I'm looking for a more dynamic solution.

my-own-loader.js does not export json but string.

That's correct, much like loading an image file doesn't always export binary data but sometimes outputs a JavaScript data structure representing metadata about the image.

Why you need to define the typescript interfaces from json file? Would the interfaces be used for typescript compilation?

Yes. I want to import a file that describes my API data structures and automatically generate corresponding TypeScript interfaces. Having a shared file allows the frontend(s) and backend(s) to always agree on what data will be present.

Body:
First off, kudos for providing an MCVE.  This is a really interesting question.  The code I worked with to put this answer together is based on said MCVE, and is available here.

Missing File?

This is a most unhelpful error message indeed. The file is clearly in that location, but TypeScript will refuse to load anything that doesn't have an acceptable extension.

This error is essentially hiding the real error, which is

TS6054: File 'c:/path/to/project/example.api' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts', '.js', '.jsx'.

This can be verified by hacking into typescript.js, and manually adding the file.  It's ugly, as detective work often is (starts at line 95141 in v2.6.1):

for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
    var fileName = rootFileNames_1[_i];
    this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName));
}
this.createEntry("c:/path/to/project/example.api", ts.toPath("c:/path/to/project/example.api", this.currentDirectory, getCanonicalFileName));

Conceptually, you're just passing a string between loaders, but it turns out the file name is important here.

A possible fix

I didn't see a way to do this with awesome-typescript-loader, but if you're willing to use ts-loader instead, you can certainly generate TypeScript from files with arbitrary extensions, compile that TypeScript, and inject it into your output.js.

ts-loader has an appendTsSuffixTo option, that can be used to work around the well-known file extension pain.  Your webpack config might look something like this if you went that route:

rules: [
  {
    test: /\.api$/,
    exclude: /node_modules/,
    use: [
      { loader: "ts-loader" },
      { loader: "my-own-loader" }
    ]
  },
  {
    test: /\.tsx?$/,
    exclude: /node_modules/,
    loader: "ts-loader",
    options: {
      appendTsSuffixTo: [/\.api$/]
    }
  }
]

Note on interfaces and DX

Interfaces are erased by the compiler.  This can be demonstrated by running tsc against something like this

interface DummyContent {
    name: string;
    age?: number;
}

vs. this

interface DummyContent {
    name: string;
    age?: number;
}

class DummyClass {
    printMessage = () => {
        console.log("message");
    }
}

var dummy = new DummyClass();
dummy.printMessage();

In order to provide a nice developer experience, you may need to write these interfaces to a file in the dev environment only.  You don't need to write them out for a production build, and you don't need (or want) to check them into version control.

Developers probably need to have them written out so their IDE has something to sink its teeth into.  You might add *.api.ts to .gitignore, and keep them out of the repository, but I suspect they'll need to exist in the developers' workspaces.

For example, in my sample repo, a new developer would have to run npm install (as usual) and npm run build (to generate the interfaces in their local environment) to get rid of all their red squigglies.


问:
Trying to concatenate strings and add integers to a sum separately
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected</p>

```<code>l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int
</code>```

答:
use isinstance function instead of type.
Tested code here:</p>

```<code>l = ['magical unicorns', 19, 'hello', 98.98, 'world']
con=''
sum=0
for i in l:
    print (i)
    if isinstance(i, str):
       con = con+str(i)
    elif isinstance(i, int):
       sum = sum+i
    else:
       pass
print (con)
print (sum)
</code>```

Body:
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected

l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int

Body:
use isinstance function instead of type.
Tested code here:

l = ['magical unicorns', 19, 'hello', 98.98, 'world']
con=''
sum=0
for i in l:
    print (i)
    if isinstance(i, str):
       con = con+str(i)
    elif isinstance(i, int):
       sum = sum+i
    else:
       pass
print (con)
print (sum)


问:
How to capitalise the first letter of each word after reversing a string
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.</p>

```<code>function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}
</code>```

答:
// Input.
const before = 'hello WORLD'
console.log(`Before: ${before}`)

// Conversion.
const lowercase = before.toLowerCase()
const reversed = [...lowercase].reverse()
const capitalised = reversed.map((character, index) => {
  const isFirstCharacter = (index === 0)
  const isAfterWhiteSpace = isFirstCharacter ? false : (reversed[index-1] === ' ')
  if (isFirstCharacter || isAfterWhiteSpace) return character.toUpperCase()
  return character
})

// Output + Proof.
const after = capitalised.join('')
console.log(`After: ${after}`)```

Body:
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}


问:
Error: Can't set headers after they are sent while reading files
I'm getting below error while trying to read file and sending the response back to browser.

```<code>[ 'Error: Can\'t set headers after they are sent.',
  '    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)',
  '    at ServerResponse.setWriteHeadHeaders (/somepath/node_modules/on-headers/index.js:82:19)',
  '    at ServerResponse.writeHead (/somepath/node_modules/on-headers/index.js:41:36)',
  '    at /somepath/server/custom.js:71:13',
  '    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)' ]
</code>```

var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
 if(req.params._pagename === 'Test123')
 {
      fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 if(req.params._pagename === 'SecondFile')
 {
      fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 else {
  fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
};```

Interestingly I'm seeing the above error only when reading 1st file (Test123.txt) and no issue when reading "SecondFile.txt".

Appreciate any help on resolving this!

答:
It's amazing that the if..else if.. is actually a problem. Am sure both the conditions can never be true.

I thought of a more succinct approach.

A simpler code:

```<code>var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
    let pagename = req.params.pagename;

    if (pagename !== 'Test123' || pagename !== 'Secondfile') pagename = 'InActive';

    fs.readFile(`/somepath/${pagename}.txt`, 'utf-8', function(err, data) {
    if (err) return console.log(err);
    res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
    return res.end(data);
    });
};
</code>```

Body:
I'm getting below error while trying to read file and sending the response back to browser.

[ 'Error: Can\'t set headers after they are sent.',
  '    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)',
  '    at ServerResponse.setWriteHeadHeaders (/somepath/node_modules/on-headers/index.js:82:19)',
  '    at ServerResponse.writeHead (/somepath/node_modules/on-headers/index.js:41:36)',
  '    at /somepath/server/custom.js:71:13',
  '    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)' ]

var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
 if(req.params._pagename === 'Test123')
 {
      fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 if(req.params._pagename === 'SecondFile')
 {
      fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 else {
  fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
};

Interestingly I'm seeing the above error only when reading 1st file (Test123.txt) and no issue when reading "SecondFile.txt".

Appreciate any help on resolving this!

Body:
It's amazing that the if..else if.. is actually a problem. Am sure both the conditions can never be true.

I thought of a more succinct approach.

A simpler code:

var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
    let pagename = req.params.pagename;

    if (pagename !== 'Test123' || pagename !== 'Secondfile') pagename = 'InActive';

    fs.readFile(`/somepath/${pagename}.txt`, 'utf-8', function(err, data) {
    if (err) return console.log(err);
    res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
    return res.end(data);
    });
};


问:
How do I add a general Google Search bar into an HTML page in a Google Chrome Extension?
I have made a New Tab Google Chrome extension and I am currently writing the HTML code. However, I need to add a Google Search bar to the code. How do I do that not using Google Custom Search, but just the general searching?</p>

答:
EDIT: The following example doesn't work. Check the codepen here

You can create your own form or input tag and have it some javascript redirect the user to the Google page with the search query

<form id=search action="https://www.google.com/search" method="get">
  <input type="search" name="q" />
  <input type="submit"/>
</form>```

The html code above will show the google webpage with the search results.

Body:
EDIT: The following example doesn't work. Check the codepen here

You can create your own form or input tag and have it some javascript redirect the user to the Google page with the search query

<form id=search action="https://www.google.com/search" method="get">
  <input type="search" name="q" />
  <input type="submit"/>
</form>

The html code above will show the google webpage with the search results.


问:
How to generate random numbers in many ranges
I am wondering how to generate random numbers in the following way in R:

```<code> randomly choose 1 number between 1 and 15
 randomly choose 1 number between 16 and 30
 ...
 randomly choose 1 number between 86 and 100
</code>```

I know that I can do this with a loop but I am wondering if there is any non-loop way to do this. I tried to google around but didn't find much helpful.

答:
We can write a function using sapply and sample in the following way

```<code>select_1_number_in_range <- function(start, stop, interval) {
  sapply(seq(start, stop, interval), function(x) sample(x:(x+interval-1), 1))
}

set.seed(31)
select_1_number_in_range(1, 100, 15)

#[1]   9  31  37  52  76  83 104
</code>```

We generate a sequence between the range with the interval as by argument and select one number from each list.

Note : 100 is not divisible by 15 so this gets extended till 105.

Body:
I am wondering how to generate random numbers in the following way in R:

 randomly choose 1 number between 1 and 15
 randomly choose 1 number between 16 and 30
 ...
 randomly choose 1 number between 86 and 100

I know that I can do this with a loop but I am wondering if there is any non-loop way to do this. I tried to google around but didn't find much helpful.

Body:
We can write a function using sapply and sample in the following way

select_1_number_in_range <- function(start, stop, interval) {
  sapply(seq(start, stop, interval), function(x) sample(x:(x+interval-1), 1))
}

set.seed(31)
select_1_number_in_range(1, 100, 15)

#[1]   9  31  37  52  76  83 104

We generate a sequence between the range with the interval as by argument and select one number from each list.

Note : 100 is not divisible by 15 so this gets extended till 105.


问:
Jenkinsfile docker agent step dies after 1 second
I have a very simple Jenkinsfile as seen below.

```<code>def workspace
node {
    workspace = sh(returnStdout: true, script: 'pwd').trim()
}

pipeline {
    agent none
    stages {
        stage('Back-end') {
            agent {
                docker {
                    image 'composer'
                    args "-v /var/lib/jenkins/.composer/auth.json:/.composer/auth.json -v $workspace:/app"
                }
            }
            steps {
                sh 'php -v'
                sh 'composer install --no-interaction --working-dir=$WORKSPACE/backend'
            }
        }
    }
}
</code>```

I've gotten to the point where this works entirely as intended (e.g.: mounts volumes as expected, moves things around, pulls image, actually runs composer install), with one minor exception...

The immediately following the docker run it gets into the shell steps, runs sh 'composer install...' and dies after 1 second, going into the docker stop --time 1 ... and docker rm ... steps immediately after.

I have no idea if this is coming from Composer doing something odd, or if there's some configurable timeout I'm completely unaware of.

Has anyone dealt with this before?

Edit:

Here is more information:

```<code>[Pipeline] withDockerContainer
Jenkins does not seem to be running inside a container
$ docker run -t -d -u 997:995 -v /var/lib/jenkins/.composer/auth.json:/.composer/auth.json -v [...] -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** --entrypoint cat composer
[Pipeline] {
[Pipeline] sh
[workspace] Running shell script
+ php -v
PHP 7.1.9 (cli) (built: Sep 15 2017 00:07:01) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
[Pipeline] sh
[workspace] Running shell script
+ composer install --no-interaction --working-dir=/app/backend --no-progress --no-ansi
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 29 installs, 0 updates, 0 removals
  - Installing laravel/tinker (v1.0.2): Downloading[Pipeline] }
$ docker stop --time=1 ee693aaa7cdde41b714fdc91dbc1b05ac07fe2be7904ab1ed528fb0a3f771047
$ docker rm -f ee693aaa7cdde41b714fdc91dbc1b05ac07fe2be7904ab1ed528fb0a3f771047
[Pipeline] // withDockerContainer
[Pipeline] }
</code>```

and from an earlier job

```<code>Installing dependencies (including require-dev) from lock file
Package operations: 55 installs, 0 updates, 0 removals
  - Installing symfony/finder (v3.3.6): Downloading (connecting...)[Pipeline] }
</code>```

It's working as can be seen, but the return code at the end is....

```<code>GitHub has been notified of this commit’s build result

ERROR: script returned exit code -1
Finished: FAILURE
</code>```

Edit 2:

Got this to work even simpler, see gist for more info:

https://gist.github.com/chuckyz/6b78b19a6a5ea418afa16cc58020096e

答:
I experienced this and resolved it by upgrading durable-task-plugin from 1.13 to 1.16.

The 1.16 changelog contains:

Using a new system for determining whether sh step processes are still alive, which should solve various robustness issues.

Body:
I have a very simple Jenkinsfile as seen below.

def workspace
node {
    workspace = sh(returnStdout: true, script: 'pwd').trim()
}

pipeline {
    agent none
    stages {
        stage('Back-end') {
            agent {
                docker {
                    image 'composer'
                    args "-v /var/lib/jenkins/.composer/auth.json:/.composer/auth.json -v $workspace:/app"
                }
            }
            steps {
                sh 'php -v'
                sh 'composer install --no-interaction --working-dir=$WORKSPACE/backend'
            }
        }
    }
}

I've gotten to the point where this works entirely as intended (e.g.: mounts volumes as expected, moves things around, pulls image, actually runs composer install), with one minor exception...

The immediately following the docker run it gets into the shell steps, runs sh 'composer install...' and dies after 1 second, going into the docker stop --time 1 ... and docker rm ... steps immediately after.

I have no idea if this is coming from Composer doing something odd, or if there's some configurable timeout I'm completely unaware of.

Has anyone dealt with this before?

Edit:

Here is more information:

[Pipeline] withDockerContainer
Jenkins does not seem to be running inside a container
$ docker run -t -d -u 997:995 -v /var/lib/jenkins/.composer/auth.json:/.composer/auth.json -v [...] -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** --entrypoint cat composer
[Pipeline] {
[Pipeline] sh
[workspace] Running shell script
+ php -v
PHP 7.1.9 (cli) (built: Sep 15 2017 00:07:01) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
[Pipeline] sh
[workspace] Running shell script
+ composer install --no-interaction --working-dir=/app/backend --no-progress --no-ansi
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 29 installs, 0 updates, 0 removals
  - Installing laravel/tinker (v1.0.2): Downloading[Pipeline] }
$ docker stop --time=1 ee693aaa7cdde41b714fdc91dbc1b05ac07fe2be7904ab1ed528fb0a3f771047
$ docker rm -f ee693aaa7cdde41b714fdc91dbc1b05ac07fe2be7904ab1ed528fb0a3f771047
[Pipeline] // withDockerContainer
[Pipeline] }

and from an earlier job

Installing dependencies (including require-dev) from lock file
Package operations: 55 installs, 0 updates, 0 removals
  - Installing symfony/finder (v3.3.6): Downloading (connecting...)[Pipeline] }

It's working as can be seen, but the return code at the end is....

GitHub has been notified of this commit’s build result

ERROR: script returned exit code -1
Finished: FAILURE

Edit 2:

Got this to work even simpler, see gist for more info:

https://gist.github.com/chuckyz/6b78b19a6a5ea418afa16cc58020096e


问:
Deleting nested array entries in a DataFrame (JSON) on a condition
I read in a DataFrame with a huge file holding on each line of it a JSON object as follows:

```<code>{
  "userId": "12345",
  "vars": {
    "test_group": "group1",
    "brand": "xband"
  },
  "modules": [
    {
      "id": "New"
    },
    {
      "id": "Default"
    },
    {
      "id": "BestValue"
    },
    {
      "id": "Rating"
    },
    {
      "id": "DeliveryMin"
    },
    {
      "id": "Distance"
    }
  ]
}
</code>```

How could I manipulate in such way the DataFrame, to keep only the module with id="Default" ? How to just delete all the other, if id does not equal "Default"?

答:
As you said you have json format given in question in each line as

```<code>{"userId":"12345","vars":{"test_group":"group1","brand":"xband"},"modules":[{"id":"New"},{"id":"Default"},{"id":"BestValue"},{"id":"Rating"},{"id":"DeliveryMin"},{"id":"Distance"}]}
{"userId":"12345","vars":{"test_group":"group1","brand":"xband"},"modules":[{"id":"New"},{"id":"Default"},{"id":"BestValue"},{"id":"Rating"},{"id":"DeliveryMin"},{"id":"Distance"}]}
</code>```

If thats true then you can use sqlContext's json api to read the json file to dataframe as below

```<code>val df = sqlContext.read.json("path to json file")
</code>```

which should give you dataframe as

```<code>+--------------------------------------------------------------------+------+--------------+
|modules                                                             |userId|vars          |
+--------------------------------------------------------------------+------+--------------+
|[[New], [Default], [BestValue], [Rating], [DeliveryMin], [Distance]]|12345 |[xband,group1]|
|[[New], [Default], [BestValue], [Rating], [DeliveryMin], [Distance]]|12345 |[xband,group1]|
+--------------------------------------------------------------------+------+--------------+
</code>```

and schema be

```<code>root
 |-- modules: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |-- userId: string (nullable = true)
 |-- vars: struct (nullable = true)
 |    |-- brand: string (nullable = true)
 |    |-- test_group: string (nullable = true)
</code>```

Final step would be to filter only the modules.id with Default as value

```<code>val finaldf = df.withColumn("modules", explode($"modules.id"))
    .filter($"modules" === "Default")
</code>```

which should give you

```<code>+-------+------+--------------+
|modules|userId|vars          |
+-------+------+--------------+
|Default|12345 |[xband,group1]|
|Default|12345 |[xband,group1]|
+-------+------+--------------+
</code>```

I hope the answer is helpful

Updated

this would create json as

```<code>{"modules":"Default","userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
{"modules":"Default","userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
</code>```

But if your requirement is to get as below

```<code>{"modules":{"id":"Default"},"userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
{"modules":{"id":"Default"},"userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
</code>```

You should be exploding the modules and not modules.id

```<code>val finaldf = df.withColumn("modules", explode($"modules"))
    .filter($"modules.id" === "Default")
</code>```

Body:
I read in a DataFrame with a huge file holding on each line of it a JSON object as follows:

{
  "userId": "12345",
  "vars": {
    "test_group": "group1",
    "brand": "xband"
  },
  "modules": [
    {
      "id": "New"
    },
    {
      "id": "Default"
    },
    {
      "id": "BestValue"
    },
    {
      "id": "Rating"
    },
    {
      "id": "DeliveryMin"
    },
    {
      "id": "Distance"
    }
  ]
}

How could I manipulate in such way the DataFrame, to keep only the module with id="Default" ? How to just delete all the other, if id does not equal "Default"?

Body:
As you said you have json format given in question in each line as

{"userId":"12345","vars":{"test_group":"group1","brand":"xband"},"modules":[{"id":"New"},{"id":"Default"},{"id":"BestValue"},{"id":"Rating"},{"id":"DeliveryMin"},{"id":"Distance"}]}
{"userId":"12345","vars":{"test_group":"group1","brand":"xband"},"modules":[{"id":"New"},{"id":"Default"},{"id":"BestValue"},{"id":"Rating"},{"id":"DeliveryMin"},{"id":"Distance"}]}

If thats true then you can use sqlContext's json api to read the json file to dataframe as below

val df = sqlContext.read.json("path to json file")

which should give you dataframe as

+--------------------------------------------------------------------+------+--------------+
|modules                                                             |userId|vars          |
+--------------------------------------------------------------------+------+--------------+
|[[New], [Default], [BestValue], [Rating], [DeliveryMin], [Distance]]|12345 |[xband,group1]|
|[[New], [Default], [BestValue], [Rating], [DeliveryMin], [Distance]]|12345 |[xband,group1]|
+--------------------------------------------------------------------+------+--------------+

and schema be

root
 |-- modules: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |-- userId: string (nullable = true)
 |-- vars: struct (nullable = true)
 |    |-- brand: string (nullable = true)
 |    |-- test_group: string (nullable = true)

Final step would be to filter only the modules.id with Default as value

val finaldf = df.withColumn("modules", explode($"modules.id"))
    .filter($"modules" === "Default")

which should give you

+-------+------+--------------+
|modules|userId|vars          |
+-------+------+--------------+
|Default|12345 |[xband,group1]|
|Default|12345 |[xband,group1]|
+-------+------+--------------+

I hope the answer is helpful

Updated

this would create json as

{"modules":"Default","userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
{"modules":"Default","userId":"12345","vars":{"brand":"xband","test_group":"group1"}}

But if your requirement is to get as below

{"modules":{"id":"Default"},"userId":"12345","vars":{"brand":"xband","test_group":"group1"}}
{"modules":{"id":"Default"},"userId":"12345","vars":{"brand":"xband","test_group":"group1"}}

You should be exploding the modules and not modules.id

val finaldf = df.withColumn("modules", explode($"modules"))
    .filter($"modules.id" === "Default")


问:
What is the best way to re-use code in two different situations when it needs variables from the current scope?
I've been writing a lot of code, and I try to avoid duplicated logic a lot, but I couldn't think of a way around this case.

```<code>if(something){
 // do something
 // then run a lot of code
} else {
 // do something else
 // then run a lot of the same code
}
</code>```

I tried this:

```<code>if(something){
 // do something
 traloc()
} else {
 // do something else
 traloc()
}

function traloc(){
 // then run a lot of code
}
</code>```

And it was working with variables, but I couldn't call resolve or reject from within the function, which means it doesn't inherit the function variables of the scope it's called in, and only some variables?

So to really achieve perfection I'd need to do:

```<code>if(something){
 // do something
 traloc(var1, var2, var3, var4)
} else {
 // do something else
 traloc(var1, var2, var3, var4)
}

function traloc(var1, var2, var3, var4){
 // then run a lot of code
}
</code>```

Is there a better way to abstract logic into functioning snippets that inherit function scope?

This is the real code for when I need to pass variables resolve and reject instead of having access to them

```<code>function relateRe(thing, relations, relation, relative, commonStateHash){
    /** params
     *  @param thing is the thing we are saving relations for
     *  @param relations is a list of relationships we are saving
     *  @param relation will be a @type {Number} representing the index of the relationship string, ie: the property of thing that is a list of related things
     *  @param relative will be a @type {Number} representing the property of the related thing where the _id of the thing should be inserted
     *  @param commonStateHash is the common hash used to identify backup states from this save function
     */
    /** returns a promise that resolves to:
     *  @func success
     *    @var thingRelatedFully
     *  @func failure
     *    @var thingRelatedSemi
     *    @var err
     */
    return new Promise((resolve, reject)=>{
      /** store a backup state of the relative for use if any other saving fails
       *  also handles conversion of non-registered documents into ._id bearing saveable model objects
       *  also handles conversion of non-object, ObjectId type relatives to ._id bearing saveable model objects
       */
      console.log(thing)
      console.log('relations')
      console.log(relations)
      console.log('relation')
      console.log(relation)
      console.log('relative')
      console.log(relative)
      if(!thing[relations[relation].relationship][relative]){
        /** check if we continue updating relationships
         */
          continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)

      } else {
        makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then((thingRelative, err)=>{
              if(!err){
                console.log(thingRelative)
                thing[relations[relation].relationship][relative] = thingRelative
                // thingRelative = thing[relations[relation].relationship][relative]
                /** add the _id of the given thing to the relationships list of the current relative
                 */
                  smartOpts.pushOpt(thing._id, relative[relations[relation].property])
                let relativeRelations = createRelativeRelations(relations, relation)
                let optsRelative = {
                  thing: thingRelative,
                  relations: relativeRelations,
                  save: relations[relation],
                  commonStateHash: commonStateHash,
                  backupState: false
                }
                saveThing(optsRelative)
                  .then((thingRelativeSaved, err)=>{
                    if(!err){
                      /** check if we continue updating relationships
                       */
                        continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)
                    } else {
                      resolve(thing, err)
                    }
                  })
              } else {
                resolve(thing, err)
              }
            })
      }
    })

    function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject){
      /** if the current relation is not the last of this relationship group/list
       *  increment the relationship counter
       *  update the next relationship
       */
        if((relative < thing[relations[relation].relationship].length-1) && ((relations[relation].save && (thing.stateId == commonStateHash)) || relations[relation].upsert)){
          console.log('next relative in relationship %s', relation)
          relateRe(thing, relations, relation, relative+=1, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if the current relationship group/list is not the last group/list
       *  increment the relationship group/list counter
       *  update the next relationship
       */
        else if(relation < relations.length-1){
          console.log('next relationship in relationship %s', relation+1)
          relateRe(thing, relations, relation+=1, 0, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if that was the last relationship and the last relationship group
       *  resolve the current state of the thing
       */
        else {
          console.log("resolving due to last relationship")
          resolve(thing)
        }
    }
  }
</code>```

答:
I'm trying to sort out your code and figure out the correct way to write the code, but I'm running into a bunch of programming mistakes:

You're using an anti-pattern of wrapping inner promises with a manually created new promise and then trying to call resolve() and reject() at the right time.  You should just return inner promises from the function and return inner promises from within .then() handlers to chain them.

You're expecting two arguments to a .then((thingRelative, err)=>{ handler.  That never happens.  .then() handlers are passed one argument.  Errors are rejected promises which you get with .catch().

You're attempting to pass multiple arguments to resolve() as in resolve(thing, err).  You can't do that either.  Both resolve() and reject() take exactly one argument.

You appear to be eating all errors and just calling resolve().  Do you really want to never return an error of any kind.  I honestly can't tell what you really should be doing with errors.  Calling resolve(thing, err) just does resolve(thing) so that's how I've coded below, but somehow I doubt that it actually desirable.

The fact that you have relateRe() which calls continueRelatingOrResolve() which calls relateRe() which calls continueRelatingOrResolve() makes this code very difficult to sort out what it does and prone to all sorts of possible errors.  I can't follow what this incestuous relationship is supposed to be doing so I can't suggest a better way to do things, but you'd usually rather have A calling B and C rather or even B sometimes calling itself rather than A calling B and B calling A.  Probably some better way of structuring the code would make this a lot easier to follow.

Anyway, when removing the anti-pattern, attempting to simplify your code and guessing on some things you just had wrong, here's what I get:

```<code>// always returns a promise so caller can know when it's done
// promise can resolve or reject if there's an unrecoverable error
function relateRe(thing, relations, relation, relative, commonStateHash) {
    if (!thing[relations[relation].relationship][relative]) {
        // check if we continue updating relationships
        // make sure we always return a promise
        return Promise.resolve(continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash));

    } else {
        return makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then(thingRelative => {
                console.log(thingRelative);
                thing[relations[relation].relationship][relative] = thingRelative;
                /** add the _id of the given thing to the relationships list of the current relative  */
                smartOpts.pushOpt(thing._id, relative[relations[relation].property]);
                let relativeRelations = createRelativeRelations(relations, relation);
                let optsRelative = {
                    thing: thingRelative,
                    relations: relativeRelations,
                    save: relations[relation],
                    commonStateHash: commonStateHash,
                    backupState: false
                };
                return saveThing(optsRelative).then(thingRelativeSaved => {
                    /** check if we continue updating relationships
                     */
                    return continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash);
                }).catch(err => {
                    // it appears that your original code does not want to return errors at all
                    // and is just resolving with thing so that's what this does, though it does not
                    // seem like a good thing to just eat all errors
                    return thing;
                });
            });
    }
}

function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash) {
    /** if the current relation is not the last of this relationship group/list
     *  increment the relationship counter
     *  update the next relationship
     */
    if ((relative < thing[relations[relation].relationship].length - 1) &&
          ((relations[relation].save && (thing.stateId == commonStateHash)) ||
          relations[relation].upsert)) {
        console.log('next relative in relationship %s', relation);
        return relateRe(thing, relations, relation, relative += 1, commonStateHash);
        /** otherwise if the current relationship group/list is not the last group/list
         *  increment the relationship group/list counter
         *  update the next relationship
         */
    } else if (relation < relations.length - 1) {
        console.log('next relationship in relationship %s', relation + 1);
        return relateRe(thing, relations, relation += 1, 0, commonStateHash);
    }
    /** otherwise if that was the last relationship and the last relationship group
     *  resolve the current state of the thing
     */
    else {
        console.log("resolving due to last relationship");
        return thing;
    }
}
</code>```

I do not expect this to work out of the box since I have no way of running it and no spec to go by for what this is supposed to do or what the data structures look like, but hopefully you can learn from the structure and see how nested async operations can be coded without the anti-pattern.

And, since there's no resolve or reject being passed around at all, that original problem is gone.  I'm guessing it was caused by the structure you had where A calls B which calls A which calls B which calls A, etc... and trying to keep track of which resolve and reject is which, but that's just a guess.

Body:
I've been writing a lot of code, and I try to avoid duplicated logic a lot, but I couldn't think of a way around this case.

if(something){
 // do something
 // then run a lot of code
} else {
 // do something else
 // then run a lot of the same code
}

I tried this:

if(something){
 // do something
 traloc()
} else {
 // do something else
 traloc()
}

function traloc(){
 // then run a lot of code
}

And it was working with variables, but I couldn't call resolve or reject from within the function, which means it doesn't inherit the function variables of the scope it's called in, and only some variables?

So to really achieve perfection I'd need to do:

if(something){
 // do something
 traloc(var1, var2, var3, var4)
} else {
 // do something else
 traloc(var1, var2, var3, var4)
}

function traloc(var1, var2, var3, var4){
 // then run a lot of code
}

Is there a better way to abstract logic into functioning snippets that inherit function scope?

This is the real code for when I need to pass variables resolve and reject instead of having access to them

function relateRe(thing, relations, relation, relative, commonStateHash){
    /** params
     *  @param thing is the thing we are saving relations for
     *  @param relations is a list of relationships we are saving
     *  @param relation will be a @type {Number} representing the index of the relationship string, ie: the property of thing that is a list of related things
     *  @param relative will be a @type {Number} representing the property of the related thing where the _id of the thing should be inserted
     *  @param commonStateHash is the common hash used to identify backup states from this save function
     */
    /** returns a promise that resolves to:
     *  @func success
     *    @var thingRelatedFully
     *  @func failure
     *    @var thingRelatedSemi
     *    @var err
     */
    return new Promise((resolve, reject)=>{
      /** store a backup state of the relative for use if any other saving fails
       *  also handles conversion of non-registered documents into ._id bearing saveable model objects
       *  also handles conversion of non-object, ObjectId type relatives to ._id bearing saveable model objects
       */
      console.log(thing)
      console.log('relations')
      console.log(relations)
      console.log('relation')
      console.log(relation)
      console.log('relative')
      console.log(relative)
      if(!thing[relations[relation].relationship][relative]){
        /** check if we continue updating relationships
         */
          continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)

      } else {
        makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then((thingRelative, err)=>{
              if(!err){
                console.log(thingRelative)
                thing[relations[relation].relationship][relative] = thingRelative
                // thingRelative = thing[relations[relation].relationship][relative]
                /** add the _id of the given thing to the relationships list of the current relative
                 */
                  smartOpts.pushOpt(thing._id, relative[relations[relation].property])
                let relativeRelations = createRelativeRelations(relations, relation)
                let optsRelative = {
                  thing: thingRelative,
                  relations: relativeRelations,
                  save: relations[relation],
                  commonStateHash: commonStateHash,
                  backupState: false
                }
                saveThing(optsRelative)
                  .then((thingRelativeSaved, err)=>{
                    if(!err){
                      /** check if we continue updating relationships
                       */
                        continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)
                    } else {
                      resolve(thing, err)
                    }
                  })
              } else {
                resolve(thing, err)
              }
            })
      }
    })

    function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject){
      /** if the current relation is not the last of this relationship group/list
       *  increment the relationship counter
       *  update the next relationship
       */
        if((relative < thing[relations[relation].relationship].length-1) && ((relations[relation].save && (thing.stateId == commonStateHash)) || relations[relation].upsert)){
          console.log('next relative in relationship %s', relation)
          relateRe(thing, relations, relation, relative+=1, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if the current relationship group/list is not the last group/list
       *  increment the relationship group/list counter
       *  update the next relationship
       */
        else if(relation < relations.length-1){
          console.log('next relationship in relationship %s', relation+1)
          relateRe(thing, relations, relation+=1, 0, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if that was the last relationship and the last relationship group
       *  resolve the current state of the thing
       */
        else {
          console.log("resolving due to last relationship")
          resolve(thing)
        }
    }
  }

Body:
I'm trying to sort out your code and figure out the correct way to write the code, but I'm running into a bunch of programming mistakes:

You're using an anti-pattern of wrapping inner promises with a manually created new promise and then trying to call resolve() and reject() at the right time.  You should just return inner promises from the function and return inner promises from within .then() handlers to chain them.

You're expecting two arguments to a .then((thingRelative, err)=>{ handler.  That never happens.  .then() handlers are passed one argument.  Errors are rejected promises which you get with .catch().

You're attempting to pass multiple arguments to resolve() as in resolve(thing, err).  You can't do that either.  Both resolve() and reject() take exactly one argument.

You appear to be eating all errors and just calling resolve().  Do you really want to never return an error of any kind.  I honestly can't tell what you really should be doing with errors.  Calling resolve(thing, err) just does resolve(thing) so that's how I've coded below, but somehow I doubt that it actually desirable.

The fact that you have relateRe() which calls continueRelatingOrResolve() which calls relateRe() which calls continueRelatingOrResolve() makes this code very difficult to sort out what it does and prone to all sorts of possible errors.  I can't follow what this incestuous relationship is supposed to be doing so I can't suggest a better way to do things, but you'd usually rather have A calling B and C rather or even B sometimes calling itself rather than A calling B and B calling A.  Probably some better way of structuring the code would make this a lot easier to follow.

Anyway, when removing the anti-pattern, attempting to simplify your code and guessing on some things you just had wrong, here's what I get:

// always returns a promise so caller can know when it's done
// promise can resolve or reject if there's an unrecoverable error
function relateRe(thing, relations, relation, relative, commonStateHash) {
    if (!thing[relations[relation].relationship][relative]) {
        // check if we continue updating relationships
        // make sure we always return a promise
        return Promise.resolve(continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash));

    } else {
        return makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then(thingRelative => {
                console.log(thingRelative);
                thing[relations[relation].relationship][relative] = thingRelative;
                /** add the _id of the given thing to the relationships list of the current relative  */
                smartOpts.pushOpt(thing._id, relative[relations[relation].property]);
                let relativeRelations = createRelativeRelations(relations, relation);
                let optsRelative = {
                    thing: thingRelative,
                    relations: relativeRelations,
                    save: relations[relation],
                    commonStateHash: commonStateHash,
                    backupState: false
                };
                return saveThing(optsRelative).then(thingRelativeSaved => {
                    /** check if we continue updating relationships
                     */
                    return continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash);
                }).catch(err => {
                    // it appears that your original code does not want to return errors at all
                    // and is just resolving with thing so that's what this does, though it does not
                    // seem like a good thing to just eat all errors
                    return thing;
                });
            });
    }
}

function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash) {
    /** if the current relation is not the last of this relationship group/list
     *  increment the relationship counter
     *  update the next relationship
     */
    if ((relative < thing[relations[relation].relationship].length - 1) &&
          ((relations[relation].save && (thing.stateId == commonStateHash)) ||
          relations[relation].upsert)) {
        console.log('next relative in relationship %s', relation);
        return relateRe(thing, relations, relation, relative += 1, commonStateHash);
        /** otherwise if the current relationship group/list is not the last group/list
         *  increment the relationship group/list counter
         *  update the next relationship
         */
    } else if (relation < relations.length - 1) {
        console.log('next relationship in relationship %s', relation + 1);
        return relateRe(thing, relations, relation += 1, 0, commonStateHash);
    }
    /** otherwise if that was the last relationship and the last relationship group
     *  resolve the current state of the thing
     */
    else {
        console.log("resolving due to last relationship");
        return thing;
    }
}

I do not expect this to work out of the box since I have no way of running it and no spec to go by for what this is supposed to do or what the data structures look like, but hopefully you can learn from the structure and see how nested async operations can be coded without the anti-pattern.

And, since there's no resolve or reject being passed around at all, that original problem is gone.  I'm guessing it was caused by the structure you had where A calls B which calls A which calls B which calls A, etc... and trying to keep track of which resolve and reject is which, but that's just a guess.


问:
AWS: SSH port timeout after changing port number
I am trying to configure the website on AWS Lightsail. First thing I did was to change port number from 22 to 2200 in

/etc/ssh/sshd_config

, then I configured the Uncomplicated Firewall like

sudo ufw allow 2200/tcp
sudo ufw allow 80/tcp
sudo ufw allow 123/udp
sudo ufw enable
sudo service ssh restart

Since this commit, I cannot connect to my server anymore, even with this command:

```<code>ssh -i ~/.ssh/private_key.rsa grader@34.215.140.134 -p 2200
</code>```

How can I fix this?

答: Go to the instance management page on the Networking tab under Firewall. Change the open port for SSH from 22 to 2200.</p>

Body:
I am trying to configure the website on AWS Lightsail. First thing I did was to change port number from 22 to 2200 in

/etc/ssh/sshd_config

, then I configured the Uncomplicated Firewall like

sudo ufw allow 2200/tcp
sudo ufw allow 80/tcp
sudo ufw allow 123/udp
sudo ufw enable
sudo service ssh restart

Since this commit, I cannot connect to my server anymore, even with this command:

ssh -i ~/.ssh/private_key.rsa grader@34.215.140.134 -p 2200

How can I fix this?


问:
Drop down button is not responding with selenium in java
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

```<code>driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/
</code>```

答:
I found solution myself,Below code worked</p>

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("homepages_dropdown")));
// drop down
driver.findElement(By.id("homepages_dropdown")).click();
Thread.sleep(2000);
// selecting configuration
driver.findElement(By.id("homepages_item_ConfigurationHomepage")).click();
Thread.sleep(2000);
</code>```

Body:
I want to click on drop down button and select one among one and click on it.I tried by many ways but it is not working. Attached image of html code, Anyone help me regarding this.
Below is my code which i tried

driver.findElement(By.id("homepages_dropdown")).click();

    /*List<WebElement> allElements = driver.findElements(By.xpath("//*[@id=\"homepages_item_AccountManagerDashboard\"]"));

    for (WebElement element: allElements)
    {
          System.out.println(element.getText());
    }*/

Body:
I found solution myself,Below code worked

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("homepages_dropdown")));
// drop down
driver.findElement(By.id("homepages_dropdown")).click();
Thread.sleep(2000);
// selecting configuration
driver.findElement(By.id("homepages_item_ConfigurationHomepage")).click();
Thread.sleep(2000);