问:
Nodejs - Return array of key-value pair by adding values with same key
I have the following array of objects:

```<code>const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]
</code>```

And I want to end up with and object that returns a list of data-sets that contains the sum of points for each name like:

```<code>const list2 = [
  {name: 'bob', points: 6}, // sum of all of bob's points
  {name: 'john', points: 16}
]
</code>```

I need this so that I can use the resulting data set to generate a line chart.

Is there a way to do this, preferably using ramda.js?

答:
This is a fairly trivial use of Array.prototype.reduce() and Object.keys():</p>

```<code>const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

const map = list.reduce((prev, next) => {
  // if the name has not already been observed, create a new entry with 0 points
  if (prev[next.name] == null) {
    prev[next.name] = 0;
  }

  // add the new points
  prev[next.name] += next.points;

  return prev;
}, {});

// map is now an object containing { [name]: [points] }
// convert this back into an array of entries
const list2 = Object.keys(map)
  .map(name => ({ name, points: map[name] }));

console.log(list2)
// [ { name: 'bob', points: 6 }, { name: 'john', points: 16 } ]
</code>```

Body:
I have the following array of objects:

const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

And I want to end up with and object that returns a list of data-sets that contains the sum of points for each name like:

const list2 = [
  {name: 'bob', points: 6}, // sum of all of bob's points
  {name: 'john', points: 16}
]

I need this so that I can use the resulting data set to generate a line chart.

Is there a way to do this, preferably using ramda.js?

Body:
This is a fairly trivial use of Array.prototype.reduce() and Object.keys():

const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

const map = list.reduce((prev, next) => {
  // if the name has not already been observed, create a new entry with 0 points
  if (prev[next.name] == null) {
    prev[next.name] = 0;
  }

  // add the new points
  prev[next.name] += next.points;

  return prev;
}, {});

// map is now an object containing { [name]: [points] }
// convert this back into an array of entries
const list2 = Object.keys(map)
  .map(name => ({ name, points: map[name] }));

console.log(list2)
// [ { name: 'bob', points: 6 }, { name: 'john', points: 16 } ]


来源: stackexchange

问:
Call Function in Main Target From Test Target in Xcode(swift)
I am writing UITest for my app. In some parts of the UITest, I should call functions from Main target. When I create an Object from the Class(that has the implementation of the function), I get the error "use of undeclared of type CLASSNAME". I added the Class to the Compile Source of the test target.Then I get the same error but this time for the super class.
I added Classes to the compile source again and again, till I get this error  "use of undeclared of UITextField, UIColor."
UITextField and UIColor are part of UIkit, then I import UIkit to my test Class , but did not work.
Any idea how to solve it?
In generell, How should we call functions in main target from test target?
Thanks a lot.</p>

答:
import your target with @testable import</p>

```<code>import XCTest
@testable import MyProject
</code>```

ContentLicense: CC BY-SA 3.0

Body:
import your target with @testable import

import XCTest
@testable import MyProject


问:
Add suffix to comma-separated strings in bash ecosystem
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

```<code>VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`
</code>```

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

答:
```<code>echo "aaa,bbb,ccc" | sed -E 's/([^,]+)/\1-foo/g'
</code>```

It makes groups of characters that are not "," and then append -foo on it

With variables:

```<code>suffix="-foo"; VARIABLE="aaa,bbb,ccc"; echo ${VARIABLE} | sed -E "s/([^,]+)/\1${suffix}/g"
</code>```

Body:
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

Body:
echo "aaa,bbb,ccc" | sed -E 's/([^,]+)/\1-foo/g'

It makes groups of characters that are not "," and then append -foo on it

With variables:

suffix="-foo"; VARIABLE="aaa,bbb,ccc"; echo ${VARIABLE} | sed -E "s/([^,]+)/\1${suffix}/g"


问:
HIVE Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
I am getting the below error on creating a hive database

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. com/facebook/fb303/FacebookService$Iface

Hadoop version:**hadoop-1.2.1**

HIVE Version: **hive-0.12.0**

Hadoop path:/home/hadoop_test/data/hadoop-1.2.1

hive path :/home/hadoop_test/data/hive-0.12.0

I have copied hive*.jar ,jline-.jar,antlr-runtime.jar from hive-0.12.0/lib to hadoop-1.2./lib

答:
```<code>set hive.msck.path.validation=ignore;
MSCK REPAIR TABLE table_name;
</code>```

<p>Make sure the location is specified correctly </p>

Body:
set hive.msck.path.validation=ignore;
MSCK REPAIR TABLE table_name;

Make sure the location is specified correctly


问:
Rmarkdown Parameterized Reports - Can't access data from selected file
I have exactly the same problem as defined in a previous post (How do I access the data from a file passed as parameters in a RMarkdown document?), and I don't find (StackOverflow, google...) any clue to solve it !

With the default filename, it works! With the selected file (which could be the same file), I get an error.

```<code>Quitting from lines 51-51 (WBD_MCS.Rmd)
Error in file(file, "rt") : cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> read.csv2 -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'C:\Users\SESA40~1\AppData\Local\Temp\RtmpaMmix8/a6232463beeca55dd111a939/0': No such file or directory
Execution halted
</code>```

I have the problem on MacOSX and Windows.

```<code>R version 3.2.5 (2016-04-14) -- "Very, Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: i386-w64-mingw32/i386 (32-bit)
</code>```

If someone can share a solution...

The header of my .Rmd file:

```<code>---
title: "Simulation de Monte Carlo pour une estimation Wideband Delphi"
author: "Alain BRET"
date: "28 avril 2016"
output:
  pdf_document:
    includes:
      before_body: tex/tex_before_body.tex
      in_header: tex/tex_header.tex
    number_sections: yes
    toc: yes
  html_document:
    number_sections: yes
    toc: yes
  word_document:
    toc: yes
params:
  nombre_occurences:
    input: slider
    label: "Nombre d'occurences:"
    max: 10000
    min: 1000
    step: 500
    value: 1000
  datafile:
    input: file
    label: 'Fichier des estimations des Experts:'
    value: data/estimation_data_2.csv
---
</code>```

答: This issue has been reported to rstudio/rmarkdown#919 and fixed in the version 1.7 of the rmarkdown package. It should suffice to install.packages('rmarkdown').

Body:
I have exactly the same problem as defined in a previous post (How do I access the data from a file passed as parameters in a RMarkdown document?), and I don't find (StackOverflow, google...) any clue to solve it !

With the default filename, it works! With the selected file (which could be the same file), I get an error.

Quitting from lines 51-51 (WBD_MCS.Rmd)
Error in file(file, "rt") : cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> read.csv2 -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'C:\Users\SESA40~1\AppData\Local\Temp\RtmpaMmix8/a6232463beeca55dd111a939/0': No such file or directory
Execution halted

I have the problem on MacOSX and Windows.

R version 3.2.5 (2016-04-14) -- "Very, Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: i386-w64-mingw32/i386 (32-bit)

If someone can share a solution...

The header of my .Rmd file:

---
title: "Simulation de Monte Carlo pour une estimation Wideband Delphi"
author: "Alain BRET"
date: "28 avril 2016"
output:
  pdf_document:
    includes:
      before_body: tex/tex_before_body.tex
      in_header: tex/tex_header.tex
    number_sections: yes
    toc: yes
  html_document:
    number_sections: yes
    toc: yes
  word_document:
    toc: yes
params:
  nombre_occurences:
    input: slider
    label: "Nombre d'occurences:"
    max: 10000
    min: 1000
    step: 500
    value: 1000
  datafile:
    input: file
    label: 'Fichier des estimations des Experts:'
    value: data/estimation_data_2.csv
---


问:
Replacing d3.csv to d3.csv.parse
I'm trying to use some d3 javascript template.

In my solution I have to replace d3.csv with d3.csv.parse method.

I'm having big problem to do that. I just can't understand how I have to change my code.

Here is link to template i'm using.
http://bl.ocks.org/KathyZ/c2d4694c953419e0509b

Here is my code:

```<code>        var width = 960,
    height = 750,
    cellSize = 25; // cell size

var no_months_in_a_row = Math.floor(width / (cellSize * 7 + 50));
var shift_up = cellSize * 3;

var day = d3.time.format("%w"), // day of the week
    day_of_month = d3.time.format("%e") // day of the month
    day_of_year = d3.time.format("%j")
    week = d3.time.format("%U"), // week number of the year
    month = d3.time.format("%m"), // month number
    year = d3.time.format("%Y"),
    percent = d3.format(".1%"),
    format = d3.time.format("%Y-%m-%d");

var color = d3.scale.quantize()
    .domain([-.05, .05])
    .range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));

var svg = d3.select("#chart").selectAll("svg")
    .data(d3.range(2017, 2018))
  .enter().append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("class", "RdYlGn")
  .append("g")

var rect = svg.selectAll(".day")
    .data(function(d) {
      return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1));
    })
  .enter().append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) {
      var month_padding = 1.2 * cellSize*7 * ((month(d)-1) % (no_months_in_a_row));
      return day(d) * cellSize + month_padding;
    })
    .attr("y", function(d) {
      var week_diff = week(d) - week(new Date(year(d), month(d)-1, 1) );
      var row_level = Math.ceil(month(d) / (no_months_in_a_row));
      return (week_diff*cellSize) + row_level*cellSize*8 - cellSize/2 - shift_up;
    })
    .datum(format);

