问:
SQL query SUM syntax (classic ASP project)

I have 3 tables: MONTHS, STORES, REPORTS (attached image sample).

I want to write a SQL query that will SUM the records (day_amount) from the table REPORTS but only the records having the same store and the same month.

I need something like that:

```<code>SELECT SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
WHERE MONTHS.month_id = REPORTS.month_id
  AND STORES.store_id = REPORTS.store_id
</code>```

Is that correct? I have to use the GROUP BY?

答:
You need to make sure you're joining the other tables (if you need to do this).

```<code>SELECT
     MONTHS.month_id
    ,STORES.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
INNER JOIN MONTHS ON MONTHS.month_id = REPORTS.month_id
INNER JOIN STORES ON STORES.store_id = REPORTS.store_id
GROUP BY MONTHS.month_id, STORES.store_id
</code>```

Although, it doesn't appear you actually need the other tables at all, you could try something like this;

```<code>SELECT
     REPORTS.month_id
    ,REPORTS.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
GROUP BY REPORTS.month_id, REPORTS.store_id
</code>```

Body:
I have 3 tables: MONTHS, STORES, REPORTS (attached image sample).

I want to write a SQL query that will SUM the records (day_amount) from the table REPORTS but only the records having the same store and the same month.

I need something like that:

SELECT SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
WHERE MONTHS.month_id = REPORTS.month_id
  AND STORES.store_id = REPORTS.store_id

Is that correct? I have to use the GROUP BY?

Body:
You need to make sure you're joining the other tables (if you need to do this).

SELECT
     MONTHS.month_id
    ,STORES.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
INNER JOIN MONTHS ON MONTHS.month_id = REPORTS.month_id
INNER JOIN STORES ON STORES.store_id = REPORTS.store_id
GROUP BY MONTHS.month_id, STORES.store_id

Although, it doesn't appear you actually need the other tables at all, you could try something like this;

SELECT
     REPORTS.month_id
    ,REPORTS.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
GROUP BY REPORTS.month_id, REPORTS.store_id


来源: stackexchange

问:
Link data with dateRangeInput in Shiny
```<code>    ## app.R ##
    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    library(data.table)

    ui <- dashboardPage(
      dashboardHeader(title = "Smart Survey Insights"),
      dashboardSidebar(
        dateRangeInput("dateRange", "Please choose date", "2017-01-01", NULL),
        checkboxInput("comparePreviousPeriod", "Compare to previous period")
      ),
      dashboardBody(
        fluidRow(
          column(12, plotOutput("boxPlot")),
        )
      )
    )

    server <- function(input, output) {

    mydata <- data_frame(ended = c("14/11/2016 13:37", "14/11/2016 13:37",
"14/11/2016 13:47", "14/11/2016 13:51", "14/11/2016 13:51"),
task = c("Find licensing information", "Sign in to my existing account",
"Sign in to my existing account", "Bus registrations", "Make changes to my existing Operator’s Licence"), taskLevelOfDifficulty = c("Extremely difficult", "Extremely easy", "Neither easy nor difficult", "Extremely difficult", "Extremely easy"))

   mydata <- mydata  %>% mutate(ended = as.Date(ended, format = "%Y-%m-%d"))

      filteredData <- mydata %>% filter(ended >= input$date_range[1] && mydata$ended <= input$date_range[2])
      output$boxPlot <- renderPlot(ggplot(filteredData, aes(taskLevelOfDifficulty))) + geom_bar()

      }

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

My piece of code doesn't seem to work, the issue is that my "ended" column has the 14/11/2016 13:37 format whereas dateRangeInput has the yyyt-mm-dd format. I don't know how to link my graph with the the dateRangeInput.

答:
I had to fix quite a bit of your code so please have a look and make sure you understand the filtering and the dependencies on the output. For example purposes I moved dataframe outside the server

```<code>library(shiny)
library(shinydashboard)
library(ggplot2)
library(data.table)
library(dplyr)

mydata <- data.frame(ended = c("14/11/2016 13:37", "15/11/2016 13:37","16/11/2016 13:47", "17/11/2016 13:51", "18/11/2016 13:51"),
                     task = c("Find licensing information", "Sign in to my existing account",
                              "Sign in to my existing account", "Bus registrations", "Make changes to my existing Operator’s Licence"),
                     taskLevelOfDifficulty = c("Extremely difficult", "Extremely easy", "Neither easy nor difficult", "Extremely difficult", "Extremely easy"))

mydata <- mydata  %>% mutate(ended = as.Date(ended, format = "%d/%m/%Y"))

ui <- dashboardPage(
  dashboardHeader(title = "Smart Survey Insights"),
  dashboardSidebar(
    dateRangeInput("dateRange", "Please choose date", "2016-11-14", "2016-11-15"),
    checkboxInput("comparePreviousPeriod", "Compare to previous period")
  ),
  dashboardBody(
    fluidRow(
      column(12, plotOutput("boxPlot"))
    )
  )
)

server <- function(input, output) {

  filteredData <- reactive({
    req(input$dateRange)
    mydata[mydata$ended >= input$dateRange[1] & mydata$ended <= input$dateRange[2],]
  })

  output$boxPlot <- renderPlot(ggplot(filteredData(), aes(taskLevelOfDifficulty)) + geom_bar())
}

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

ContentLicense: CC BY-SA 3.0

Title: Link data with dateRangeInput in Shiny

Body:
    ## app.R ##
    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    library(data.table)

    ui <- dashboardPage(
      dashboardHeader(title = "Smart Survey Insights"),
      dashboardSidebar(
        dateRangeInput("dateRange", "Please choose date", "2017-01-01", NULL),
        checkboxInput("comparePreviousPeriod", "Compare to previous period")
      ),
      dashboardBody(
        fluidRow(
          column(12, plotOutput("boxPlot")),
        )
      )
    )

    server <- function(input, output) {

    mydata <- data_frame(ended = c("14/11/2016 13:37", "14/11/2016 13:37",
"14/11/2016 13:47", "14/11/2016 13:51", "14/11/2016 13:51"),
task = c("Find licensing information", "Sign in to my existing account",
"Sign in to my existing account", "Bus registrations", "Make changes to my existing Operator’s Licence"), taskLevelOfDifficulty = c("Extremely difficult", "Extremely easy", "Neither easy nor difficult", "Extremely difficult", "Extremely easy"))

   mydata <- mydata  %>% mutate(ended = as.Date(ended, format = "%Y-%m-%d"))

      filteredData <- mydata %>% filter(ended >= input$date_range[1] && mydata$ended <= input$date_range[2])
      output$boxPlot <- renderPlot(ggplot(filteredData, aes(taskLevelOfDifficulty))) + geom_bar()

      }

    shinyApp(ui, server)

My piece of code doesn't seem to work, the issue is that my "ended" column has the 14/11/2016 13:37 format whereas dateRangeInput has the yyyt-mm-dd format. I don't know how to link my graph with the the dateRangeInput.

Body:
I had to fix quite a bit of your code so please have a look and make sure you understand the filtering and the dependencies on the output. For example purposes I moved dataframe outside the server

library(shiny)
library(shinydashboard)
library(ggplot2)
library(data.table)
library(dplyr)

mydata <- data.frame(ended = c("14/11/2016 13:37", "15/11/2016 13:37","16/11/2016 13:47", "17/11/2016 13:51", "18/11/2016 13:51"),
                     task = c("Find licensing information", "Sign in to my existing account",
                              "Sign in to my existing account", "Bus registrations", "Make changes to my existing Operator’s Licence"),
                     taskLevelOfDifficulty = c("Extremely difficult", "Extremely easy", "Neither easy nor difficult", "Extremely difficult", "Extremely easy"))

mydata <- mydata  %>% mutate(ended = as.Date(ended, format = "%d/%m/%Y"))

ui <- dashboardPage(
  dashboardHeader(title = "Smart Survey Insights"),
  dashboardSidebar(
    dateRangeInput("dateRange", "Please choose date", "2016-11-14", "2016-11-15"),
    checkboxInput("comparePreviousPeriod", "Compare to previous period")
  ),
  dashboardBody(
    fluidRow(
      column(12, plotOutput("boxPlot"))
    )
  )
)

server <- function(input, output) {

  filteredData <- reactive({
    req(input$dateRange)
    mydata[mydata$ended >= input$dateRange[1] & mydata$ended <= input$dateRange[2],]
  })

  output$boxPlot <- renderPlot(ggplot(filteredData(), aes(taskLevelOfDifficulty)) + geom_bar())
}

shinyApp(ui, server)


问:
Single sign on not working on Java migration 1.7
I am using openAm 9.5.4 as service provider and salesforce as IDP. With existing java 1.6 version of OpenAm my IDP initiated sso works.
But when we migrate java version of openAm to 1.7 sso failes with error "HTTP Status 500 - Single Sign On failed.". What may be the issue causing by change of java version ?

One more important question that I want to confirm is, whether OpenAm 9.5.4 even supports SSO on Java 1.7? Someone tried this combination?

答: OpenAM 9.5.4 only runs on Java 1.6. The first OpenAM release that supported Java 1.7 was 11.0.0, see the release notes.</p>


问:
qtip jquery, Ghosts" Artefacts of Tooltip in DOM, how remove
I am using the qtip plugin in the jquery fullcalendar (on doubleclick on a event).

I create a modal tooltip window in my page. In this tooltip window i am loading some ajax content and calling some functions (links with binded events, example deleting the event on the calendar), but this is not the problem i think.

If i open the tooltip at the firsttime everything is ok. on the second and more openings my jQuery-selector (selection by id) is fired two or more times.

I checked the generated code with Webdeveloper-Toolbar of FireFox. I saw all created tooltips in the DOM (every doubleclick creates a tooltip in the DOM, so i have a lot of copies in it).
After closing the tooltip (standard function of tooltip), the tooltips are always present in the DOM (every opening of an tooltip creates an "ghost", not visible, but my jquery selector find it).

I read some similar problems but i don't understand the solution.

how can i remove this "ghosts", because the "ghosts" need memory a produce undefined results (more than one element with the same id, for example).

i try for example:
$('.qtip').remove(); and other solutions like this with $(this).parents... etc. no result.

Or i call the remove on the wrong places.
First Try: remove it on the hideEvent of qTip
Second Try: on doubleclick on an event of my calendar.
--> No effect in both.

Thanks so much for an solution.

Chichi

Thanks alot for reply.

答:
qTip is great, no need to remove it, face the problem!

I had the same issue with qTip. What qTip version are you using? Switch to qTip2! It fixes this problem for you.

Like jhanifen says in his comment, I used

```<code>$('a.ppname[rel]').qtip({
   content : {stuff},
   style : {stuff},
   position: {stuff},
   show: 'mouseover',
   hide: 'mouseout',
   onHide: function() { $(this).qtip('destroy'); }
});
</code>```

to remove the qTip from DOM. qTip2 handles this for you. Here is my example for qTip2 usage.

More examples: qTip2 Demos.

ContentLicense: CC BY-SA 2.5

Body:
qTip is great, no need to remove it, face the problem!

I had the same issue with qTip. What qTip version are you using? Switch to qTip2! It fixes this problem for you.

Like jhanifen says in his comment, I used

$('a.ppname[rel]').qtip({
   content : {stuff},
   style : {stuff},
   position: {stuff},
   show: 'mouseover',
   hide: 'mouseout',
   onHide: function() { $(this).qtip('destroy'); }
});

to remove the qTip from DOM. qTip2 handles this for you. Here is my example for qTip2 usage.

More examples: qTip2 Demos.


问:
Convert a Cookie to string
I have a cookie called LoginCookie and would like to convert the value to a string. how would I go around converting it?

After converting it to a string, I will put the string's data in a label.

答:
As already noted, the Value property of HttpCookie returns all cookie data as string.

```<code>var cookie = new HttpCookie("CookieName");
cookie["1"] = "Value1";
cookie["2"] = "Value2";

string defaultValueString = cookie.Value;
// result: "1=Value1&2=Value2"
</code>```

If the cookie contains multiple keys, the Values property lets you access a certain key. You can use this to return a custom format.

```<code>var valuesByKey = cookie.Values.Keys.Cast<string>()
    .ToDictionary(k => k, v => cookie.Values[v]);

string customValueString = string.Join("; ",
    valuesByKey.Select(kvp => $"Name: '{kvp.Key}', Value: '{kvp.Value}'");
// result: "Name: '1', Value: 'Value1'; Name: '2', Value: 'Value2'"
</code>```

Title: Convert a Cookie to string

Body:
As already noted, the Value property of HttpCookie returns all cookie data as string.

var cookie = new HttpCookie("CookieName");
cookie["1"] = "Value1";
cookie["2"] = "Value2";

string defaultValueString = cookie.Value;
// result: "1=Value1&2=Value2"

If the cookie contains multiple keys, the Values property lets you access a certain key. You can use this to return a custom format.

var valuesByKey = cookie.Values.Keys.Cast<string>()
    .ToDictionary(k => k, v => cookie.Values[v]);

string customValueString = string.Join("; ",
    valuesByKey.Select(kvp => $"Name: '{kvp.Key}', Value: '{kvp.Value}'");
// result: "Name: '1', Value: 'Value1'; Name: '2', Value: 'Value2'"


问:
Artifactory restore nuget packages with authentication from powershell
Our team started using Artifactory a few weeks ago and one of the challenges we are currently trying to work through is authentication. Currently we have every developer setup in Artifactory with an account login, we have a build.ps1 file that we use to restore our nuget packages but we're trying to automate this process.

Here is what our powershell script looks like. But it is not prompting the user to enter their username and password, unless they add it as parameters to the .\build.ps1 command line but the issue there is that the password is being entered in plain text.

```<code>"Updating NuGet Dependencies"
$nuget = "$rootDir\.nuget\NuGet.exe"
if ($nuser)
{
    Invoke-Expression "$nuget Sources Update -Name 'Artifactory' -UserName $user -Password $pass"
}
Invoke-Expression "$nuget install -NonInteractive -DisableParallel"
if ($lastexitcode -ne 0) {
    Write-Host -foreground red "Error occurred downloading dependencies."
    exit 1
}
dir . | where { $_.psiscontainer } | where { (test-path (join-path $_.fullname "packages.config")) } | foreach {
    Invoke-Expression "$nuget install '$($_.fullname)\packages.config' -NonInteractive -DisableParallel"
    if ($lastexitcode -ne 0) {
        Write-Host -foreground red "Error occurred downloading project dependencies."
        exit 1
    }
}
</code>```

答:
I had some problems with setting the credentials.

My solutions was to upgrade nuget.exe (v4.3.0 from v3.x.x) and using the Add Sources with the username/ password, with the ApiKey from the Artifactory as the password.

Body:
Our team started using Artifactory a few weeks ago and one of the challenges we are currently trying to work through is authentication. Currently we have every developer setup in Artifactory with an account login, we have a build.ps1 file that we use to restore our nuget packages but we're trying to automate this process.

Here is what our powershell script looks like. But it is not prompting the user to enter their username and password, unless they add it as parameters to the .\build.ps1 command line but the issue there is that the password is being entered in plain text.

"Updating NuGet Dependencies"
$nuget = "$rootDir\.nuget\NuGet.exe"
if ($nuser)
{
    Invoke-Expression "$nuget Sources Update -Name 'Artifactory' -UserName $user -Password $pass"
}
Invoke-Expression "$nuget install -NonInteractive -DisableParallel"
if ($lastexitcode -ne 0) {
    Write-Host -foreground red "Error occurred downloading dependencies."
    exit 1
}
dir . | where { $_.psiscontainer } | where { (test-path (join-path $_.fullname "packages.config")) } | foreach {
    Invoke-Expression "$nuget install '$($_.fullname)\packages.config' -NonInteractive -DisableParallel"
    if ($lastexitcode -ne 0) {
        Write-Host -foreground red "Error occurred downloading project dependencies."
        exit 1
    }
}


问:
How would I check if user input is over the Int limit using public static main void (String args[])
This is what I've put so far:

```<code>public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}
</code>```

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

答:
You can either catch the exception as suggested by @AxelH or try below suggestion

You may cast the input to Long and then check if the value is greater than max value of Integer or not.

```<code>public static void main(String[] args) {
        Long l = Long.parseLong(args[0]);
        if(l > Integer.MAX_VALUE){
            System.out.println("Value can't be handled by Integer");
        } else{
            System.out.println("Proper Integer");
        }

    }
</code>```

Please note you may still get NumberFormatException if the input can't be parsed to Long.

And if the input can go larger then use BigInteger bi = new BigInteger(args[0]);

If you want to get details on how to operate on BigInteger
Refer to documentation of BigInteger here

Body:
This is what I've put so far:

public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

Body:
You can either catch the exception as suggested by @AxelH or try below suggestion

You may cast the input to Long and then check if the value is greater than max value of Integer or not.

public static void main(String[] args) {
        Long l = Long.parseLong(args[0]);
        if(l > Integer.MAX_VALUE){
            System.out.println("Value can't be handled by Integer");
        } else{
            System.out.println("Proper Integer");
        }

    }

Please note you may still get NumberFormatException if the input can't be parsed to Long.

And if the input can go larger then use BigInteger bi = new BigInteger(args[0]);

If you want to get details on how to operate on BigInteger
Refer to documentation of BigInteger here


问:
Repeat File Printing Using Scanner
I'm trying to make a program which reprints the text file simple.txt every time the user presses "c", but with my code, it will only print once:

```<code>public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    Scanner fileSearch = new Scanner(new File("simple.txt"));
    UI(console, fileSearch);
}

public static void UI (Scanner console, Scanner fileSearch) {
    String choice = "Start";
    while (!choice.equals("q")) {
        System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
        choice = console.next();
        choice = choice.toLowerCase();
        if (choice.equals("c")) {
            System.out.println("Create");
            CreateMadLibs(fileSearch);
        } else if (!choice.equals("q")) {
            System.out.println("I don't understand.");
        }
    }
}

public static File FileGrab (Scanner fileSearch) {
    File thing = new File(fileSearch.next());
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
return thing;
}

public static void CreateMadLibs (Scanner fileSearch) {
    FileGrab(fileSearch);
}
</code>```

I think the issue is that I create the scanner fileSearch in main instead of in UI. I tried initializing fileSearch in the if statement, but that gave me a fileNotFoundException.  As is, I get this:

```<code>Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at test.FileGrab(test.java:28)
    at test.CreateMadLibs(test.java:36)
    at test.UI(test.java:20)
    at test.main(test.java:9)
</code>```

答:
You can put the fileSearch into the while loop so that it finds the file each time you re-search through the loop. You just call UI(console); in the main then.

Also, I would recommend closing the scanner at the end, as it may not be used again (unless of course c is re-entered).

```<code>public static void UI(Scanner console) throws FileNotFoundException {
        String choice = "Start";
        while (!choice.equals("q")) {
            Scanner fileSearch = new Scanner(new File("simple.txt"));
            System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
            choice = console.next();
            choice = choice.toLowerCase();
            if (choice.equals("c")) {
                System.out.println("Create");
                CreateMadLibs(fileSearch);
            } else if (!choice.equals("q")) {
                System.out.println("I don't understand.");
            }
            fileSearch.close();
        }
    }
</code>```

Title: Repeat File Printing Using Scanner

Body:
I'm trying to make a program which reprints the text file simple.txt every time the user presses "c", but with my code, it will only print once:

public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    Scanner fileSearch = new Scanner(new File("simple.txt"));
    UI(console, fileSearch);
}