var month_titles = svg.selectAll(".month-title")  // Jan, Feb, Mar and the whatnot
      .data(function(d) {
        return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
    .enter().append("text")
      .text(monthTitle)
      .attr("x", function(d, i) {
        var month_padding = 1.2 * cellSize*7* ((month(d)-1) % (no_months_in_a_row));
        return month_padding;
      })
      .attr("y", function(d, i) {
        var week_diff = week(d) - week(new Date(year(d), month(d)-1, 1) );
        var row_level = Math.ceil(month(d) / (no_months_in_a_row));
        return (week_diff*cellSize) + row_level*cellSize*8 - cellSize - shift_up;
      })
      .attr("class", "month-title")
      .attr("d", monthTitle);

var year_titles = svg.selectAll(".year-title")  // Jan, Feb, Mar and the whatnot
      .data(function(d) {
        return d3.time.years(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
    .enter().append("text")
      .text(yearTitle)
      .attr("x", function(d, i) { return width/2 - 100; })
      .attr("y", function(d, i) { return cellSize*5.5 - shift_up; })
      .attr("class", "year-title")
      .attr("d", yearTitle);

//  Tooltip Object
var tooltip = d3.select("body")
  .append("div").attr("id", "tooltip")
  .style("position", "absolute")
  .style("z-index", "10")
  .style("visibility", "hidden")
  .text("a simple tooltip");
</code>```

/* This is what dji.csv have right now and its working. But I like to use string insteed. */
    var dataIliketoUse = "Date,Open\n2010-10-01,1\n2010-09-30,1";

```<code>d3.csv("dji.csv", function(error, csv) {
  var data = d3.nest()
    .key(function(d) { return d.Date; })
    .rollup(function(d) { return d[0].Value; })
    .map(csv);

  rect.filter(function(d) { return d in data; })
      .attr("class", function(d) { return "day " + color(data[d]); })
    .select("title")
      .text(function(d) { return d + ": " + percent(data[d]); });

  //  Tooltip
  rect.on("mouseover", mouseover);
  rect.on("mouseout", mouseout);
  function mouseover(d) {
    tooltip.style("visibility", "visible");
    var percent_data = (data[d] !== undefined) ? percent(data[d]) : percent(0);
    var purchase_text = d + ": " + percent_data;

    tooltip.transition()
                .duration(200)
                .style("opacity", .9);
    tooltip.html(purchase_text)
                .style("left", (d3.event.pageX)+30 + "px")
                .style("top", (d3.event.pageY) + "px");
  }
  function mouseout (d) {
    tooltip.transition()
            .duration(500)
            .style("opacity", 0);
    var $tooltip = $("#tooltip");
    $tooltip.empty();
  }

});

function dayTitle (t0) {
  return t0.toString().split(" ")[2];
}
function monthTitle (t0) {
  return t0.toLocaleString("en-us", { month: "long" });
}
function yearTitle (t0) {
  return t0.toString().split(" ")[3];
}
</code>```

答:
You should define variable csv this way:

```<code>var csv = d3.csv.parse(dataAsString, function(item) {
    return item;
});
</code>```

All code that was in callback function for d3.csv put after this variable definition.

```<code>var data = d3.nest()
  .key(function(d) {
    return d.Date;
  })
  .rollup(function(d) {
    return (d[0].Close - d[0].Open) / d[0].Open;
  })
  .map(csv);

rect.filter(function(d) {
    return d in data;
  })
  .attr("class", function(d) {
    return "day " + color(data[d]);
  })
  .select("title")
  .text(function(d) {
    return d + ": " + percent(data[d]);
  });
...
</code>```

Check the working example here - https://jsfiddle.net/levsha/2zp8y7r8/

Title: Replacing d3.csv to d3.csv.parse

Body:
I'm trying to use some d3 javascript template.

In my solution I have to replace d3.csv with d3.csv.parse method.

I'm having big problem to do that. I just can't understand how I have to change my code.

Here is link to template i'm using.
http://bl.ocks.org/KathyZ/c2d4694c953419e0509b

Here is my code:

        var width = 960,
    height = 750,
    cellSize = 25; // cell size

var no_months_in_a_row = Math.floor(width / (cellSize * 7 + 50));
var shift_up = cellSize * 3;

var day = d3.time.format("%w"), // day of the week
    day_of_month = d3.time.format("%e") // day of the month
    day_of_year = d3.time.format("%j")
    week = d3.time.format("%U"), // week number of the year
    month = d3.time.format("%m"), // month number
    year = d3.time.format("%Y"),
    percent = d3.format(".1%"),
    format = d3.time.format("%Y-%m-%d");

var color = d3.scale.quantize()
    .domain([-.05, .05])
    .range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));

var svg = d3.select("#chart").selectAll("svg")
    .data(d3.range(2017, 2018))
  .enter().append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("class", "RdYlGn")
  .append("g")

var rect = svg.selectAll(".day")
    .data(function(d) {
      return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1));
    })
  .enter().append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) {
      var month_padding = 1.2 * cellSize*7 * ((month(d)-1) % (no_months_in_a_row));
      return day(d) * cellSize + month_padding;
    })
    .attr("y", function(d) {
      var week_diff = week(d) - week(new Date(year(d), month(d)-1, 1) );
      var row_level = Math.ceil(month(d) / (no_months_in_a_row));
      return (week_diff*cellSize) + row_level*cellSize*8 - cellSize/2 - shift_up;
    })
    .datum(format);

var month_titles = svg.selectAll(".month-title")  // Jan, Feb, Mar and the whatnot
      .data(function(d) {
        return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
    .enter().append("text")
      .text(monthTitle)
      .attr("x", function(d, i) {
        var month_padding = 1.2 * cellSize*7* ((month(d)-1) % (no_months_in_a_row));
        return month_padding;
      })
      .attr("y", function(d, i) {
        var week_diff = week(d) - week(new Date(year(d), month(d)-1, 1) );
        var row_level = Math.ceil(month(d) / (no_months_in_a_row));
        return (week_diff*cellSize) + row_level*cellSize*8 - cellSize - shift_up;
      })
      .attr("class", "month-title")
      .attr("d", monthTitle);

var year_titles = svg.selectAll(".year-title")  // Jan, Feb, Mar and the whatnot
      .data(function(d) {
        return d3.time.years(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
    .enter().append("text")
      .text(yearTitle)
      .attr("x", function(d, i) { return width/2 - 100; })
      .attr("y", function(d, i) { return cellSize*5.5 - shift_up; })
      .attr("class", "year-title")
      .attr("d", yearTitle);

//  Tooltip Object
var tooltip = d3.select("body")
  .append("div").attr("id", "tooltip")
  .style("position", "absolute")
  .style("z-index", "10")
  .style("visibility", "hidden")
  .text("a simple tooltip");

/* This is what dji.csv have right now and its working. But I like to use string insteed. */
    var dataIliketoUse = "Date,Open\n2010-10-01,1\n2010-09-30,1";

d3.csv("dji.csv", function(error, csv) {
  var data = d3.nest()
    .key(function(d) { return d.Date; })
    .rollup(function(d) { return d[0].Value; })
    .map(csv);

  rect.filter(function(d) { return d in data; })
      .attr("class", function(d) { return "day " + color(data[d]); })
    .select("title")
      .text(function(d) { return d + ": " + percent(data[d]); });

  //  Tooltip
  rect.on("mouseover", mouseover);
  rect.on("mouseout", mouseout);
  function mouseover(d) {
    tooltip.style("visibility", "visible");
    var percent_data = (data[d] !== undefined) ? percent(data[d]) : percent(0);
    var purchase_text = d + ": " + percent_data;

    tooltip.transition()
                .duration(200)
                .style("opacity", .9);
    tooltip.html(purchase_text)
                .style("left", (d3.event.pageX)+30 + "px")
                .style("top", (d3.event.pageY) + "px");
  }
  function mouseout (d) {
    tooltip.transition()
            .duration(500)
            .style("opacity", 0);
    var $tooltip = $("#tooltip");
    $tooltip.empty();
  }

});

function dayTitle (t0) {
  return t0.toString().split(" ")[2];
}
function monthTitle (t0) {
  return t0.toLocaleString("en-us", { month: "long" });
}
function yearTitle (t0) {
  return t0.toString().split(" ")[3];
}

Body:
You should define variable csv this way:

var csv = d3.csv.parse(dataAsString, function(item) {
    return item;
});

All code that was in callback function for d3.csv put after this variable definition.

var data = d3.nest()
  .key(function(d) {
    return d.Date;
  })
  .rollup(function(d) {
    return (d[0].Close - d[0].Open) / d[0].Open;
  })
  .map(csv);

rect.filter(function(d) {
    return d in data;
  })
  .attr("class", function(d) {
    return "day " + color(data[d]);
  })
  .select("title")
  .text(function(d) {
    return d + ": " + percent(data[d]);
  });
...

Check the working example here - https://jsfiddle.net/levsha/2zp8y7r8/


问:
Why node js doesn't exit after promise call
In the following code:

```<code>function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

sleep(10000);
</code>```

Why NodeJS doesn't exit immediately? What causes the Promise to be waited for?

I thought I needed await sleep(10000) - but this gives an error.

答:
Nodejs waits for timers that are still active before exiting.  You can tell it to NOT wait for a timer by calling .unref() on the timer object itself.

So, it's not actually the promise it is waiting for, but rather the timer it is waiting for.

Internally, node.js keeps a reference count of the number of open timers that have not been .unref() and will not exit until that count (among other things) gets to zero.

Here's a couple excerpts from the node.js doc for timers:

Class: Timeout

By default, when a timer is scheduled using either setTimeout() or setInterval(), the Node.js event loop will continue running as long as the timer is active. Each of the Timeout objects returned by these functions export both timeout.ref() and timeout.unref() functions that can be used to control this default behavior.

timeout.unref()

When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked. Calling timeout.unref() multiple times will have no effect.

Body:
In the following code:

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

sleep(10000);

Why NodeJS doesn't exit immediately? What causes the Promise to be waited for?

I thought I needed await sleep(10000) - but this gives an error.


问:
Is this the fastest way to parse my XML into JavaScript objects using jQuery?
I have an XML file like this:

```<code><content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>
</code>```

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

```<code>var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};
</code>```

Thanks in advance.

答:
I have an XML source I am forced to use.. I convert it to JSON on the client side and then load it.. much easier..

```<code>Tracker.loadCasesFromServer = function () {
$.ajax({
    type: 'GET',
    url: '/WAITING.CASES.XML',
    dataType: 'xml',
    success: function (data) {
            Tracker.cases = jQuery.parseJSON(xml2json(data, ""));
            Tracker.loadCasesToMap();
        },
        data: {},
        async: true
    });
</code>```

};

Used the XML2JSON converter that can be found here: http://www.thomasfrank.se/xml_to_json.html

Duncan

ContentLicense: CC BY-SA 2.5

Body:
I have an XML file like this:

<content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};

Thanks in advance.

Body:
I have an XML source I am forced to use.. I convert it to JSON on the client side and then load it.. much easier..

Tracker.loadCasesFromServer = function () {
$.ajax({
    type: 'GET',
    url: '/WAITING.CASES.XML',
    dataType: 'xml',
    success: function (data) {
            Tracker.cases = jQuery.parseJSON(xml2json(data, ""));
            Tracker.loadCasesToMap();
        },
        data: {},
        async: true
    });

};

Used the XML2JSON converter that can be found here: http://www.thomasfrank.se/xml_to_json.html

Duncan


问:
Truncate output of measurement to match significant digits of its error
I want to automatically create a latex-table with measurements. The measurements are given in a text file in the following format:

```<code>#measurements #error
1.23456       0.00034
2.34567       0.34
</code>```

and so on.

My problem is now that i want to have the data printed out in the following format:

```<code>#measurement(error)
1.23456(34)
2.34(34)
</code>```

where the number of digits in brackets denotes the number of digits of the measurement subject to the uncertainty given in the brackets.

I get to the point of

```<code>#measurement(error)
1.23456(34)
2.34567(34000)
</code>```

which is not very beautiful

by using

```<code>awk '{printf("%f(%d)\n", $1, $2*100000)}' datafile
</code>```

Is there a way to truncate the output of the measurement according to the individual magnitude of the error.
I am not bound to awk, solutions employing other methods are very welcome too!

Body:
I want to automatically create a latex-table with measurements. The measurements are given in a text file in the following format:

#measurements #error
1.23456       0.00034
2.34567       0.34

and so on.

My problem is now that i want to have the data printed out in the following format:

#measurement(error)
1.23456(34)
2.34(34)

where the number of digits in brackets denotes the number of digits of the measurement subject to the uncertainty given in the brackets.

I get to the point of

#measurement(error)
1.23456(34)
2.34567(34000)

which is not very beautiful

by using

awk '{printf("%f(%d)\n", $1, $2*100000)}' datafile

Is there a way to truncate the output of the measurement according to the individual magnitude of the error.
I am not bound to awk, solutions employing other methods are very welcome too!

Body:
awk to the rescue!

1$ awk 'NR==1;
        NR>1 {n=match($2,/[1-9]/);
              print substr($1,1,n+1) "(" substr($2,n) ")" }' file

#measurements #error
1.23456(34)
2.34(34)


问:
How could I disable caching, for specific php files?
I am currently working on a WordPress powered ecommerce website, where the chosen shopping platform is WooCommerce.

Is there a way, without using a Plugin, which will allow me to prevent browsers from Caching certain php files?  In this instance, the 'header.php' and 'cart.php' files?  My assumption would be, that some tinkering to the '.htacess' file would be required but then I could be wrong.

答:
I found out the issue.  I completely overlooked/forgot, I had the below Caching Code in the .htaccess file.  School Boy error!

Once I removed the below code, the Basket Caching Problem was resolved.

```<code>## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
</code>```

Should I discover a way to cache a website, without the Basket being Cached, I will add it to this answer.

Body:
I found out the issue.  I completely overlooked/forgot, I had the below Caching Code in the .htaccess file.  School Boy error!

Once I removed the below code, the Basket Caching Problem was resolved.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

Should I discover a way to cache a website, without the Basket being Cached, I will add it to this answer.


问:
Gathering credit card information, security?
We have created a portal for users to pay online via our website.

We have created an option for user to check a "checkbox" to save their details to their account so they can pay easily next time.

What is the best way to save credit card details to a mySQL database? I want it to be secure, I don't want to purely save their details to a field as "XXXXXXXXXXXXXXXX".

What is the most secure way to save credit card details? We will have SSL on our server when the site goes live.

Regards

答:
You should never store CC details, except the grossly masked 'XXXX XXXX XXXX 1234' type format, and you are not EVER permitted to store the CVV numbers.

What you can store is the transaction ID turned from your payment processor, from which you can look up their stored copy of the CC number. That relieves you of the problem of securing your system enough that you could store a CC number (which is a huge undertaking) and puts the onus of the security overhead on the processor's head.

SSL is irrelevant for securing your database, an SSL connection exists only while an HTTP transaction is open, and then is gone. You need to have 100% security on your server AND your database at all times.

I'd suggest getting a copy of the PCI standards, which go into extreme detail as to what the requirements are for various levels of credit card handling/processing.


问:
jQuery - Append() is not working to add a button on Clicking an element
jsfiddle: https://jsfiddle.net/gkmuhfqt/1/

As you can see on jsfiddle, I made a Readmore text that can be clicked and it's for some functions.

Using jQuery, I tried to add a button through clicking the Readmore text that uses the append() function.

But it did not work.

Why does my Readmore text click not work at all in append()- to add some button?

I want to add hello button through clicking readmore text.

Where is my problem? How can I fix it?

-Edit-

html :

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-xs-12 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-4 col-lg-offset-4"  style="border:0.5px; border-style: solid;">
              <div class="media">
                <div class="media-left media-top" style="">
                  <img src="https://6dbaudio.files.wordpress.com/2013/08/imgp0746.jpg" class="media-object pull-left img-circle" style="width:70px; height:70px;">
                </div>
                <div class="media-body" style="">
                  <p><h4 class="media-heading">hello</h4></p>
                  <p class="readmore_as_p">Lorem ipsum dolor sit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consectetur.
                  </p>
                 </div>
                </div>
        </div>
</code>```

javascript:

```<code>$(".readmore_as_p").each(function () {

    var original_str = $(this).text();
    console.log("hi");
    if (original_str.length>20) {
        var subtracted_str = original_str.substr(0, 20);
        var p_plus_readmore_str = '<p class="readmore_before" data="' + original_str + '">' + subtracted_str + '...</p>';
        var link_read_more = '<a class="read_more"><p>Read more</p></a>';
        $(this).parent().children('p.readmore_as_p').html(p_plus_readmore_str+link_read_more);

        $('.read_more').click(function () {
            var originaltext = $(this).parent().children('p.readmore_before').attr('data');
            $(this).parent().html(originaltext);

            //Here is problem starting. What i ask is here.
            var text = '<div class="media" style="">\n' +
    '                    <div class="media-body text-center" style="">\n' +
    '                        <button class="btn btn-warning" style="">hello</button>' +
    '                    </div>\n' +
    '                </div>\n';
            $(this).parent().parent().append(text);
                             //To here
        });
    }
    else {
    }
});
</code>```

答:
The issue is that

```<code>$(this).parent().html(originaltext);
</code>```

removes the element that "this" refers to  so $(this).parent().parent() doesn't have a context to get parent from.

You can fix this by moving that line to under the add button line, ie:

```<code>$(this).parent().parent().append(text);
$(this).parent().html(originaltext);
</code>```

Updated fiddle: https://jsfiddle.net/gkmuhfqt/2/

As an extra: $('.read_more').click(function () { should be $('.read_more', this)... or move that outside the $(".readmore_as_p").each

Body:
jsfiddle: https://jsfiddle.net/gkmuhfqt/1/

As you can see on jsfiddle, I made a Readmore text that can be clicked and it's for some functions.

Using jQuery, I tried to add a button through clicking the Readmore text that uses the append() function.

But it did not work.

Why does my Readmore text click not work at all in append()- to add some button?

I want to add hello button through clicking readmore text.

Where is my problem? How can I fix it?

-Edit-

html :

hello

Lorem ipsum dolor sit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consectetur.

javascript:

$(".readmore_as_p").each(function () {

    var original_str = $(this).text();
    console.log("hi");
    if (original_str.length>20) {
        var subtracted_str = original_str.substr(0, 20);
        var p_plus_readmore_str = '
' + subtracted_str + '...
';
        var link_read_more = '
Read more
';
        $(this).parent().children('p.readmore_as_p').html(p_plus_readmore_str+link_read_more);

        $('.read_more').click(function () {
            var originaltext = $(this).parent().children('p.readmore_before').attr('data');
            $(this).parent().html(originaltext);

            //Here is problem starting. What i ask is here.
            var text = '
\n' +
    '
\n' +
    '                        <button class="btn btn-warning" style="">hello</button>' +
    '
\n' +
    '
\n';
            $(this).parent().parent().append(text);
                             //To here
        });
    }
    else {
    }
});

Body:
The issue is that

$(this).parent().html(originaltext);

removes the element that "this" refers to  so $(this).parent().parent() doesn't have a context to get parent from.

You can fix this by moving that line to under the add button line, ie:

$(this).parent().parent().append(text);
$(this).parent().html(originaltext);

Updated fiddle: https://jsfiddle.net/gkmuhfqt/2/

As an extra: $('.read_more').click(function () { should be $('.read_more', this)... or move that outside the $(".readmore_as_p").each


问:
Getting ListView Row Index Values
I am trying to write a piece of code that search a listView for the occurrence of a particular string.

Once the string is found, the code should store the index value of the row where the string was found in the listView.

After compiling the program, an ArgumentOutOfRangeException error occurred on this line:-

store[index] = listView1.SelectedIndices[0];

Could someone please advise me how to resolve this problem...

Thanks in advance

Error Messages:-

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in
System.Windows.Forms.dll

Additional information: InvalidArgument=Value of '0' is not valid for 'index'.

System.ArgumentOutOfRangeException

{"InvalidArgument=Value of '0' is not valid for 'index'.\r\nParameter name: index"}

code:-

```<code>  private void button3_Click(object sender, EventArgs e){
        int[] store = new int[20];
        string s = "    Search Via Forename";
        int result = 0;
        int count = 0;
        int index = 0;

        result = string.Compare(textBox1.Text, s);

        if ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
            MessageBox.Show("Please input forename...");
            return;
        }

        foreach (ListViewItem item in listView1.Items){
            foreach (ListViewItem.ListViewSubItem subItem in item.SubItems){
                if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
                    count++;
                    statusBar1.Panels[2].Text = "Found: " + count.ToString();
                    store[index] = listView1.SelectedIndices[0];
                    index++;
                }
            }
        }

        for (index = 0; index < count; index++){
            MessageBox.Show(store[index].ToString());
            // MessageBox.Show(listView1.Items[store[index]].SubItems[0].ToString());
        }

        button1.Text = "Clear";
        textBox1.Visible = false;
        button3.Visible = false;
        button2.Visible = false;

    }
</code>```

答: For a list use reference instead of index. List are useful because you don't need index to work with them, but you need to keep the reference somewhere or find the object by its value.</p>

Title: Getting ListView Row Index Values

Body:
I am trying to write a piece of code that search a listView for the occurrence of a particular string.

Once the string is found, the code should store the index value of the row where the string was found in the listView.

After compiling the program, an ArgumentOutOfRangeException error occurred on this line:-

store[index] = listView1.SelectedIndices[0];

Could someone please advise me how to resolve this problem...

Thanks in advance

Error Messages:-

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in
System.Windows.Forms.dll

Additional information: InvalidArgument=Value of '0' is not valid for 'index'.

System.ArgumentOutOfRangeException

{"InvalidArgument=Value of '0' is not valid for 'index'.\r\nParameter name: index"}

code:-

  private void button3_Click(object sender, EventArgs e){
        int[] store = new int[20];
        string s = "    Search Via Forename";
        int result = 0;
        int count = 0;
        int index = 0;

        result = string.Compare(textBox1.Text, s);

        if ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
            MessageBox.Show("Please input forename...");
            return;
        }

        foreach (ListViewItem item in listView1.Items){
            foreach (ListViewItem.ListViewSubItem subItem in item.SubItems){
                if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
                    count++;
                    statusBar1.Panels[2].Text = "Found: " + count.ToString();
                    store[index] = listView1.SelectedIndices[0];
                    index++;
                }
            }
        }

        for (index = 0; index < count; index++){
            MessageBox.Show(store[index].ToString());
            // MessageBox.Show(listView1.Items[store[index]].SubItems[0].ToString());
        }

        button1.Text = "Clear";
        textBox1.Visible = false;
        button3.Visible = false;
        button2.Visible = false;

    }


问:
How to parse slice inside json in golang?
I am trying to unmarshal json data. The slice inside is deliberately without quotes, because this is what I am getting from https (added manually \ before ")

```<code>data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"
</code>```

into Message struct:

```<code>type Message struct {
    QueryEndTime string `json:"queryEndTime"`
    Message []string `json:"message"`

}
</code>```

but I am getting correct QueryEndTime and empty Message. I tried to change Message type but it always stays empty

```<code>var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s\nMessage: %s\n", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []
</code>```

See it in go playground https://play.golang.org/p/on0_cSKb0c.

答:
```<code>package main

import (
    "encoding/json"
    "fmt"
)

type Message struct {
    QueryEndTime string `json:"queryEndTime"`

    // you need to use a struct can use anon struct
    Message      []struct {
        SpamScore  int `json:"spamScore"`
        PhishScore int `json:"phishScore"`
    } `json:"message"`

}

func main() {
    var message Message

    // You can use backticks to for your example JSON, so that you don't have to escape anything.
    data := `{
        "queryEndTime" : "2017-11-15T14:39:00Z",
        "message" : [
            {"spamScore":67, "phishScore":0}
        ]
    }`

    // please check for errors
    err := json.Unmarshal([]byte(data), &message)
    if err != nil {
        fmt.Println(err)
    }

    // +v prints structs very nicely
    fmt.Printf("%+v\n", message)
}
</code>```

https://play.golang.org/p/Mu3WZCej3L

Have fun!

Body:
I am trying to unmarshal json data. The slice inside is deliberately without quotes, because this is what I am getting from https (added manually \ before ")

data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"

into Message struct:

type Message struct {
    QueryEndTime string `json:"queryEndTime"`
    Message []string `json:"message"`

}

but I am getting correct QueryEndTime and empty Message. I tried to change Message type but it always stays empty

var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s\nMessage: %s\n", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []

See it in go playground https://play.golang.org/p/on0_cSKb0c.

Body:
package main

import (
    "encoding/json"
    "fmt"
)

type Message struct {
    QueryEndTime string `json:"queryEndTime"`

    // you need to use a struct can use anon struct
    Message      []struct {
        SpamScore  int `json:"spamScore"`
        PhishScore int `json:"phishScore"`
    } `json:"message"`

}

func main() {
    var message Message

    // You can use backticks to for your example JSON, so that you don't have to escape anything.
    data := `{
        "queryEndTime" : "2017-11-15T14:39:00Z",
        "message" : [
            {"spamScore":67, "phishScore":0}
        ]
    }`

    // please check for errors
    err := json.Unmarshal([]byte(data), &message)
    if err != nil {
        fmt.Println(err)
    }

    // +v prints structs very nicely
    fmt.Printf("%+v\n", message)
}

https://play.golang.org/p/Mu3WZCej3L

Have fun!


问:
Quit Application when press logout button
When I press back button in my android application or close the app, it terminates and I want my app to be terminated when I press the logout button.
I only want my app to be terminated when I press the logout button, otherwise not, whether I press back button or close it by minimizing the app.

What should I do?

For the back button, I used this simple code

```<code>@Override
public void onBackPressed()
{
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    moveTaskToBack(true);

    if (drawer.isDrawerOpen(GravityCompat.START))
    {
        drawer.closeIrawer(GravityCompat.START);
    }
    else
    {
        super.onBackPressed();
    }
}
</code>```

Should I do something with these lines?

Or should make any web services for this?

答:
Try using this:

```<code>         @Override public void onBackPressed() {
new AlertDialog.Builder(this)
 .setMessage("Are you sure you want to exit?")
     .setPositiveButton("Yes", new DialogInterface.OnClickListener()
     {
    @Override public void onClick(DialogInterface dialog, int which) {
    MyActivity.super.onBackPressed(); } })
     .setNegativeButton("No", null)
    .show(); }
</code>```

If you do not want the back button to exit the app at all :

```<code>@Override public void onBackPressed() {
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I press back button in my android application or close the app, it terminates and I want my app to be terminated when I press the logout button.
I only want my app to be terminated when I press the logout button, otherwise not, whether I press back button or close it by minimizing the app.

What should I do?

For the back button, I used this simple code

@Override
public void onBackPressed()
{
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    moveTaskToBack(true);

    if (drawer.isDrawerOpen(GravityCompat.START))
    {
        drawer.closeIrawer(GravityCompat.START);
    }
    else
    {
        super.onBackPressed();
    }
}

Should I do something with these lines?

Or should make any web services for this?

Body:
Try using this:

         @Override public void onBackPressed() {
new AlertDialog.Builder(this)
 .setMessage("Are you sure you want to exit?")
     .setPositiveButton("Yes", new DialogInterface.OnClickListener()
     {
    @Override public void onClick(DialogInterface dialog, int which) {
    MyActivity.super.onBackPressed(); } })
     .setNegativeButton("No", null)
    .show(); }

If you do not want the back button to exit the app at all :

@Override public void onBackPressed() {
 }


问:
R: divide variable in dataframe by specific value from list or vector
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

```<code>Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3
</code>```

答:
A dplyr/tidyverse approach:

code to replicate your dataframes

```<code>df1 <-
    read.table(text = "Location Response
                        Loc1     25
                        Loc2     63
                        Loc3     5.63
                      ", header = TRUE, stringsAsFactors = FALSE)
df2 <-
    read.table(text = "Location  Sampling_effort
                        Loc1     2
                        Loc2     6.5
                        Loc3     3
                      ", header = TRUE, stringsAsFactors = FALSE)
</code>```

code to generate the effect size calculation

```<code>library(dplyr)
df_joined <-
    df1 %>%
    left_join(df2) %>%
    mutate(Effect_size = Response / Sampling_effort)
</code>```

which results in:

```<code>> df_joined
  Location Response Sampling_effort Effect_size
1     Loc1    25.00             2.0   12.500000
2     Loc2    63.00             6.5    9.692308
3     Loc3     5.63             3.0    1.876667
</code>```

There are lots of good introductions to manipulating data in R, but we did find the datacamp one to be useful - though it is not free anymore.

Body:
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3

Body:
A dplyr/tidyverse approach:

code to replicate your dataframes

df1 <-
    read.table(text = "Location Response
                        Loc1     25
                        Loc2     63
                        Loc3     5.63
                      ", header = TRUE, stringsAsFactors = FALSE)
df2 <-
    read.table(text = "Location  Sampling_effort
                        Loc1     2
                        Loc2     6.5
                        Loc3     3
                      ", header = TRUE, stringsAsFactors = FALSE)

code to generate the effect size calculation

library(dplyr)
df_joined <-
    df1 %>%
    left_join(df2) %>%
    mutate(Effect_size = Response / Sampling_effort)

which results in:

> df_joined
  Location Response Sampling_effort Effect_size
1     Loc1    25.00             2.0   12.500000
2     Loc2    63.00             6.5    9.692308
3     Loc3     5.63             3.0    1.876667

There are lots of good introductions to manipulating data in R, but we did find the datacamp one to be useful - though it is not free anymore.


答:
You can do this:

```<code>var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum)               //=> {bob: 6, john: 16}
)
</code>```

Or you could use a reduce, but I think this is simpler.

Update: I misread the output format.  This fixes it:

```<code>var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum),              //=> {bob: 6, john: 16}
  toPairs,               //=> [["bob", 6], ["john", 16]]
  map(zipObj(['name', 'points'])) //=> [{name: "bob", points: 6},
                         //             {name: "john", points: 16}]
)
</code>```

Title: Nodejs - Return array of key-value pair by adding values with same key

Body:
I have the following array of objects:

const list = [
  {points: 3, name:'bob'},
  {points: 1, name:'john'},
  {points: 5, name:'john'},
  {points: 2, name:'john'},
  {points: 8, name:'john'},
  {points: 0, name:'bob'},
  {points: 2, name:'bob'},
  {points: 1, name:'bob'},
]

And I want to end up with and object that returns a list of data-sets that contains the sum of points for each name like:

const list2 = [
  {name: 'bob', points: 6}, // sum of all of bob's points
  {name: 'john', points: 16}
]

I need this so that I can use the resulting data set to generate a line chart.

Is there a way to do this, preferably using ramda.js?

Body:
You can do this:

var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum)               //=> {bob: 6, john: 16}
)

Or you could use a reduce, but I think this is simpler.

Update: I misread the output format.  This fixes it:

var combine = pipe(
  groupBy(prop('name')), //=> {bob: [bob_obj_1, bob_obj_2, ...], john: [ ... ]}
  map(pluck('points')),  //=> {bob: [3, 0, 2, 1], john: [1, 5, 2, 8]}
  map(sum),              //=> {bob: 6, john: 16}
  toPairs,               //=> [["bob", 6], ["john", 16]]
  map(zipObj(['name', 'points'])) //=> [{name: "bob", points: 6},
                         //             {name: "john", points: 16}]
)


问:
Create multi element json
I have a data frame as follows:

```<code>item <- c(rep.int("Item ID 1", 4), rep.int("Item ID 2", 3))
links <- c("A", "B", "C", "D", "A", "E", "F")

df <- as.data.frame(cbind(item, links))
</code>```

I am looking to convert this to a json with multiple values for each links key (is that the correct term?)

Expected JSON

```<code>{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
}
</code>```

This is needed for a d3.js visualization but I haven't been able to convert it so far.

答:
Manipulate data as list:

```<code>library(tidyverse)
library(jsonlite)

js <- split(df$links, df$item) %>%                      # use split to group links by item
    imap(~ list(type = "item", name = .y, links = .x)) %>%   # add extra fields to each item
    {list(items = unname(.))} %>%                       # add the top level items key
    toJSON(auto_unbox = TRUE)       # convert to json unbox single element vector to scalar

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}
</code>```

Manipulate data as data.frame:

```<code>js <- df %>%
    group_by(item) %>% nest() %>%
    mutate(type = "item", data = map(data, "links")) %>%
    select(type, name = item, links = data) %>%
    list(items = .) %>%
    toJSON(dataframe = "rows")

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}
</code>```

Title: Create multi element json

Body:
I have a data frame as follows:

item <- c(rep.int("Item ID 1", 4), rep.int("Item ID 2", 3))
links <- c("A", "B", "C", "D", "A", "E", "F")

df <- as.data.frame(cbind(item, links))

I am looking to convert this to a json with multiple values for each links key (is that the correct term?)

Expected JSON

{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
}

This is needed for a d3.js visualization but I haven't been able to convert it so far.

Body:
Manipulate data as list:

library(tidyverse)
library(jsonlite)

js <- split(df$links, df$item) %>%                      # use split to group links by item
    imap(~ list(type = "item", name = .y, links = .x)) %>%   # add extra fields to each item
    {list(items = unname(.))} %>%                       # add the top level items key
    toJSON(auto_unbox = TRUE)       # convert to json unbox single element vector to scalar

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}

Manipulate data as data.frame:

js <- df %>%
    group_by(item) %>% nest() %>%
    mutate(type = "item", data = map(data, "links")) %>%
    select(type, name = item, links = data) %>%
    list(items = .) %>%
    toJSON(dataframe = "rows")

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}


问:
Supervised GenServer not being restarted?
I've reduced the size of the question, cause it was too big. Here's the code:

```<code>defmodule MayRaiseGenServer do
  use GenServer

  def start_link do
    IO.puts "started MyServer, name is #{__MODULE__}"

    GenServer.start_link(__MODULE__, [], name: __MODULE__)
  end

  def maybe_will_raise do
    GenServer.call(__MODULE__, :maybe_will_raise)
  end

  def handle_call(:maybe_will_raise,_from, state) do
    IO.puts "maybe_will_raise called!"
    :random.seed(:erlang.now)
    number = Enum.to_list(1..100) |> Enum.shuffle |> List.first
    IO.puts "number is #{number}"
    if rem(number,2) != 0 do
      raise "#{number}"
    end
    {:reply, {"You got lucky"}, state}
  end
end

defmodule MayRaiseSupervisor do
  use Supervisor

  def start_link([]) do
    IO.puts "starting supervisor, name is #{__MODULE__}"
    Supervisor.start_link(__MODULE__, [])
  end

  def init(arg) do
    IO.puts "initted with arg: #{arg}"
    children = [
      worker(MayRaiseGenServer, [])
    ]

    supervise(children, strategy: :one_for_one, restart: :transient, name: __MODULE__)
  end
end

MayRaiseSupervisor.start_link([])
IO.inspect MayRaiseGenServer.maybe_will_raise
:timer.sleep(2000)
IO.puts "after sleep"
</code>```

Initially, I only saw the message for starting the GenServer once, but now I see it again. Here's the output:

```<code>starting supervisor, name is Elixir.MayRaiseSupervisor
initted with arg:
started MyServer, name is Elixir.MayRaiseGenServer
maybe_will_raise called!
number is 14
started MyServer, name is Elixir.MayRaiseGenServer

11:32:28.807 [error] GenServer MayRaiseGenServer terminating
** (RuntimeError) 14
    lib/mini.ex:20: MayRaiseGenServer.handle_call/3
    (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
    (stdlib) gen_server.erl:647: :gen_server.handle_msg/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: :maybe_will_raise
State: []
** (exit) exited in: GenServer.call(MayRaiseGenServer, :maybe_will_raise, 5000)
    ** (EXIT) an exception was raised:
        ** (RuntimeError) 14
            lib/mini.ex:20: MayRaiseGenServer.handle_call/3
            (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
            (stdlib) gen_server.erl:647: :gen_server.handle_msg/5
            (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
    (elixir) lib/gen_server.ex:604: GenServer.call/3
    lib/mini.ex:45: (file)
    (elixir) lib/code.ex:363: Code.require_file/2
</code>```

From the above output, it's not very clear to me what happens. It looks like the GenServer is restarted, based on the message shown on IO, but why is the exception being thrown again? Also, in this code:

```<code>MayRaiseSupervisor.start_link([])
IO.inspect MayRaiseGenServer.maybe_will_raise
:timer.sleep(2000)
IO.puts "after sleep"
</code>```

If the method call MayRaiseGenServer.maybe_will_raise will indeed raise an error, it looks like the lines after, the one with timer.sleep and the IO.puts won't be run anymore. Even if I change the code to try and handle the exception, like this:

```<code>MayRaiseSupervisor.start_link([])
try do
  IO.inspect MayRaiseGenServer.maybe_will_raise
rescue
  RuntimeError -> IO.puts "there was an error"
end
:timer.sleep(2000)
IO.puts "after sleep"
</code>```

I still cannot seem to reach the last IO.puts ( if there was an error ). Is there a way of handling the call to maybe_will_raise that would allow me to handle it raising an error, and continuing execution? I'm guessing supervisors won't automatically retry a piece of code when they're being restarted.

答:
By mistake, I have used GenServer.start instead of GenServer.start_link and searched for answer for two days.

Note 1: Supervisor tree in :observer.start helped a lot to debug this problem

Note 2: But above problem using start_link only. I am writing for people who are doing the same mistake like me :-P.

Body:
I've reduced the size of the question, cause it was too big. Here's the code:

defmodule MayRaiseGenServer do
  use GenServer

  def start_link do
    IO.puts "started MyServer, name is #{__MODULE__}"

    GenServer.start_link(__MODULE__, [], name: __MODULE__)
  end

  def maybe_will_raise do
    GenServer.call(__MODULE__, :maybe_will_raise)
  end

  def handle_call(:maybe_will_raise,_from, state) do
    IO.puts "maybe_will_raise called!"
    :random.seed(:erlang.now)
    number = Enum.to_list(1..100) |> Enum.shuffle |> List.first
    IO.puts "number is #{number}"
    if rem(number,2) != 0 do
      raise "#{number}"
    end
    {:reply, {"You got lucky"}, state}
  end
end

defmodule MayRaiseSupervisor do
  use Supervisor

  def start_link([]) do
    IO.puts "starting supervisor, name is #{__MODULE__}"
    Supervisor.start_link(__MODULE__, [])
  end

  def init(arg) do
    IO.puts "initted with arg: #{arg}"
    children = [
      worker(MayRaiseGenServer, [])
    ]

    supervise(children, strategy: :one_for_one, restart: :transient, name: __MODULE__)
  end
end

MayRaiseSupervisor.start_link([])
IO.inspect MayRaiseGenServer.maybe_will_raise
:timer.sleep(2000)
IO.puts "after sleep"

Initially, I only saw the message for starting the GenServer once, but now I see it again. Here's the output:

starting supervisor, name is Elixir.MayRaiseSupervisor
initted with arg:
started MyServer, name is Elixir.MayRaiseGenServer
maybe_will_raise called!
number is 14
started MyServer, name is Elixir.MayRaiseGenServer

11:32:28.807 [error] GenServer MayRaiseGenServer terminating
** (RuntimeError) 14
    lib/mini.ex:20: MayRaiseGenServer.handle_call/3
    (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
    (stdlib) gen_server.erl:647: :gen_server.handle_msg/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: :maybe_will_raise
State: []
** (exit) exited in: GenServer.call(MayRaiseGenServer, :maybe_will_raise, 5000)
    ** (EXIT) an exception was raised:
        ** (RuntimeError) 14
            lib/mini.ex:20: MayRaiseGenServer.handle_call/3
            (stdlib) gen_server.erl:615: :gen_server.try_handle_call/4
            (stdlib) gen_server.erl:647: :gen_server.handle_msg/5
            (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
    (elixir) lib/gen_server.ex:604: GenServer.call/3
    lib/mini.ex:45: (file)
    (elixir) lib/code.ex:363: Code.require_file/2

From the above output, it's not very clear to me what happens. It looks like the GenServer is restarted, based on the message shown on IO, but why is the exception being thrown again? Also, in this code:

MayRaiseSupervisor.start_link([])
IO.inspect MayRaiseGenServer.maybe_will_raise
:timer.sleep(2000)
IO.puts "after sleep"

If the method call MayRaiseGenServer.maybe_will_raise will indeed raise an error, it looks like the lines after, the one with timer.sleep and the IO.puts won't be run anymore. Even if I change the code to try and handle the exception, like this:

MayRaiseSupervisor.start_link([])
try do
  IO.inspect MayRaiseGenServer.maybe_will_raise
rescue
  RuntimeError -> IO.puts "there was an error"
end
:timer.sleep(2000)
IO.puts "after sleep"

I still cannot seem to reach the last IO.puts ( if there was an error ). Is there a way of handling the call to maybe_will_raise that would allow me to handle it raising an error, and continuing execution? I'm guessing supervisors won't automatically retry a piece of code when they're being restarted.


答:
Maybe you can use your own class based on lisboxitem which can store the font, size, and index and maybe more.</p>

```<code>Like every item will know his index of course
</code>```

Title: Getting ListView Row Index Values

Body:
Maybe you can use your own class based on lisboxitem which can store the font, size, and index and maybe more.

Like every item will know his index of course


问:
.Net Security Exception when trying to render a reCaptcha control
I've downloaded the recaptcha.dll in both 1.0.1.0 and 1.0.4.0.
When trying to render the control, I get the following exception:

Security Exception
  Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Stack Trace:[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
     System.Reflection.Assembly._GetType(String name, Boolean throwOnError, Boolean ignoreCase) +0
     System.Web.UI.NamespaceTagNameToTypeMapper.GetControlType(String tagName, IDictionary attribs, Boolean throwOnError) +209

The solution to this, as provided by a quick Googling, is to use caspol.exe to add full trust to the recaptcha.dll assembly.

C:\%path%\caspol -af C:\inetpub\wwwroot\%path%\bin\recaptcha.dll

At this point, I get the following error:

ERROR: This assembly is not strong name signed

Short of downloading the source code and recompiling it locally, is there any other way to get this working?

答:
I ran into the same problem and your solution helped me.  I also had to perform the following steps on the reCAPTCHA ASP.NET source code.

1) Open the AssemblyInfo.cs file of the DLL project and add following using statement.

using System.Security;

2) Add following line to AssembleInfo.cs.

[assembly: AllowPartiallyTrustedCallers()]

3) Recomiple the dlls and redeploy your projects. This error should be solved.

NOTE: The website I am working on is using 1and1.com as their hosting company.  I also had to set the Proxy property in the code-behind to avoid a timeout exception during the HttpWebRequest.

```<code>recaptcha.Proxy = new WebProxy("http://ntproxyus.lxa.perfora.net:3128");
</code>```

Hope this helps someone but now I have reCAPTCHA up and running on an ASP.NET site hosted on  1and1.com.

Body:
I ran into the same problem and your solution helped me.  I also had to perform the following steps on the reCAPTCHA ASP.NET source code.

1) Open the AssemblyInfo.cs file of the DLL project and add following using statement.

using System.Security;

2) Add following line to AssembleInfo.cs.

[assembly: AllowPartiallyTrustedCallers()]

3) Recomiple the dlls and redeploy your projects. This error should be solved.

NOTE: The website I am working on is using 1and1.com as their hosting company.  I also had to set the Proxy property in the code-behind to avoid a timeout exception during the HttpWebRequest.

recaptcha.Proxy = new WebProxy("http://ntproxyus.lxa.perfora.net:3128");

Hope this helps someone but now I have reCAPTCHA up and running on an ASP.NET site hosted on  1and1.com.


答:
Take a look at the unref() function for timers in node - https://nodejs.org/api/timers.html#timers_timeout_unref

When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked.

You can create a timeout and call the unref() function on it - this will prevent node from staying alive if the only thing it is waiting for is the timeout.

```<code>function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms).unref();
    });
}
</code>```

As a side note, the same unref function can also be used for setTimeout calls.

As correctly noted by jfriend00, it is not the promise that is keeping node alive, it is the timeout.

Title: Why node js doesn't exit after promise call

Body:
In the following code:

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

sleep(10000);

Why NodeJS doesn't exit immediately? What causes the Promise to be waited for?

I thought I needed await sleep(10000) - but this gives an error.

Body:
Take a look at the unref() function for timers in node - https://nodejs.org/api/timers.html#timers_timeout_unref

When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked.

You can create a timeout and call the unref() function on it - this will prevent node from staying alive if the only thing it is waiting for is the timeout.

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms).unref();
    });
}

As a side note, the same unref function can also be used for setTimeout calls.

As correctly noted by jfriend00, it is not the promise that is keeping node alive, it is the timeout.


问:
Keras model taking forerver to train with dask dataframe
I m working with large dataset having low memory and I got introduced to Dask dataframe. What I understood from the docs that Dask does not load whole dataset into memory . instead it created multiple threads which will fetch the records from disk on demand basis. So I suppose keras model with having batch size = 500, it should only have 500 records in the memory at the training time. but when I start training. it takes forever.May be I am doing something wrong.please suggest.

shape of training data: 1000000 * 1290

```<code>import glob
import dask.dataframe
paths_train = glob.glob(r'x_train_d_final*.csv')

X_train_d = dd.read_csv('.../x_train_d_final0.csv')
Y_train1 = keras.utils.to_categorical(Y_train.iloc[,1], num_classes)
batch_size = 500
num_classes = 2
epochs = 5

model = Sequential()
model.add(Dense(645, activation='sigmoid', input_shape=(1290,),kernel_initializer='glorot_normal'))
#model.add(Dense(20, activation='sigmoid',kernel_initializer='glorot_normal'))
model.add(Dense(num_classes, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
          optimizer=Adam(decay=0),
          metrics=['accuracy'])

history = model.fit(X_train_d.to_records(), Y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                class_weight = {0:1,1:6.5},
                shuffle=False)
</code>```

答:
Today Keras does not know about Dask dataframes or arrays.  I suspect that it is just converting the dask object into the equivalent Pandas or Numpy object instead.

If your Keras model can be trained incrementally then you could solve this problem using dask.delayed and some for loops.

Eventually it would be nice to see the Keras and Dask projects learn more about each other to facilitate these workloads without excess work.

Body:
I m working with large dataset having low memory and I got introduced to Dask dataframe. What I understood from the docs that Dask does not load whole dataset into memory . instead it created multiple threads which will fetch the records from disk on demand basis. So I suppose keras model with having batch size = 500, it should only have 500 records in the memory at the training time. but when I start training. it takes forever.May be I am doing something wrong.please suggest.

shape of training data: 1000000 * 1290

import glob
import dask.dataframe
paths_train = glob.glob(r'x_train_d_final*.csv')

X_train_d = dd.read_csv('.../x_train_d_final0.csv')
Y_train1 = keras.utils.to_categorical(Y_train.iloc[,1], num_classes)
batch_size = 500
num_classes = 2
epochs = 5

model = Sequential()
model.add(Dense(645, activation='sigmoid', input_shape=(1290,),kernel_initializer='glorot_normal'))
#model.add(Dense(20, activation='sigmoid',kernel_initializer='glorot_normal'))
model.add(Dense(num_classes, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
          optimizer=Adam(decay=0),
          metrics=['accuracy'])

history = model.fit(X_train_d.to_records(), Y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                class_weight = {0:1,1:6.5},
                shuffle=False)


问:
How create runnable .jar file in Intellij/Gradle
Can someone tell me how run .jar file with Intellij and Gradle in cmd?

I try create manifest file but get errors:

```<code>no main manifest attribute, in eureka-server.jar
</code>```

or

```<code>Error: Could not find or load main class com.project.EurekaServerApplication
Caused by: java.lang.ClassNotFoundException: com.project.EurekaServerApplication
</code>```

My main class:

```<code>package com.project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

In MANIFEST.MF in path /resources/META-INF

```<code>Manifest-Version: 1.0
Main-Class: com.project.EurekaServerApplication
</code>```

Also I try it, in build.gradle

```<code>jar {
    manifest {
        attributes(
                'Main-Class': 'com.project.EurekaServerApplication'
        )
    }
}
</code>```

I run this jar file in this way:

```<code>java -jar [nameApplication].jar
</code>```

答:
In order to run the .jar file you have to make it executable after the gradle build (regardless of intellij), use the bootRepackage task in your gradle file:</p>

```<code>bootRepackage {
  mainClass = 'com.project.EurekaServerApplication'
}
</code>```

Body:
Can someone tell me how run .jar file with Intellij and Gradle in cmd?

I try create manifest file but get errors:

no main manifest attribute, in eureka-server.jar

or

Error: Could not find or load main class com.project.EurekaServerApplication
Caused by: java.lang.ClassNotFoundException: com.project.EurekaServerApplication

My main class:

package com.project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

In MANIFEST.MF in path /resources/META-INF

Manifest-Version: 1.0
Main-Class: com.project.EurekaServerApplication

Also I try it, in build.gradle

jar {
    manifest {
        attributes(
                'Main-Class': 'com.project.EurekaServerApplication'
        )
    }
}

I run this jar file in this way:

java -jar [nameApplication].jar

Body:
In order to run the .jar file you have to make it executable after the gradle build (regardless of intellij), use the bootRepackage task in your gradle file:

bootRepackage {
  mainClass = 'com.project.EurekaServerApplication'
}


问:
Tomcat multiple web application different domain name on centOS
I have a CentOS server and on it, I have a tomcat server. I have two clients with two web applications eg. 131.163.121.215/application1 and 131.163.121.215/application2

Both of those clients need a separate domain name for their web applications
eg. www.application1.com and www.application2.com
 Is that possible and if it is, how can I achieve that?

答:
Yes, it is possible.

I suppose you are using the default Tomcat port (8080), You can edit the server.xml file on <TOMCAT_DIR>/conf/server.xml to add another service with a connector running on a different port for example 9090, you then place your other app on the second service. With this configuration you can add your application on a different folder for example webapps2

Example of server.xml

```<code>...
<Service name="Service1">
<Connector port="8080" connectionTimeout="20000" protocol="HTTP/1.1" maxThreads="250"/>
<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
</Host>
</Service>

<Service name="Service2">
<Connector port="9090" protocol="HTTP/1.1" maxThreads="300" connectionTimeout="20000" />
<Host name="localhost"  appBase="webapps2" unpackWARs="true" autoDeploy="true">
</Host>
</Service>
...
</code>```

Your tomcat directory should have 2 webapps folders with your applications:

<TOMCAT_DIR>/webapps/application1

<TOMCAT_DIR>/webapps2/application2

The domains will redirect to the same server but to different port:

www.application1.com -> 131.163.121.215:8080/application1

and

www.application2.com -> 131.163.121.215:9090/application2

Body:
Yes, it is possible.

I suppose you are using the default Tomcat port (8080), You can edit the server.xml file on <TOMCAT_DIR>/conf/server.xml to add another service with a connector running on a different port for example 9090, you then place your other app on the second service. With this configuration you can add your application on a different folder for example webapps2

Example of server.xml

...
<Service name="Service1">
<Connector port="8080" connectionTimeout="20000" protocol="HTTP/1.1" maxThreads="250"/>
<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
</Host>
</Service>

<Service name="Service2">
<Connector port="9090" protocol="HTTP/1.1" maxThreads="300" connectionTimeout="20000" />
<Host name="localhost"  appBase="webapps2" unpackWARs="true" autoDeploy="true">
</Host>
</Service>
...

Your tomcat directory should have 2 webapps folders with your applications:

<TOMCAT_DIR>/webapps/application1

<TOMCAT_DIR>/webapps2/application2

The domains will redirect to the same server but to different port:

www.application1.com -> 131.163.121.215:8080/application1

and

www.application2.com -> 131.163.121.215:9090/application2


问:
Laravel is not parsing a JSON Object in Blade as expected - Error Undefined property: stdClass
I have a JSON Object like so:

```<code>{
  "statusCode": 0,
  "statusMessage": "OK",
  "content": {
    "templateId": "5a00775807105e735085c65d",
    "authorId": "fabio.peddis@bsc.it",
    "title": "Primo Template",
    "description": "Descrizione del Primo Template",
    "status": 0,
    "saveDate": 1509979998738,
    "publishDate": null,
    "keywords": [
      "keyDue",
      "keySecondo"
    ],
    "icon": null,
    "questions": [
      {
        "questionId": 1,
        "questionText": "Domanda 01?",
        "responses": [
          {
            "keywords": [
              "Sì",
              "Yes",
              "Oui"
            ],
            "nextQuestionId": 11
          },
          {
            "keywords": [
              "No",
              "Not",
              "Non"
            ],
            "nextQuestionId": 12
          }
        ]
      },
      {
        "questionId": 11,
        "questionText": "Domanda 11?",
        "responses": [
          {
            "keywords": [
</code>```

I pass it to a view after doing this:

```<code>$objResp=json_decode($response);
</code>```

Then on the view I simply access it like so:

```<code>@foreach($template->content->questions as $question)
    ...
    {{$question->questionText}}
    ...
    @foreach($question->responses as $res )
        ....
    @endforeach

@endforeach
</code>```

"Responses" is a different structure but at the same level as "questionText" that I can easily access it.

So the problem is in the second/internal loop, it crashes without hope..., but if I do a dd() of $question->responses, I can see the correct contents of an array size2.

Laravel gives me back this error with the loop:

Undefined property: stdClass::$responses

What is causing this error?

答:
You can try setting a key for each response.

Like:

```<code>"responses": [
      "1": {
        "keywords": [
          "Sì",
          "Yes",
          "Oui"
        ],
        "nextQuestionId": 11
      },
      "2": {
        "keywords": [
          "No",
          "Not",
          "Non"
        ],
        "nextQuestionId": 12
      }
    ]
</code>```

There is multiple ways to reresent json and I think this json syntax is not supported by php.

Body:
I have a JSON Object like so:

{
  "statusCode": 0,
  "statusMessage": "OK",
  "content": {
    "templateId": "5a00775807105e735085c65d",
    "authorId": "fabio.peddis@bsc.it",
    "title": "Primo Template",
    "description": "Descrizione del Primo Template",
    "status": 0,
    "saveDate": 1509979998738,
    "publishDate": null,
    "keywords": [
      "keyDue",
      "keySecondo"
    ],
    "icon": null,
    "questions": [
      {
        "questionId": 1,
        "questionText": "Domanda 01?",
        "responses": [
          {
            "keywords": [
              "Sì",
              "Yes",
              "Oui"
            ],
            "nextQuestionId": 11
          },
          {
            "keywords": [
              "No",
              "Not",
              "Non"
            ],
            "nextQuestionId": 12
          }
        ]
      },
      {
        "questionId": 11,
        "questionText": "Domanda 11?",
        "responses": [
          {
            "keywords": [

I pass it to a view after doing this:

$objResp=json_decode($response);

Then on the view I simply access it like so:

@foreach($template->content->questions as $question)
    ...
    {{$question->questionText}}
    ...
    @foreach($question->responses as $res )
        ....
    @endforeach

@endforeach

"Responses" is a different structure but at the same level as "questionText" that I can easily access it.

So the problem is in the second/internal loop, it crashes without hope..., but if I do a dd() of $question->responses, I can see the correct contents of an array size2.

Laravel gives me back this error with the loop:

Undefined property: stdClass::$responses

What is causing this error?

Body:
You can try setting a key for each response.

Like:

"responses": [
      "1": {
        "keywords": [
          "Sì",
          "Yes",
          "Oui"
        ],
        "nextQuestionId": 11
      },
      "2": {
        "keywords": [
          "No",
          "Not",
          "Non"
        ],
        "nextQuestionId": 12
      }
    ]

There is multiple ways to reresent json and I think this json syntax is not supported by php.


问:
How can I represent a "many to many" relation with Android Room when column names are same?
How can I represent a "many to many" relation with Room? My column names are also the same.

e.g. I have Guest and Reservation. Reservation can have many Guest's and a Guest can be part of many Reservations.

Here are my entity definitions:

```<code>@Entity data class Reservation(
    @PrimaryKey val id: Long,
    val table: String,
    val guests: List<Guest>
)

@Entity data class Guest(
    @PrimaryKey val id: Long,
    val name: String,
    val email: String
)
</code>```

While looking into docs I came across @Relation. I found it really confusing though.

According to this I would want to create a POJO and add the relationships there. So, with my example I did the following:

```<code>data class ReservationForGuest(
    @Embedded val reservation: Reservation,
    @Relation(
        parentColumn = "reservation.id",
        entityColumn = "id",
        entity = Guest::class
    ) val guestList: List<Guest>
)
</code>```

With above I get the compiler error:

```<code>> Cannot figure out how to read this field from a cursor.
</code>```

I wasn't able to find a working sample of @Relation.

答:
Based on the answer above: https://stackoverflow.com/a/44428451/4992598 only by keeping separate field names between entities
you can have models returned (not just ids). All you need to do is:

```<code>@Entity data class ReservationGuest(
    @PrimaryKey(autoGenerate = true) val id: Long,
    val reservationId: Long,
    @Embedded
    val guest: Guest
)
</code>```

And yes entities can be embedded in one another as long as you don't keep duplicate fields. So in consequence the ReservationWithGuests class can look like this.

```<code>data class ReservationWithGuests(
    @Embedded val reservation:Reservation,
    @Relation(
        parentColumn = "id",
        entityColumn = "reservationId",
        entity = ReservationGuest::class,
        projection = "guestId"
    ) val guestList: List<Guest>
)
</code>```

So at this point you can use val guestIdList: List because your ReservationGuest entity actually maps ids with entity models.

Body:
How can I represent a "many to many" relation with Room? My column names are also the same.

e.g. I have Guest and Reservation. Reservation can have many Guest's and a Guest can be part of many Reservations.

Here are my entity definitions:

@Entity data class Reservation(
    @PrimaryKey val id: Long,
    val table: String,
    val guests: List<Guest>
)

@Entity data class Guest(
    @PrimaryKey val id: Long,
    val name: String,
    val email: String
)

While looking into docs I came across @Relation. I found it really confusing though.

According to this I would want to create a POJO and add the relationships there. So, with my example I did the following:

data class ReservationForGuest(
    @Embedded val reservation: Reservation,
    @Relation(
        parentColumn = "reservation.id",
        entityColumn = "id",
        entity = Guest::class
    ) val guestList: List<Guest>
)

With above I get the compiler error:

> Cannot figure out how to read this field from a cursor.

I wasn't able to find a working sample of @Relation.

Body:
Based on the answer above: https://stackoverflow.com/a/44428451/4992598 only by keeping separate field names between entities
you can have models returned (not just ids). All you need to do is:

@Entity data class ReservationGuest(
    @PrimaryKey(autoGenerate = true) val id: Long,
    val reservationId: Long,
    @Embedded
    val guest: Guest
)

And yes entities can be embedded in one another as long as you don't keep duplicate fields. So in consequence the ReservationWithGuests class can look like this.

data class ReservationWithGuests(
    @Embedded val reservation:Reservation,
    @Relation(
        parentColumn = "id",
        entityColumn = "reservationId",
        entity = ReservationGuest::class,
        projection = "guestId"
    ) val guestList: List<Guest>
)

So at this point you can use val guestIdList: List because your ReservationGuest entity actually maps ids with entity models.


问:
How to test if an input has only specific characters
Im trying to make a script that tests id there are characters in the input that are not A, T, C, G and if there are than the input is false.

I dont have any clue how to start. I would love if someone could help.
Thanks!

答:
The following function can check a string to find out if it only contains the characters A, T, C, and G.</p>

```<code>def check_string(code):
    return all(character in {'A', 'T', 'C', 'G'} for character in code)
</code>```

Body:
The following function can check a string to find out if it only contains the characters A, T, C, and G.

def check_string(code):
    return all(character in {'A', 'T', 'C', 'G'} for character in code)


问:
How can I parse this xFBML invite-form in my iframe facebook app?
I got a Facebook canvas apps that already works for authentification on server side and client side. I can post on the wall of my user, and run my app in the canvas fine.

I wanted to add a 'invite your friends' page, and followed the doc by creating a xFBML form:

```<code>[...]
<div id='invite-friends-form'>
     <fb:serverfbml style="width: 650px;">
            <script type="text/fbml">
                <fb:fbml>
                  <fb:request-form
                    action="http://www.myapp.com:8080//invite/"
                    method="POST"
                    invite="true"
                    type="Name of my app"
                    content="My app description
                      <fb:req-choice url='http://apps.facebook.com/myapp/'
                      label='Accept'
                      />
                    " >
                    <fb:multi-friend-selector
                      showborder="false"
                      actiontext="Invite your friends to my app"
                      rows="4"
                    > <fb:multi-friend-selector />
                  </fb:request-form>
                </fb:fbml>
            </script>
        </fb:serverfbml>
</div>

<div id='fb-root'></div>

</body>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

<script src="http://connect.facebook.net/fr_FR/all.js"></script>
<!-- This does nothing so I commented it out. Can't find a way to debug
<script src="http://static.ak.fbcdn.net/connect/en_US/core.debug.js"></script> -->
<script src="http://myapp.com:8080/js/my_app_js.js"></script>

</html>
</code>```

This xFBML renders fine when tested in their test page.

Now, in my iframe, I got nothing but the facebook loading animation displaying forever.

Here is my Javascript. I use jQuery to run the code once DOM is ready:

```<code>$(function(){

  FB.init({
     appId  : 'my_app_id',
     status : true,
     cookie : true,
     xfbml  : true,
     level  : "debug"
   });

     FB.getLoginStatus(function(response) {

         if (response.session) {
             // logged in and connected user, someone you know

             alert('logged in'); // this always show up

                 FB.XFBML.parse(document.getElementById('invite-friends-form'),
                function(e) {alert(e)}
                );
             alert('after xfmbl parsing'); // this sometime show up

         }
     });

[...]
</code>```

I got no error showing up, and can't find anyway to debug this. I feel stuck.

Help warmly welcome :-)

答:
Found it:

You need to fill "url" and "domain name" in the internet site section of your app settings with url being the full web url (not the canvas one) and domain should be something like "mysite.com".

Body:
I got a Facebook canvas apps that already works for authentification on server side and client side. I can post on the wall of my user, and run my app in the canvas fine.

I wanted to add a 'invite your friends' page, and followed the doc by creating a xFBML form:

[...]

     <fb:serverfbml style="width: 650px;">

        </fb:serverfbml>

This xFBML renders fine when tested in their test page.

Now, in my iframe, I got nothing but the facebook loading animation displaying forever.

Here is my Javascript. I use jQuery to run the code once DOM is ready:

$(function(){

  FB.init({
     appId  : 'my_app_id',
     status : true,
     cookie : true,
     xfbml  : true,
     level  : "debug"
   });

     FB.getLoginStatus(function(response) {

         if (response.session) {
             // logged in and connected user, someone you know

             alert('logged in'); // this always show up

                 FB.XFBML.parse(document.getElementById('invite-friends-form'),
                function(e) {alert(e)}
                );
             alert('after xfmbl parsing'); // this sometime show up

         }
     });

[...]

I got no error showing up, and can't find anyway to debug this. I feel stuck.

Help warmly welcome :-)


问:
Function scope when used from outside controller
Supposedly we have an object with an arrow function in it like this:

```<code>obj: {
    key1: someValue,
    key2: (arg) => { $scope.close() }
}
</code>```

We pass this object to a component ( with isolated scope ), whose controller has the implementation of close().

What happens is that $scope is undefined ( if not injected in the controller where it was declared) or the $scope of controller it was declared , thus close() is always undefined.

Ideally i want to clone the function to the target controller.

Working fiddle

答:
Component's controller use isolate scope only so you cannot pass $scope from one component controller to another.

in your example you can try:

```<code>myFn($scope)
</code>```

and in parentComponent call $ctrl.data:

```<code>ctrl.obj = {
    key1: 'test',
    key2: (arg) => { console.log(arg.$ctrl.data); }
  }
</code>```

Example

Body:
Supposedly we have an object with an arrow function in it like this:

obj: {
    key1: someValue,
    key2: (arg) => { $scope.close() }
}

We pass this object to a component ( with isolated scope ), whose controller has the implementation of close().

What happens is that $scope is undefined ( if not injected in the controller where it was declared) or the $scope of controller it was declared , thus close() is always undefined.

Ideally i want to clone the function to the target controller.

Working fiddle

Body:
Component's controller use isolate scope only so you cannot pass $scope from one component controller to another.

in your example you can try:

myFn($scope)

and in parentComponent call $ctrl.data:

ctrl.obj = {
    key1: 'test',
    key2: (arg) => { console.log(arg.$ctrl.data); }
  }

Example


问:
incorrect display when using fish shell
My Mac laptop displays weirdly when using fish shell as below.

It maybe has nothing to do with fish shell, but I can not figure out what is going on.

the ENV: macOS sierra + iterm2(or terminal) + fish 2.4.0

It looks like this in Terminal

答:
I had the same issue recently. You can simply set the following variable color:

# Background color for matching quotes and parenthesis
set fish_color_match <your_color>

It will probably affect other things but for now (2 months) I haven't seen anything problematic with that.

Title: incorrect display when using fish shell


问:
Multiple SQL Server connection strings in app.config file
I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.

At first I thought of using a delimiter to separate the connections

```<code>  <appSettings>
    <add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>
</code>```

And then split the key value pairs.

Is it possible to do this in a different way?

答:
This is how to use LINQ to get list of connection strings:

```<code>List<string> connectionStrings = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .Select(v => v.ConnectionString)
    .ToList();
</code>```

Or you can build a dictionary of it:

```<code>Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .ToDictionary(v => v.Name, v => v.ConnectionString);
</code>```

Body:
I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.

At first I thought of using a delimiter to separate the connections

  <appSettings>
    <add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>

And then split the key value pairs.

Is it possible to do this in a different way?

Body:
This is how to use LINQ to get list of connection strings:

List<string> connectionStrings = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .Select(v => v.ConnectionString)
    .ToList();

Or you can build a dictionary of it:

Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .ToDictionary(v => v.Name, v => v.ConnectionString);