public static void UI (Scanner console, Scanner fileSearch) {
    String choice = "Start";
    while (!choice.equals("q")) {
        System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
        choice = console.next();
        choice = choice.toLowerCase();
        if (choice.equals("c")) {
            System.out.println("Create");
            CreateMadLibs(fileSearch);
        } else if (!choice.equals("q")) {
            System.out.println("I don't understand.");
        }
    }
}

public static File FileGrab (Scanner fileSearch) {
    File thing = new File(fileSearch.next());
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
return thing;
}

public static void CreateMadLibs (Scanner fileSearch) {
    FileGrab(fileSearch);
}

I think the issue is that I create the scanner fileSearch in main instead of in UI. I tried initializing fileSearch in the if statement, but that gave me a fileNotFoundException.  As is, I get this:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at test.FileGrab(test.java:28)
    at test.CreateMadLibs(test.java:36)
    at test.UI(test.java:20)
    at test.main(test.java:9)

Body:
You can put the fileSearch into the while loop so that it finds the file each time you re-search through the loop. You just call UI(console); in the main then.

Also, I would recommend closing the scanner at the end, as it may not be used again (unless of course c is re-entered).

public static void UI(Scanner console) throws FileNotFoundException {
        String choice = "Start";
        while (!choice.equals("q")) {
            Scanner fileSearch = new Scanner(new File("simple.txt"));
            System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
            choice = console.next();
            choice = choice.toLowerCase();
            if (choice.equals("c")) {
                System.out.println("Create");
                CreateMadLibs(fileSearch);
            } else if (!choice.equals("q")) {
                System.out.println("I don't understand.");
            }
            fileSearch.close();
        }
    }


问:
ChartJS vertical line not removed on touchend
I'm using this plugin to draw a vertical line where the user touches/hovers over the chart:

```<code>Chart.plugins.register({
   afterDatasetsDraw: function(chart) {
      if (chart.tooltip._active && chart.tooltip._active.length) {
         var activePoint = chart.tooltip._active[0],
            ctx = chart.ctx,
            y_axis = chart.scales['y-axis-0'],
            x = activePoint.tooltipPosition().x,
            topY = y_axis.top,
            bottomY = y_axis.bottom;
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = '#26D4A5';
         ctx.stroke();
         ctx.restore();
      }
   }
});
</code>```

The line gets removed after the hovering ends, however if a touchend/touchcancel happens, the line is still there.

I tried adding afterEvent to the plugin like this:

```<code>Chart.plugins.register({
   afterDatasetsDraw: function(chart) {
      if (chart.tooltip._active && chart.tooltip._active.length) {
         var activePoint = chart.tooltip._active[0],
            ctx = chart.ctx,
            y_axis = chart.scales['y-axis-0'],
            x = activePoint.tooltipPosition().x,
            topY = y_axis.top,
            bottomY = y_axis.bottom;
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = '#26D4A5';
         ctx.stroke();
         ctx.restore();
      }
   },
   afterEvent: function(chart, e) {
     if(e.type=="mouseout"){
       alert("mouseout");
     }
     if(e.type=="touchend"){
       alert("touchend");
     }
     if(e.type=="mousemove"){
       alert("mouse move");
     }
   }
});
</code>```

But the only events that work on touch are mousemove, touchend and mouseout do not work on mobile/touch. Is there any workaround?

答:
Seems like the problem was that "touchend" event was removed from the default config.

Re-adding the event "touchend" to the options like this, removes the tooltip after touchend.

```<code>events: ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]
</code>```

This was changed here: https://github.com/chartjs/Chart.js/pull/1644/files

Body:
I'm using this plugin to draw a vertical line where the user touches/hovers over the chart:

Chart.plugins.register({
   afterDatasetsDraw: function(chart) {
      if (chart.tooltip._active && chart.tooltip._active.length) {
         var activePoint = chart.tooltip._active[0],
            ctx = chart.ctx,
            y_axis = chart.scales['y-axis-0'],
            x = activePoint.tooltipPosition().x,
            topY = y_axis.top,
            bottomY = y_axis.bottom;
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = '#26D4A5';
         ctx.stroke();
         ctx.restore();
      }
   }
});

The line gets removed after the hovering ends, however if a touchend/touchcancel happens, the line is still there.

I tried adding afterEvent to the plugin like this:

Chart.plugins.register({
   afterDatasetsDraw: function(chart) {
      if (chart.tooltip._active && chart.tooltip._active.length) {
         var activePoint = chart.tooltip._active[0],
            ctx = chart.ctx,
            y_axis = chart.scales['y-axis-0'],
            x = activePoint.tooltipPosition().x,
            topY = y_axis.top,
            bottomY = y_axis.bottom;
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 1;
         ctx.strokeStyle = '#26D4A5';
         ctx.stroke();
         ctx.restore();
      }
   },
   afterEvent: function(chart, e) {
     if(e.type=="mouseout"){
       alert("mouseout");
     }
     if(e.type=="touchend"){
       alert("touchend");
     }
     if(e.type=="mousemove"){
       alert("mouse move");
     }
   }
});

But the only events that work on touch are mousemove, touchend and mouseout do not work on mobile/touch. Is there any workaround?

Body:
Seems like the problem was that "touchend" event was removed from the default config.

Re-adding the event "touchend" to the options like this, removes the tooltip after touchend.

events: ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]

This was changed here: https://github.com/chartjs/Chart.js/pull/1644/files


问:
iPhone: Splash screen in app - Good or Bad?
I'm going to submit a Lifestyle app to the App Store. I'm confused whether to add a Splash Screen to the App or not ?

Please advise me whether it's a good or bad idea as far as usability and App Store's submission guidelines are concerned.

答:
You can add a Default.png (see iOS documentation!) to your application bundle.
This image is being shown full screen while your application is loading.

Other than that, I wouldn't add a splash screen to your app.


问:
How to concat a string to a windows batch command variable in Jenkins?
I'm getting our application version value via curl command and set it into a app_version variable:

```<code>for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
)
</code>```

This works for me and I'm getting the value as expected.
Later on, I'm using this value as a parameter to build our application installer for overriding the application version.

My application version syntax should be: Beta - version %app_version%.
How can I concat the app_version variable to the "Beta - version" String?

Whatever I tried I got 2 strings like that: "Beta - version" "10.1.2"

答:
just set another variable called beta_version:

```<code>@echo off
for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
  set "beta_version=Beta - version %%a"
  set beta_version=%beta_version:"=%
  echo %beta_version%
)
</code>```

or if you prefer:

```<code>set "beta_version=Beta - version %app_version%"
</code>```

Body:
I'm getting our application version value via curl command and set it into a app_version variable:

for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
)

This works for me and I'm getting the value as expected.
Later on, I'm using this value as a parameter to build our application installer for overriding the application version.

My application version syntax should be: Beta - version %app_version%.
How can I concat the app_version variable to the "Beta - version" String?

Whatever I tried I got 2 strings like that: "Beta - version" "10.1.2"

Body:
just set another variable called beta_version:

@echo off
for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
  set "beta_version=Beta - version %%a"
  set beta_version=%beta_version:"=%
  echo %beta_version%
)

or if you prefer:

set "beta_version=Beta - version %app_version%"


问:
Typescript throws errors in node_modules with strict compiler options
There are several github issues about why errors in node_modules are thrown although that folder is excluded in tsconfig.json. If there is any import on the lib it is included, ignoring the exclude property.

However when using stricter compiler options (i.e. strictNullChecks, noUnusedLocals, ...) and reference any lib that is not designed to work on those options, errors are thrown.

Thus whenever using such a lib it is always a decision of not using the lib or not using the compiler option. However there are big libraries/frameworks that do not support those options (i.e. Angular) so it seems like there is no way of using those options to ensure strict checks in the own project.

Am I missing some possibility to avoid errors in node_modules being thrown?
If not, is there any technical requirement to apply those rules to all imported libraries or what is the reasoning behind this behaviour?

答:
In all my projects setup I have structure where in root I have:

Folders:

code_folder

node_modules

Files:

package.json

README.md

tsconfig.json

tslint.json

yarn.lock

Then in tsconfig.json:

```<code>{
    "compilerOptions": {
        "lib": ["es6"]
    },
    "include": [
        "code_folder/*"
    ]
}
</code>```

Body:
In all my projects setup I have structure where in root I have:

Folders:

code_folder

node_modules

Files:

package.json

README.md

tsconfig.json

tslint.json

yarn.lock

Then in tsconfig.json:

{
    "compilerOptions": {
        "lib": ["es6"]
    },
    "include": [
        "code_folder/*"
    ]
}


问:
Is there a way to render SVG objects on HTML5 Canvas?
My program generates SVG objects dynamically and I can visualise them by adding them to the DOM.

I would also like to draw them on a HTML5 canvas but so far have failed despite lost of searching on the web. Support for drawing SVGs that are actual source files is abundant but not for dynamically created SVGs as far as I can find so far.

My attempts are shown in the code below:

```<code>// dynamically create an svg containing a black circle
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS (svgns, "svg");
svg.setAttribute ( "width"  , "128" );
svg.setAttribute ( "height" , "128" );
svg.setAttributeNS ("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

shape = document.createElementNS (svgns, "circle");
svg.appendChild (shape);
shape.setAttribute ( "cx", 64);
shape.setAttribute ( "cy", 64);
shape.setAttribute ( "r",  50);
shape.setAttribute ( "fill", "black");

// add the svg to the DOM
document.body.appendChild (svg); // works

// create a canvas to render the black circle
var canvas = document.createElement ("canvas");
document.body.appendChild (canvas);
canvas.width = 300 ; canvas.height = 150 ;
var ctx = canvas.getContext ("2d");
// create an image to contain the svg data
var img = new Image ();
img.onload = function () { ctx.drawImage (this,10,10) };

// ATTEMPT 1

var svgURL = new XMLSerializer().serializeToString (svg);
img.src = "data:image/svg+xml; charset=utf8," + encodeURIComponent (svgURL);  // does not work

// ATTEMPT 2

var xml = (new XMLSerializer()).serializeToString (svg);
img.src = "data:image/svg+xml;base64," + btoa (xml); //  also does not work

// ATTEMPT 3

var hiddenDiv = document.createElement("div");
hiddenDiv.appendChild (svg.cloneNode(true));
img.src = "data:image/svg+xml;base64," + window.btoa (hiddenDiv.innerHTML); // also deos not work
</code>```

By the way in case you ask why not draw the object directly onto the canvas instead of creating the SVG, it is that I want to use the svgs in the DOM as well.

答:
The canvg library does what you're after.

From the introduction text:

canvg is a SVG parser and renderer. It takes a URL to a SVG file or the text of an SVG file, parses it in JavaScript, and renders the result on a Canvas element. The rendering speed of the examples is about as fast as native SVG.

I used it a while ago and found it straightforward to use and reliable.

Body:
My program generates SVG objects dynamically and I can visualise them by adding them to the DOM.

I would also like to draw them on a HTML5 canvas but so far have failed despite lost of searching on the web. Support for drawing SVGs that are actual source files is abundant but not for dynamically created SVGs as far as I can find so far.

My attempts are shown in the code below:

// dynamically create an svg containing a black circle
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS (svgns, "svg");
svg.setAttribute ( "width"  , "128" );
svg.setAttribute ( "height" , "128" );
svg.setAttributeNS ("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

shape = document.createElementNS (svgns, "circle");
svg.appendChild (shape);
shape.setAttribute ( "cx", 64);
shape.setAttribute ( "cy", 64);
shape.setAttribute ( "r",  50);
shape.setAttribute ( "fill", "black");

// add the svg to the DOM
document.body.appendChild (svg); // works

// create a canvas to render the black circle
var canvas = document.createElement ("canvas");
document.body.appendChild (canvas);
canvas.width = 300 ; canvas.height = 150 ;
var ctx = canvas.getContext ("2d");
// create an image to contain the svg data
var img = new Image ();
img.onload = function () { ctx.drawImage (this,10,10) };

// ATTEMPT 1

var svgURL = new XMLSerializer().serializeToString (svg);
img.src = "data:image/svg+xml; charset=utf8," + encodeURIComponent (svgURL);  // does not work

// ATTEMPT 2

var xml = (new XMLSerializer()).serializeToString (svg);
img.src = "data:image/svg+xml;base64," + btoa (xml); //  also does not work

// ATTEMPT 3

var hiddenDiv = document.createElement("div");
hiddenDiv.appendChild (svg.cloneNode(true));
img.src = "data:image/svg+xml;base64," + window.btoa (hiddenDiv.innerHTML); // also deos not work

By the way in case you ask why not draw the object directly onto the canvas instead of creating the SVG, it is that I want to use the svgs in the DOM as well.


问:
Assigning NaN to Unique Condition in Rows of Array in MATLAB
I have an array like:

A = [ 1 2 3 4; NaN NaN 3 4; NaN NaN NaN 4 ];

I need an index such that looks like this where the first  non NaN value is set to 1 in each row of a large array. The resulting index should look like:

```<code>B = [ 0 0 0 0; 0 0 1 0; 0 0 0 1];
</code>```

I've tried using cumsum along the rows but can't get this to work.

答:
Since I'm not allowed to comment, I'm adding an answer. The code given by @Tommaso Belluzzo does the job but makes the assumption that the numbers in the rows are always in increasing order. For example, if we have a matrix defined as

```<code>a = [
    1 2 3 4;
    NaN NaN 5 4;
    NaN NaN NaN 4
];
</code>```

or

```<code>a = [
    1 2 3 4;
    NaN 5 NaN 4;
    NaN NaN NaN 4
];
</code>```

@Tommaso's code gives the same output in both the cases, which is also wrong in each case.

```<code>b =

     1     0     0     0
     0     0     0     1
     0     0     0     1
</code>```

Whereas the universal solution to this problem could be achieved by a simple modification.

```<code>a_size = size(a);
c=isnan(a);
[~,a_sub] = min(c.');
a_idx = sub2ind(a_size,(1:3)',a_sub');
b = zeros(a_size);
b(a_idx) = 1;
</code>```

And the output then received is-

b =

```<code>     1     0     0     0
     0     0     1     0
     0     0     0     1
</code>```

b1 =

```<code>     1     0     0     0
     0     1     0     0
     0     0     0     1
</code>```

Hope this helps!

Body:
I have an array like:

A = [ 1 2 3 4; NaN NaN 3 4; NaN NaN NaN 4 ];

I need an index such that looks like this where the first  non NaN value is set to 1 in each row of a large array. The resulting index should look like:

B = [ 0 0 0 0; 0 0 1 0; 0 0 0 1];

I've tried using cumsum along the rows but can't get this to work.

Body:
Since I'm not allowed to comment, I'm adding an answer. The code given by @Tommaso Belluzzo does the job but makes the assumption that the numbers in the rows are always in increasing order. For example, if we have a matrix defined as

a = [
    1 2 3 4;
    NaN NaN 5 4;
    NaN NaN NaN 4
];

or

a = [
    1 2 3 4;
    NaN 5 NaN 4;
    NaN NaN NaN 4
];

@Tommaso's code gives the same output in both the cases, which is also wrong in each case.

b =

     1     0     0     0
     0     0     0     1
     0     0     0     1

Whereas the universal solution to this problem could be achieved by a simple modification.

a_size = size(a);
c=isnan(a);
[~,a_sub] = min(c.');
a_idx = sub2ind(a_size,(1:3)',a_sub');
b = zeros(a_size);
b(a_idx) = 1;

And the output then received is-

b =

     1     0     0     0
     0     0     1     0
     0     0     0     1

b1 =

     1     0     0     0
     0     1     0     0
     0     0     0     1

Hope this helps!


问:
How to inject react (webpack's) bundle path into wordpress scripts functions
I'm building a WordPress theme using olympos theme template and react (with create-react-app) as my front-end tool to complete the application views.

Problem is I need a React bundle path to supply to Wordpress as it loads my scripts so I can work better with the app in both builds Development & Production.

The first problem is with development builds there is no direct way to get a path to the React bundle (or at least I cannot find one, Webpack noob).

Second when I run yarn build to make production builds with paths they keep having an ID'ish looking string between them and this forces me to keep changing that random generated ID every time I make a build.

Example:

```<code>path/to/wp-theme/build/static/js/main.i3i391.js

path/to/wp-theme/build/static/css/styles.91k1j2.css
</code>```

Aim

To have a path that wont change and then place it in my Wordpress function and use it in development builds (and production if possible) so when I experience Webpack's hot reload it happens from inside my Wordpress configurations.

Kinda like this:

```<code>function theme_register_scripts() {
    wp_enqueue_style( 'styles', get_stylesheet_uri() . 'build/static/css/styles.css' );
    wp_enqueue_script( 'scripts', esc_url(trailingslashit( get_template_directory_uri()) . 'build/static/js/main.js' ), NULL, '1.0', true);
}
</code>```

I'm ready to configure my webpack configurations, as I have already done

```<code>npm run eject
</code>```

to show my webpack and other behind the scene configurations but it was pretty confussing to know what button to press and what to avoid.

答:
After some more reading, I understood my misconceptions and thought I should post an answer to help others.

Wordpress 4.7 and higher comes integrated with Rest API features and thus no need for a plugin installation.

Just after starting your Wordpress a quick hit on

```<code>http://localhost/wp-json/
</code>```

will give you the json body if not then

```<code>http://localhost/binladen/?rest_route=/
</code>```

Will do.

If you are using create-react-app (or Webpack for that matter) for your react theme development and you want to keep your HMR as you write your React front-end without creating the bundle everytime then don't worry about Wordpress. It can safely stay on one tab and your front-end in another.

You'll be using the WP Rest API to call for Wordpress resources on your React's logic and until your front-end is finished or you are satisfied with it is when you can include it in your Wordpress bundle and ship your Wordpress site with that React theme.

Building your front-end production bundle (with create-react-app)

```<code>npm run build
</code>```

and included the created React bundle produced by the above code in Wordpress theme functions file.

```<code>function theme_register_scripts() {
    wp_enqueue_style( 'styles', get_stylesheet_uri() . 'build/static/css/styles.1k9s92.css' );
    wp_enqueue_script( 'scripts', esc_url(trailingslashit( get_template_directory_uri()) . 'build/static/js/bundle.i1929a.js' ), NULL, '1.0', true);
}
</code>```

Sources.

create-react-app: Source

Multiple WP Rest API & React integration source & articles: Source

Multiple routes to WP Rest API: Source

Olypos WP template theme: Source

Body:
I'm building a WordPress theme using olympos theme template and react (with create-react-app) as my front-end tool to complete the application views.

Problem is I need a React bundle path to supply to Wordpress as it loads my scripts so I can work better with the app in both builds Development & Production.

The first problem is with development builds there is no direct way to get a path to the React bundle (or at least I cannot find one, Webpack noob).

Second when I run yarn build to make production builds with paths they keep having an ID'ish looking string between them and this forces me to keep changing that random generated ID every time I make a build.

Example:

path/to/wp-theme/build/static/js/main.i3i391.js

path/to/wp-theme/build/static/css/styles.91k1j2.css

Aim

To have a path that wont change and then place it in my Wordpress function and use it in development builds (and production if possible) so when I experience Webpack's hot reload it happens from inside my Wordpress configurations.

Kinda like this:

function theme_register_scripts() {
    wp_enqueue_style( 'styles', get_stylesheet_uri() . 'build/static/css/styles.css' );
    wp_enqueue_script( 'scripts', esc_url(trailingslashit( get_template_directory_uri()) . 'build/static/js/main.js' ), NULL, '1.0', true);
}

I'm ready to configure my webpack configurations, as I have already done

npm run eject

to show my webpack and other behind the scene configurations but it was pretty confussing to know what button to press and what to avoid.

Body:
After some more reading, I understood my misconceptions and thought I should post an answer to help others.

Wordpress 4.7 and higher comes integrated with Rest API features and thus no need for a plugin installation.

Just after starting your Wordpress a quick hit on

http://localhost/wp-json/

will give you the json body if not then

http://localhost/binladen/?rest_route=/

Will do.

If you are using create-react-app (or Webpack for that matter) for your react theme development and you want to keep your HMR as you write your React front-end without creating the bundle everytime then don't worry about Wordpress. It can safely stay on one tab and your front-end in another.

You'll be using the WP Rest API to call for Wordpress resources on your React's logic and until your front-end is finished or you are satisfied with it is when you can include it in your Wordpress bundle and ship your Wordpress site with that React theme.

Building your front-end production bundle (with create-react-app)

npm run build

and included the created React bundle produced by the above code in Wordpress theme functions file.

function theme_register_scripts() {
    wp_enqueue_style( 'styles', get_stylesheet_uri() . 'build/static/css/styles.1k9s92.css' );
    wp_enqueue_script( 'scripts', esc_url(trailingslashit( get_template_directory_uri()) . 'build/static/js/bundle.i1929a.js' ), NULL, '1.0', true);
}

Sources.

create-react-app: Source

Multiple WP Rest API & React integration source & articles: Source

Multiple routes to WP Rest API: Source

Olypos WP template theme: Source


问:
I/O error 530 when running crystal reports
Since updating to Windows 10 1709, crystal reports appears to crash when selecting a report to run. It displays an I/O error : 530.

I have never seen this before, has anybody else come across this?, I've been looking online for further help but haven't really found anything.

Any suggestions would be much appreciated, thanks.

答: This issue was specific to certain manufacturers PCs, in this case - Dell. Preinstalled Dell software on the PCs was causing some sort of confliction. I uninstalled these software packages and it all appears to be working now.</p>


问:
Get data from New York Times API JSON response
I'm currently working with NewYorkTimes news API. I receive this JSON response. And now I want to loop through it using PHP and get each of articles (image, title and excerpt).

```<code>{
  "status": "OK",
  "copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.",
  "response": {
    "docs": [
      {
        "web_url": "https://www.nytimes.com/reuters/2017/11/15/business/15reuters-square-bitcoin.html",
        "snippet": "Payments company Square Inc said it has started allowing select customers to buy and sell bitcoins on its Cash app, as it looks to tap into a craze that has sent the cryptocurrency up nearly sevenfold this year.",
        "blog": {},
        "source": "Reuters",
        "multimedia": [],
        "headline": {
          "main": "Payments Company Square Tests Bitcoin Buying and Selling",
          "print_headline": "Payments Company Square Tests Bitcoin Buying and Selling"
        },
        "keywords": [],
        "pub_date": "2017-11-15T18:24:36+0000",
        "document_type": "article",
        "new_desk": "None",
        "byline": {
          "original": "By REUTERS"
        },
        "type_of_material": "News",
        "_id": "5a0c866b7c459f246b6349f9",
        "word_count": 388,
        "score": 2.5538578,
        "uri": "nyt://article/1dff4a88-4086-507c-b644-33e0d7d95e28"
      },
      {
        "web_url": "https://www.nytimes.com/reuters/2017/11/13/business/13reuters-investment-summit-fink-bitcoin.html",
        "snippet": "Bitcoin, whose value has fluctuated significantly this month, remains a \"speculative\" investment that thrives because of the cryptocurrency's anonymous nature, BlackRock Inc Chief Executive Larry Fink said on Monday.",
        "blog": {},
        "source": "Reuters",
        "multimedia": [],
        "headline": {
          "main": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity",
          "print_headline": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity"
        },
        "keywords": [],
        "pub_date": "2017-11-13T17:45:33+0000",
        "document_type": "article",
        "new_desk": "None",
        "byline": {
          "original": "By REUTERS"
        },
        "type_of_material": "News",
        "_id": "5a09da4a7c459f246b63428d",
        "word_count": 322,
        "score": 2.5538578,
        "uri": "nyt://article/bb396871-c686-5afc-9e71-3f9f5af8dac1"
      }
    ],
    "meta": {
      "hits": 959,
      "offset": 0,
      "time": 7
    }
  }
}
</code>```

Firstly I used  $arr = json_decode($result); to decode my json.
But when I tried to make a loop it doesnt return me anything

```<code>foreach($arr['docs'] as $article){
    echo $article['web_url'];
}
</code>```

Please help me to loop through this JSON response and get neccessary data. Thank you!

答:
try this

```<code>$json = json_decode($response, true);
foreach($json['response']['docs'] as $key => $value)
{
  if(!empty($value['web_url']))
  {
   $WEB= $value['web_url'];
   $WEB= addslashes($WEB);
   $WEB= trim(preg_replace('/\s\s+/', ' ', $WEB));
  }
  else
  {
    $WEB= '';
  }
   echo 'WEB= '.$WEB.'</br>';
}
</code>```

just make sure the foreach is true, maybe can help.

Body:
I'm currently working with NewYorkTimes news API. I receive this JSON response. And now I want to loop through it using PHP and get each of articles (image, title and excerpt).

{
  "status": "OK",
  "copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.",
  "response": {
    "docs": [
      {
        "web_url": "https://www.nytimes.com/reuters/2017/11/15/business/15reuters-square-bitcoin.html",
        "snippet": "Payments company Square Inc said it has started allowing select customers to buy and sell bitcoins on its Cash app, as it looks to tap into a craze that has sent the cryptocurrency up nearly sevenfold this year.",
        "blog": {},
        "source": "Reuters",
        "multimedia": [],
        "headline": {
          "main": "Payments Company Square Tests Bitcoin Buying and Selling",
          "print_headline": "Payments Company Square Tests Bitcoin Buying and Selling"
        },
        "keywords": [],
        "pub_date": "2017-11-15T18:24:36+0000",
        "document_type": "article",
        "new_desk": "None",
        "byline": {
          "original": "By REUTERS"
        },
        "type_of_material": "News",
        "_id": "5a0c866b7c459f246b6349f9",
        "word_count": 388,
        "score": 2.5538578,
        "uri": "nyt://article/1dff4a88-4086-507c-b644-33e0d7d95e28"
      },
      {
        "web_url": "https://www.nytimes.com/reuters/2017/11/13/business/13reuters-investment-summit-fink-bitcoin.html",
        "snippet": "Bitcoin, whose value has fluctuated significantly this month, remains a \"speculative\" investment that thrives because of the cryptocurrency's anonymous nature, BlackRock Inc Chief Executive Larry Fink said on Monday.",
        "blog": {},
        "source": "Reuters",
        "multimedia": [],
        "headline": {
          "main": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity",
          "print_headline": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity"
        },
        "keywords": [],
        "pub_date": "2017-11-13T17:45:33+0000",
        "document_type": "article",
        "new_desk": "None",
        "byline": {
          "original": "By REUTERS"
        },
        "type_of_material": "News",
        "_id": "5a09da4a7c459f246b63428d",
        "word_count": 322,
        "score": 2.5538578,
        "uri": "nyt://article/bb396871-c686-5afc-9e71-3f9f5af8dac1"
      }
    ],
    "meta": {
      "hits": 959,
      "offset": 0,
      "time": 7
    }
  }
}

Firstly I used  $arr = json_decode($result); to decode my json.
But when I tried to make a loop it doesnt return me anything

foreach($arr['docs'] as $article){
    echo $article['web_url'];
}

Please help me to loop through this JSON response and get neccessary data. Thank you!

Body:
try this

$json = json_decode($response, true);
foreach($json['response']['docs'] as $key => $value)
{
  if(!empty($value['web_url']))
  {
   $WEB= $value['web_url'];
   $WEB= addslashes($WEB);
   $WEB= trim(preg_replace('/\s\s+/', ' ', $WEB));
  }
  else
  {
    $WEB= '';
  }
   echo 'WEB= '.$WEB.'</br>';
}

just make sure the foreach is true, maybe can help.


问:
ADB Install Fails With INSTALL_FAILED_TEST_ONLY
I am having issues installing an apk to my device.

```<code>adb install <.apk>
</code>```

Using the above command returns the following:

```<code>5413 KB/s (99747 bytes in 0.017s)
        pkg: /data/local/tmp/AppClient.TestOnly.App3.apk
Failure [INSTALL_FAILED_TEST_ONLY]
</code>```

Any idea on what might cause this issue?

It definitely recognizes the device.  Could it be an issue with the apk?

答:
I see the accepted answer  but  you dont have to actually  push the apk and then run the  command on adb shell  direct  adb install with -t flag  actually works

adb install -t "path to apk in ur  computer"

attaching a screenshot for reference

Body:
I am having issues installing an apk to my device.

adb install <.apk>

Using the above command returns the following:

5413 KB/s (99747 bytes in 0.017s)
        pkg: /data/local/tmp/AppClient.TestOnly.App3.apk
Failure [INSTALL_FAILED_TEST_ONLY]

Any idea on what might cause this issue?

It definitely recognizes the device.  Could it be an issue with the apk?


问:
UIScrollView added in code is not being scrolled anymore
This is what I simply do in code:

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let scroll = UIScrollView()
    scroll.backgroundColor = .yellow
    scroll.translatesAutoresizingMaskIntoConstraints = false

    let leading = NSLayoutConstraint(item: scroll, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    let trailing = NSLayoutConstraint(item: scroll, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    let top = NSLayoutConstraint(item: scroll, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
    let bottom = NSLayoutConstraint(item: scroll, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)

    view.addSubview(scroll)
    view.addConstraints([leading, trailing, top, bottom])

    let label = UILabel()
    label.text = "helloo, my new text"
    label.backgroundColor = .orange
    label.translatesAutoresizingMaskIntoConstraints = false

    let leading2 = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: scroll, attribute: .leading, multiplier: 1, constant: 0)
    let trailing2 = NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: scroll, attribute: .trailing, multiplier: 1, constant: 0)
    let top2 = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: scroll, attribute: .top, multiplier: 1, constant: 200)
    let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 400)
    let height2 = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 600)

    scroll.addSubview(label)
    label.addConstraint(height2)
    scroll.addConstraints([leading2, trailing2, top2, bottom2])
    scroll.layoutIfNeeded()
}
</code>```

This is how it looks on the screen:

But I cannot scroll it at all. Why? What is wrong here?

I know there is a lot of examples and questions on SO, but not even one works.

答:
You have given wrong bottom constraint to label. Change the constant value from 400 to 0.

```<code>let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0)
</code>```

Body:
This is what I simply do in code:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let scroll = UIScrollView()
    scroll.backgroundColor = .yellow
    scroll.translatesAutoresizingMaskIntoConstraints = false

    let leading = NSLayoutConstraint(item: scroll, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    let trailing = NSLayoutConstraint(item: scroll, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    let top = NSLayoutConstraint(item: scroll, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
    let bottom = NSLayoutConstraint(item: scroll, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)

    view.addSubview(scroll)
    view.addConstraints([leading, trailing, top, bottom])

    let label = UILabel()
    label.text = "helloo, my new text"
    label.backgroundColor = .orange
    label.translatesAutoresizingMaskIntoConstraints = false

    let leading2 = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: scroll, attribute: .leading, multiplier: 1, constant: 0)
    let trailing2 = NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: scroll, attribute: .trailing, multiplier: 1, constant: 0)
    let top2 = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: scroll, attribute: .top, multiplier: 1, constant: 200)
    let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 400)
    let height2 = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 600)

    scroll.addSubview(label)
    label.addConstraint(height2)
    scroll.addConstraints([leading2, trailing2, top2, bottom2])
    scroll.layoutIfNeeded()
}

This is how it looks on the screen:

But I cannot scroll it at all. Why? What is wrong here?

I know there is a lot of examples and questions on SO, but not even one works.

Body:
You have given wrong bottom constraint to label. Change the constant value from 400 to 0.

let bottom2 = NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0)


问:
Communication between Activity and Service
I am trying to make my own MusicPlayer for android. Where i came to a problem is running some things in background. Main activity manages GUI and up to now all the songs are playing. I wanted to separate GUI and music playing classes. I want to put music managing part in Service and leave other things as they are now.

My problem is that i can't organize communication between Activity and Service as lot of communication is happening between them including moving objects in both directions. I tried many techniques that I searched here on Stack Overflow but every time I had problems. I need Service to be able to send objects to Activity and vice versa. When I add widget i also want it to be able to communicate with Service.

Any tips are appreciated, if you need source code place comment bellow but now in this transition it became chaotic.

Is there any more advanced tutorial on this than calling one method that returns random number from service? :P

EDIT: Possible solution is to use RoboGuice library and move objects with injection

答: Very easy yet powerful way is to use EventBus you can add it to your gradle build and enjoy the easy  publisher/subscriber pattern .


问:
Why are only final variables accessible in anonymous class?

a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

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

How can I return the 5 * a when it clicked? I mean,

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}
</code>```

答:
There is a trick that allows anonymous class to update data in the outer scope.

```<code>private void f(Button b, final int a) {
    final int[] res = new int[1];
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            res[0] = a * 5;
        }
    });

    // But at this point handler is most likely not executed yet!
    // How should we now res[0] is ready?
}
</code>```

However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated

This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:

```<code>// ...

final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);

// ...
</code>```

Body:
a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}

How can I return the 5 * a when it clicked? I mean,

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}

Body:
There is a trick that allows anonymous class to update data in the outer scope.

private void f(Button b, final int a) {
    final int[] res = new int[1];
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            res[0] = a * 5;
        }
    });

    // But at this point handler is most likely not executed yet!
    // How should we now res[0] is ready?
}

However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated

This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:

// ...

final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);

// ...


问:
Lazy loading in ionic3 , but it was wrong : No component factory found

I use Lazy loading in ionic3 , but when it serve , then browser show the error:

Failed to navigate:  No component factory found for TabsPage. Did you
  add it to @NgModule.entryComponents?

here's my code :

app.module.ts

```<code>@NgModule({
  declarations: [
    MyApp,
    FormModal,
    PreviewModal,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule,
    CommonModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
  ],
  providers: [
    Router,
    StatusBar,
    SplashScreen,
    ApiService,
    Toast,
    Loading,
    Alert,
    UserService,
    ChangeTitle,
    ParseLogin,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

app.component.ts

```<code>@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  rootPage:any = "TabsPage";

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,router:Router) {
    router.setVersion('1.0',10000);
    router.load(Routes);
    Event.subscribe('push',(ev,data)=>{
      document.title =Routes[data.toPage.name].title;
      var i = document.createElement('iframe');
      i.src = 'blank.html';
      i.style.display = 'none';
      i.onload = function() {
        setTimeout(function(){
          i.remove();
        }, 9)
      }
      document.body.appendChild(i);

    })
    Event.subscribe('pop',(ev,data)=>{
      if(!data.toPage.name||!Routes[data.toPage.name])return;//这里应该关闭微信页面
      document.title =Routes[data.toPage.name].title;
      var i = document.createElement('iframe');
      i.src = 'blank.html';
      i.style.display = 'none';
      i.onload = function() {
        setTimeout(function(){
          i.remove();
        }, 9)
      }
      document.body.appendChild(i);
      console.log(data);
    })
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}
</code>```

tabs.html

```<code><ion-tabs selectedIndex="{{selectedIndex}}">
    <ion-tab [root]="tab1Root" tabTitle="发现" tabIcon="eye" (ionSelect)="chat('发现')"></ion-tab>
    <ion-tab [root]="tab2Root" tabTitle="活动" tabIcon="paper-plane" (ionSelect)="chat('活动')"></ion-tab>
    <ion-tab [root]="tab3Root" tabTitle="君读" tabIcon="book" (ionSelect)="chat('君读')"></ion-tab>
    <ion-tab [root]="tab4Root" tabTitle="我" tabIcon="person" (ionSelect)="chat('我')"></ion-tab>
</ion-tabs>
</code>```

tabs.module.ts

```<code>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TabsPage } from './tabs';

@NgModule({
  declarations: [
    TabsPage,
  ],
  imports: [
    IonicPageModule.forChild(TabsPage)
  ],
  exports: [
    TabsPage
  ]
})
export class TabsPageModule {}
</code>```

tabs.ts

```<code>import { Component} from '@angular/core';
import { NavParams ,IonicPage} from 'ionic-angular';
import{ChangeTitle} from"../../components/changeTitle"

@IonicPage()
@Component({
  templateUrl: 'tabs.html'
})

export class TabsPage {

  tab1Root = "FinderPage";
  tab2Root = "ListPage";
  tab3Root = "ArticleListPage";
  tab4Root = "UserPage";
  selectedIndex:string='0';

  constructor(public changeTitle:ChangeTitle,public navParams: NavParams) {
       this.selectedIndex=this.navParams.get("index");
       if (!this.selectedIndex){
          this.selectedIndex = '0'; // 默认发现首页
       }
  }
  chat(title){
    console.log(title);
    this.changeTitle.changeDomTitle(title);
  }
}
</code>```

but after i run comman : ‘ionic serve’ , my browser is show the error:

Failed to navigate:  No component factory found for TabsPage. Did you
  add it to @NgModule.entryComponents?

答: If you are exporting TabsPageModule then there is no need of these formalities like exports:[TabsPage] orentryComponents: [TabsPage] . Only you have to take care of whenever you are pushing or poppinng the tabspage through nav , push it as a string this.navCtrl.push('AboutusPage');

Body:
I use Lazy loading in ionic3 , but when it serve , then browser show the error:

Failed to navigate:  No component factory found for TabsPage. Did you
  add it to @NgModule.entryComponents?

here's my code :

app.module.ts

@NgModule({
  declarations: [
    MyApp,
    FormModal,
    PreviewModal,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule,
    CommonModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
  ],
  providers: [
    Router,
    StatusBar,
    SplashScreen,
    ApiService,
    Toast,
    Loading,
    Alert,
    UserService,
    ChangeTitle,
    ParseLogin,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

app.component.ts

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  rootPage:any = "TabsPage";

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,router:Router) {
    router.setVersion('1.0',10000);
    router.load(Routes);
    Event.subscribe('push',(ev,data)=>{
      document.title =Routes[data.toPage.name].title;
      var i = document.createElement('iframe');
      i.src = 'blank.html';
      i.style.display = 'none';
      i.onload = function() {
        setTimeout(function(){
          i.remove();
        }, 9)
      }
      document.body.appendChild(i);

    })
    Event.subscribe('pop',(ev,data)=>{
      if(!data.toPage.name||!Routes[data.toPage.name])return;//这里应该关闭微信页面
      document.title =Routes[data.toPage.name].title;
      var i = document.createElement('iframe');
      i.src = 'blank.html';
      i.style.display = 'none';
      i.onload = function() {
        setTimeout(function(){
          i.remove();
        }, 9)
      }
      document.body.appendChild(i);
      console.log(data);
    })
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

tabs.html

<ion-tabs selectedIndex="{{selectedIndex}}">
    <ion-tab [root]="tab1Root" tabTitle="发现" tabIcon="eye" (ionSelect)="chat('发现')"></ion-tab>
    <ion-tab [root]="tab2Root" tabTitle="活动" tabIcon="paper-plane" (ionSelect)="chat('活动')"></ion-tab>
    <ion-tab [root]="tab3Root" tabTitle="君读" tabIcon="book" (ionSelect)="chat('君读')"></ion-tab>
    <ion-tab [root]="tab4Root" tabTitle="我" tabIcon="person" (ionSelect)="chat('我')"></ion-tab>
</ion-tabs>

tabs.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TabsPage } from './tabs';

@NgModule({
  declarations: [
    TabsPage,
  ],
  imports: [
    IonicPageModule.forChild(TabsPage)
  ],
  exports: [
    TabsPage
  ]
})
export class TabsPageModule {}

tabs.ts

import { Component} from '@angular/core';
import { NavParams ,IonicPage} from 'ionic-angular';
import{ChangeTitle} from"../../components/changeTitle"

@IonicPage()
@Component({
  templateUrl: 'tabs.html'
})

export class TabsPage {

  tab1Root = "FinderPage";
  tab2Root = "ListPage";
  tab3Root = "ArticleListPage";
  tab4Root = "UserPage";
  selectedIndex:string='0';

  constructor(public changeTitle:ChangeTitle,public navParams: NavParams) {
       this.selectedIndex=this.navParams.get("index");
       if (!this.selectedIndex){
          this.selectedIndex = '0'; // 默认发现首页
       }
  }
  chat(title){
    console.log(title);
    this.changeTitle.changeDomTitle(title);
  }
}

but after i run comman : ‘ionic serve’ , my browser is show the error:

Failed to navigate:  No component factory found for TabsPage. Did you
  add it to @NgModule.entryComponents?


问:
How to change color of bootstrap glyphicon .?
How do I change the color of my star glyphicon? My code is

```<code><span  class="glyphicon glyphicon-star-empty " onclick = "addToFav()">      </span>
</code>```

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

答:
```<code> <span class="glyphicon glyphicon-print" style="color:red;background-color:blue;padding:10px"></span>
</code>```

<p>you can change how ever you want like color,background-color,padding change it </p>

Body:
How do I change the color of my star glyphicon? My code is

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

Body:
 <span class="glyphicon glyphicon-print" style="color:red;background-color:blue;padding:10px"></span>

you can change how ever you want like color,background-color,padding change it


问:
JavaScript user input text to options value not sending to php
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

```<code><?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        <label for="items">List of items</label><br />
        <div class="form-section">
            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">
    </div>

<script type="text/javascript">

       function displayQuantity(noOfitems, labelVal)  {
          var qq = noOfitems;
          var labelName = labelVal;
          var quoteQuantity = document.getElementById("qlist");
          var quantity = quoteQuantity.value;
          quantity += labelName + ": ";
          quantity += qq;
          quantity += " pcs\n";
          quoteQuantity.value = quantity;
          var option = document.createElement("option");
          option.text = quantity;
          quoteQuantity.add(option);

       }

       function deleteEntry() {
          var myList = document.getElementById('qlist');
          var i;
          for (i = myList.length - 1; i>=0; i--) {
              if (myList.options[i].selected) {
                  myList.remove(i);
              }
          }
       }
</script>
</code>```

iframe.php

```<code><div class="order-quantity">
   <form name="form">
        <label id="itemType">Heavy Duty Square Core Drilled</label>
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>
</div>

    <script type="text/javascript">
    function getVal() {
       var labelVal = document.getElementById("itemType").textContent;
       return labelVal;
    }
    </script>
</code>```

答:
From

```<code> foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }
</code>```

to

```<code>$Data = $_POST["qlist"];
      foreach ($Data as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
      $body = $selectList;
      }
</code>```

Body:
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

<?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        List of items

            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">

iframe.php

   <form name="form">
        Heavy Duty Square Core Drilled
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>

Body:
From

 foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

to

$Data = $_POST["qlist"];
      foreach ($Data as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
      $body = $selectList;
      }


问:
Removing space between h1 and h2
I have stumbled across a problem that I can not seem to solve in any way, maybe I am using divs in a wrong way?

.greeting h1 {
  font-family: 'Raleway', sans-serif;
  font-weight: lighter;
  font-size: 100px;
  text-align: center
}
.greeting h2 {
  font-family: 'Raleway', sans-serif;
  font-weight: lighter;
  font-size: 35px;
  line-height: 0px;
  text-align: center
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="greeting">
  <h1>Hi.</h1>
  <h2>Select a group</h2>
</div></code>```

This is the outcome:

I want to decrease the space between my
 and
, and I found out that the way to do that was to set line-height in h1 to 0px.

But as I do that my entire page moves up like so:

I want to keep the text at the same position as it was before I change the line-height. I am suspecting that I am using the div class function wrong. This is more of theoretical question.

答:
Just add the following lines</p>

```<code>.greeting h1 {
  margin:0px;
  line-height:35px;
}
.greeting h2 {
  margin:0px;
  line-height:35px;
}
</code>```

Title: Removing space between h1 and h2

Body:
I have stumbled across a problem that I can not seem to solve in any way, maybe I am using divs in a wrong way?

.greeting h1 {
  font-family: 'Raleway', sans-serif;
  font-weight: lighter;
  font-size: 100px;
  text-align: center
}
.greeting h2 {
  font-family: 'Raleway', sans-serif;
  font-weight: lighter;
  font-size: 35px;
  line-height: 0px;
  text-align: center
}

Hi.

Select a group

This is the outcome:

I want to decrease the space between my
 and
, and I found out that the way to do that was to set line-height in h1 to 0px.

But as I do that my entire page moves up like so:

I want to keep the text at the same position as it was before I change the line-height. I am suspecting that I am using the div class function wrong. This is more of theoretical question.

Body:
Just add the following lines

.greeting h1 {
  margin:0px;
  line-height:35px;
}
.greeting h2 {
  margin:0px;
  line-height:35px;
}


问:
jquery traversing an appended to ol/ul
I'm trying to traverse a ul that has been appended to before traversing like so:

```<code>var items = [];
$('#list').append('<li id="item_10">item 10</li>');
$('#list').each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());
</code>```

But when I alert the output I don't see the item I added. Anyone have a clue on how I can add to a list then traverse it?

答:
What andy said.

Also consider using jQuery awesome chainability:

```<code>var items = [];
$('#list')
.append('<li id="item_10">item 10</li>')
.find('li')
.each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());
</code>```

Title: jquery traversing an appended to ol/ul

Body:
I'm trying to traverse a ul that has been appended to before traversing like so:

var items = [];
$('#list').append('
item 10
');
$('#list').each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());

But when I alert the output I don't see the item I added. Anyone have a clue on how I can add to a list then traverse it?

Body:
What andy said.

Also consider using jQuery awesome chainability:

var items = [];
$('#list')
.append('<li id="item_10">item 10</li>')
.find('li')
.each(function () {
    var item = $(this).attr('id');
    items.push(item);
});
alert(items.toString());


问:
jQuery attr() method to change a class name
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}</code>```

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

```

答:
Change $('h1').attr('class', +fontChange); To

$('h1').attr('class', fontChange);

function myFontStyle() {
    $('#font').on("change", function() {
    var fontChange = this.value
    //console.log(this.value);

    $('h1').attr('class', fontChange);
    console.log('h1 has now class: ', $('h1').attr('class'))
  });

}
myFontStyle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="font">Choose font</label>
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

<div class="card celadonBackground">
  <div id="coverImage">
    <img src="assets/birthday.jpg"/>
  </div>
  <div class="noBorder">
    <h1 class="sketch">Happy birthday to you</h1>
  </div>
</div></code>```

Body:
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();

.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

Body:
Change $('h1').attr('class', +fontChange); To

$('h1').attr('class', fontChange);

function myFontStyle() {
    $('#font').on("change", function() {
    var fontChange = this.value
    //console.log(this.value);

    $('h1').attr('class', fontChange);
    console.log('h1 has now class: ', $('h1').attr('class'))
  });

}
myFontStyle();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="font">Choose font</label>
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

<div class="card celadonBackground">
  <div id="coverImage">
    <img src="assets/birthday.jpg"/>
  </div>
  <div class="noBorder">
    <h1 class="sketch">Happy birthday to you</h1>
  </div>
</div>


问:
Using derived abstract classes to define different logic used by Model
I am currently setting up an architecture that should allow me to set up multiple derived classes of an abstract base class. These classes will implement the actual logic of the methods and assign values to the properties.

I have a model that should implement a specific logic from the respecting class, depending on a property.

```<code>public abstract class AbstractLogic
{
    protected String Prop1 { get; set; }
    public abstract String Method1();
}

public class ActualLogic : AbstractLogic
    {
        public ActualLogic()
        {
           Prop1 = "Test";
        }

        public override string Method1()
        {
            throw new NotImplementedException();
        }

    }

public class Model
{
    public string LogicType { get; set; }
    private AbstractLogic Logic { get; set; } //I need to have something like this to use the logic inside of the model
}
</code>```

I want to use the classes in a generic way, for example calling Model.logic.Method1() somewhere and it should pull the logic from the ActualLogic class

My problem with this architecture is that when I load the Model, the Logic property is always null and thus working with it is very hard and it feels inconsistent.

I can't really wrap my head around a better solution, so maybe someone can help me with this. Maybe an interface would be better? Or a generic class? I tried both, but couldn't get a better result.

Thank you in advance.

Edit

Moved my own answer to an answer.

答:
I found an even better way to access the right logic class:
In my Model, I define a property enum LogicType and just access the respecting LogicClass using an extension method.

```<code>public enum LogicType
    {
        actuallogic,
        actuallogic2
    }

    public static class LogicExtensions
    {
        public static AbstractLogic LogicClass(this LogicType self)
        {
            switch (self)
            {
                case LogicType.actuallogic:
                    return new ActualLogic();
                case LogicType.actuallogic2:
                    return new ActualLogic2();
                default:
                    return null;
            }
        }
    }
</code>```

Now I can access it like this Model.LogicType.LogicClass()

Body:
I am currently setting up an architecture that should allow me to set up multiple derived classes of an abstract base class. These classes will implement the actual logic of the methods and assign values to the properties.

I have a model that should implement a specific logic from the respecting class, depending on a property.

public abstract class AbstractLogic
{
    protected String Prop1 { get; set; }
    public abstract String Method1();
}

public class ActualLogic : AbstractLogic
    {
        public ActualLogic()
        {
           Prop1 = "Test";
        }

        public override string Method1()
        {
            throw new NotImplementedException();
        }

    }

public class Model
{
    public string LogicType { get; set; }
    private AbstractLogic Logic { get; set; } //I need to have something like this to use the logic inside of the model
}

I want to use the classes in a generic way, for example calling Model.logic.Method1() somewhere and it should pull the logic from the ActualLogic class

My problem with this architecture is that when I load the Model, the Logic property is always null and thus working with it is very hard and it feels inconsistent.

I can't really wrap my head around a better solution, so maybe someone can help me with this. Maybe an interface would be better? Or a generic class? I tried both, but couldn't get a better result.

Thank you in advance.

Edit

Moved my own answer to an answer.

Body:
I found an even better way to access the right logic class:
In my Model, I define a property enum LogicType and just access the respecting LogicClass using an extension method.

public enum LogicType
    {
        actuallogic,
        actuallogic2
    }

    public static class LogicExtensions
    {
        public static AbstractLogic LogicClass(this LogicType self)
        {
            switch (self)
            {
                case LogicType.actuallogic:
                    return new ActualLogic();
                case LogicType.actuallogic2:
                    return new ActualLogic2();
                default:
                    return null;
            }
        }
    }

Now I can access it like this Model.LogicType.LogicClass()


问:
Webview In Ionic 3
I have my one blog which i want to convert into ionic app.
I use InAppBrowser plugin but the problem is when i press the back button it will come to my default ionic home page.

i follow the below steps :

ionic start myblog

ionic platform add android

ionic cordova plugin add cordova-plugin-inappbrowser

npm install --save @ionic-native/in-app-browser

and then added provider in app.module and in home.ts write the following.

```<code>import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(private iab: InAppBrowser) { }

...

const browser = this.iab.create('https://ionicframework.com/','_self','location=no');
browser.show();
</code>```

Also location=no is not working.
Like android ionic provide the webview ??
can anyone help me out ?
any help is appreciated. :)

答:
Simple and sort solution from the my github repo

in home.html

```<code><iframe  height="100%" width="100%" [src]="urlpaste()"></iframe>
</code>```

and in home.ts

```<code>import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  url: any;
  constructor(private sanitize: DomSanitizer) {}
  urlpaste(){
    this.url = "https://hackerrankgeek.wordpress.com/";
    return this.sanitize.bypassSecurityTrustResourceUrl(this.url);
  }
}
</code>```

Title: Webview In Ionic 3

Body:
I have my one blog which i want to convert into ionic app.
I use InAppBrowser plugin but the problem is when i press the back button it will come to my default ionic home page.

i follow the below steps :

ionic start myblog

ionic platform add android

ionic cordova plugin add cordova-plugin-inappbrowser

npm install --save @ionic-native/in-app-browser

and then added provider in app.module and in home.ts write the following.

import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(private iab: InAppBrowser) { }

...

const browser = this.iab.create('https://ionicframework.com/','_self','location=no');
browser.show();

Also location=no is not working.
Like android ionic provide the webview ??
can anyone help me out ?
any help is appreciated. :)

Body:
Simple and sort solution from the my github repo

in home.html

<iframe  height="100%" width="100%" [src]="urlpaste()"></iframe>

and in home.ts

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  url: any;
  constructor(private sanitize: DomSanitizer) {}
  urlpaste(){
    this.url = "https://hackerrankgeek.wordpress.com/";
    return this.sanitize.bypassSecurityTrustResourceUrl(this.url);
  }
}

ContentLicense: CC BY-SA 4.0