问:
Directly returning a rejected jQuery promise
For jQuery's promises, $.when() with no arguments returns a resolved promise. What is the equivalent that returns a rejected jQuery promise?

For example:

```<code>(function () { return $.when(); })()
   .then(()=>console.log('resolved'))
   .fail(()=>console.log('failed'));
</code>```

Prints "resolved". I'd like to change only what the function returns so that it prints "failed".

This is for bridging synchronous stuff with jQuery promises. The only thing I've thought of to do is to wrap the whole thing in a deferred object, e.g. where I might have:

```<code>function doSomething () {
    let success = ...;
    return success ? $.when() : /* not sure */;
}
</code>```

I could do this instead:

```<code>function doSomething () {
    return $.Deferred(function (def) {
        let success = ...;
        if (success)
            def.resolve();
        else
            def.reject();
    }).promise();
}
</code>```

But it would be more convenient if I didn't have to wrap things like that, and could return something like $.when() directly instead.

答:
If you absolutely want to use jQuery promises instead of native promises, you can use Deferred.reject:

(function () { return $.when($.Deferred().reject()); })()
   .then(()=>console.log('resolved'))
   .fail(()=>console.log('failed'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
For jQuery's promises, $.when() with no arguments returns a resolved promise. What is the equivalent that returns a rejected jQuery promise?

For example:

(function () { return $.when(); })()
   .then(()=>console.log('resolved'))
   .fail(()=>console.log('failed'));

Prints "resolved". I'd like to change only what the function returns so that it prints "failed".

This is for bridging synchronous stuff with jQuery promises. The only thing I've thought of to do is to wrap the whole thing in a deferred object, e.g. where I might have:

function doSomething () {
    let success = ...;
    return success ? $.when() : /* not sure */;
}

I could do this instead:

function doSomething () {
    return $.Deferred(function (def) {
        let success = ...;
        if (success)
            def.resolve();
        else
            def.reject();
    }).promise();
}

But it would be more convenient if I didn't have to wrap things like that, and could return something like $.when() directly instead.

Body:
If you absolutely want to use jQuery promises instead of native promises, you can use Deferred.reject:

(function () { return $.when($.Deferred().reject()); })()
   .then(()=>console.log('resolved'))
   .fail(()=>console.log('failed'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


来源: stackexchange

问:
Form request validation return error with old input
I am using Laravel's form request validation, which I find very useful, and is making my controllers a lot tidier.

My more complex validation pieces, which, if the Validator fails, should return back to the previous page, with the user's old input.

I also, sometimes, have to specify a named error bag, which again, doesn't seem to come built in as an option to the request forms.

Unfortunately, this additional error functions doesn't appear to come by default with the form requests validator.

At the moment I have:

```<code>$validator = Validator::make($request->all(), [
    'id' => 'required|numeric',
    'name' => 'required|alpha_spaces',
    'email' => 'required|email',
]);

if ($validator->fails()) {
    return back()
        ->withErrors($validator, 'aNamedErrorBag')
        ->withInput();
}
</code>```

Is there a way to extract the rules into a request validator file, and return with input to the named error bag aNamedErrorBag, should the validator fail?

Many thanks

答:
The FormRequest class juggles the name of the error bag as a property:

```<code>/**
 * The key to be used for the view error bag.
 *
 * @var string
 */
protected $errorBag = 'default';
</code>```

You can change this value to the errorBag that you want the errors to be sent to. Simply add it to your custom request class as a property.

Edit

This is what the FormRequest returns on the validation error:

```<code>/**
 * Get the proper failed validation response for the request.
 *
 * @param  array  $errors
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Laravel's form request validation, which I find very useful, and is making my controllers a lot tidier.

My more complex validation pieces, which, if the Validator fails, should return back to the previous page, with the user's old input.

I also, sometimes, have to specify a named error bag, which again, doesn't seem to come built in as an option to the request forms.

Unfortunately, this additional error functions doesn't appear to come by default with the form requests validator.

At the moment I have:

$validator = Validator::make($request->all(), [
    'id' => 'required|numeric',
    'name' => 'required|alpha_spaces',
    'email' => 'required|email',
]);

if ($validator->fails()) {
    return back()
        ->withErrors($validator, 'aNamedErrorBag')
        ->withInput();
}

Is there a way to extract the rules into a request validator file, and return with input to the named error bag aNamedErrorBag, should the validator fail?

Many thanks

Body:
The FormRequest class juggles the name of the error bag as a property:

/**
 * The key to be used for the view error bag.
 *
 * @var string
 */
protected $errorBag = 'default';

You can change this value to the errorBag that you want the errors to be sent to. Simply add it to your custom request class as a property.

Edit

This is what the FormRequest returns on the validation error:

/**
 * Get the proper failed validation response for the request.
 *
 * @param  array  $errors
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}


问:
Why does my code thinks that 60 is bigger than 135?

i want to get the bigger number and subtract by the smaller number (input's value) even tho they are in the wrong order when you put them into the input like -1 = inputX / 1 = inputY then 1 = greater and -1 smaller, it works with other numbers, but these kinda break it idk why tho what did I do wrong?
  why does it think 60 is bigger than 135? look at the img...

```<code><script type="text/javascript">
var x;
var y;
var big;
var small;
var result;
function calcT() {
    x = document.getElementById("inputX").value;
    y = document.getElementById("inputY").value;
    //result = x - y;
    if(x > y) {
      big = x;
      small = y;
       } else if(x < y) {
      big = y;
      small = x;
       }
    result = parseInt(big) - parseInt(small);
    document.getElementById("resultHere").innerHTML = result;

}
</code>```

答: I think there is a problem with variables define. Try to move var x,y,big,small; into the function.


问:
having trouble plotting a D3 line graph where X-Axis is not a date
I have data that looks like this:

```<code>LABEL,VALUE
2011/2012,6267.783164
2012/2013,6385.832768
2013/2014,6334.048158
2014/2015,6359.295548
2015/2016,6380.218338
2016/2017,6519.040832
2017/2018,6370.332847
</code>```

the Label is to be my x-axis values and though they represent a fiscal year they are esentially just a label that i want to be spaced equi-distint on a xaxis

here is the code I currently have ...note I have 2 similar data sets one for headcount and the other for FTE

I think it  has to do with this line I am just unsure what to change it too:

var x = d3.time.scale().range([0, width]);

```<code><!DOCTYPE html>
<meta charset="utf-8">

<head>
<title>Self Identification Percentages</title>
<style>
.dataDisplay {
  font-size:1em;
}

body { font: 12px Arial;}

path {
    stroke-width: 2;
    fill: none;
}

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

</style>

 <script src="./jquery.min.js" type="text/javascript"></script>
 <script src="./jquery-ui.min.js" type="text/javascript"></script>
 <script src="./jquery.corner.js"></script>
</head>

<body>

<script src="./d3/d3.v3.min.js"></script>

<div id="graph"></div>

<script>

// Set the dimensions of the canvas / graph
var margin = {top: 0, right: 20, bottom: 20, left: 60},
    width = 400 - margin.left - margin.right,
    height = 350 - margin.top - margin.bottom;

// Parse the date / time
///var parseDate = d3.time.format("%Y-%m-%d").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line()
    .x(function(d) { return x(d.LABEL); })
    .y(function(d) { return y(d.VALUE); });

// Adds the svg canvas
var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

// Get the data

 var dataFile = ".\\temp\\hc.csv";
 d3.csv(dataFile, function(error, data) {
    data.forEach(function(d) {
        d.LABEL = d.LABEL;
        d.VALUE = d.VALUE;
    });

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.LABEL; }));
    y.domain([0, d3.max(data, function(d) { return d.VALUE; })]);

    svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data))
        .attr("stroke", "#7CA2C8");

    // Add the X Axis
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -60)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
          .style("font-size", "12px")
          .style("font-weight", "900")
          .style("font", "sans-serif")
      .text("Count");

 });

 dataFile = ".\\temp\\fte.csv";
 d3.csv(dataFile, function(error, data) {
    data.forEach(function(d) {
        d.LABEL = d.LABEL;
        d.VALUE = d.VALUE;
    });

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.LABEL; }));
    y.domain([0, d3.max(data, function(d) { return d.VALUE; })]);

    // Add the valueline path.
    svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data))
        .attr("stroke", "#ECAD6F");
 });

</script>
<div class=Legend>
<b>
 <font size=2 color=#7CA2C8>HeadCount<font><!--input size 2 type="checkbox" id="HeadCount" name="HeadCount" value="HC" onChange="this.form.submit()"-->
 <font size=2 color=#7CC8A2>FTE<font><!--input size 2  type="checkbox" id="FTE" name="FTE" value="FTE"  onChange="this.form.submit()"-->
</b>
</div>

</body>
</html>
</code>```

答:
You probably want an ordinal scale:

Ordinal scales have a discrete domain, such as a set of names or
  categories. (d3v3 API documentation)

This will create a scale that will allow your data to "be spaced equi-distint on a xaxis".

The range can be set with .rangeRoundBands, as opposed to .range:

.rangeRoundBands([intervalMin,intervalMax]): Will map domain values to a continuous interval, ensuring that values are integers to avoid anti-aliasing effects.

.range([values]): Will map domain values to a range of discrete values

The API documentation has all this information though (and in greater detail).

Here's a simple example of your data drawn with an ordinal x scale (without axis labels, etc):

var data = [
{year:"2011/2012",value:6267.783164},
{year:"2012/2013",value:6385.832768},
{year:"2013/2014",value:6334.048158},
{year:"2014/2015",value:6359.295548},
{year:"2015/2016",value:6380.218338},
{year:"2016/2017",value:6519.040832},
{year:"2017/2018",value:6370.332847}
];

var width = 500;
var height = 400;

var x = d3.scale.ordinal()
  .rangeRoundBands([0,width])
  .domain(data.map(function(d) { return d.year }));

var y = d3.scale.linear()
  .range([height,0])
  .domain([d3.min(data,function(d) { return d.value; }), d3.max(data, function(d) { return d.value; })
  ]);

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var line = d3.svg.line()
  .x(function(d) { return x(d.year); })
  .y(function(d) { return y(d.value); });

svg.append("path")
  .datum(data)
  .attr("d",line)
  .attr("fill","none")
  .attr("stroke","steelblue");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script></code>```

Note:

With a bar graph each bar starts at a point returned by the ordinal scale, this is fine for bar graphs as each bar will be a certain width and the axis will account for this: The axis label will be aligned properly halfway between the beginning and end of the bar. However, with a line graph, the vertices of the line will be where each bar would have begun - and the labels will be half way between the vertices. So you may have to use an offset to align the ticks as you want along the x axis:

(relevant code:  .x(function(d) { return x(d.year) + x.rangeBand()/2; }) )

var data = [
{year:"2011/2012",value:6267.783164},
{year:"2012/2013",value:6385.832768},
{year:"2013/2014",value:6334.048158},
{year:"2014/2015",value:6359.295548},
{year:"2015/2016",value:6380.218338},
{year:"2016/2017",value:6519.040832},
{year:"2017/2018",value:6370.332847}
];

var width = 500;
var height = 200;
var margin = {top:10,left:10,bottom:30,right:10}

var x = d3.scale.ordinal()
  .rangeRoundBands([margin.left,width-margin.right])
  .domain(data.map(function(d) { return d.year }));

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var y = d3.scale.linear()
  .range([height-margin.bottom,margin.top])
  .domain([d3.min(data,function(d) { return d.value; }), d3.max(data, function(d) { return d.value; })
  ]);

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var line = d3.svg.line()
  .x(function(d) { return x(d.year) + x.rangeBand()/2; })
  .y(function(d) { return y(d.value); });

svg.append("path")
  .datum(data)
  .attr("d",line)
  .attr("fill","none")
  .attr("stroke","steelblue");

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (height - margin.bottom)  + ")")
    .call(xAxis);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.axis text {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}</code>```

```

Body:
I have data that looks like this:

LABEL,VALUE
2011/2012,6267.783164
2012/2013,6385.832768
2013/2014,6334.048158
2014/2015,6359.295548
2015/2016,6380.218338
2016/2017,6519.040832
2017/2018,6370.332847

the Label is to be my x-axis values and though they represent a fiscal year they are esentially just a label that i want to be spaced equi-distint on a xaxis

here is the code I currently have ...note I have 2 similar data sets one for headcount and the other for FTE

I think it  has to do with this line I am just unsure what to change it too:

var x = d3.time.scale().range([0, width]);

<!DOCTYPE html>
<meta charset="utf-8">

<title>Self Identification Percentages</title>

 HeadCount
 FTE

Body:
You probably want an ordinal scale:

Ordinal scales have a discrete domain, such as a set of names or
  categories. (d3v3 API documentation)

This will create a scale that will allow your data to "be spaced equi-distint on a xaxis".

The range can be set with .rangeRoundBands, as opposed to .range:

.rangeRoundBands([intervalMin,intervalMax]): Will map domain values to a continuous interval, ensuring that values are integers to avoid anti-aliasing effects.

.range([values]): Will map domain values to a range of discrete values

The API documentation has all this information though (and in greater detail).

Here's a simple example of your data drawn with an ordinal x scale (without axis labels, etc):

var data = [
{year:"2011/2012",value:6267.783164},
{year:"2012/2013",value:6385.832768},
{year:"2013/2014",value:6334.048158},
{year:"2014/2015",value:6359.295548},
{year:"2015/2016",value:6380.218338},
{year:"2016/2017",value:6519.040832},
{year:"2017/2018",value:6370.332847}
];

var width = 500;
var height = 400;

var x = d3.scale.ordinal()
  .rangeRoundBands([0,width])
  .domain(data.map(function(d) { return d.year }));

var y = d3.scale.linear()
  .range([height,0])
  .domain([d3.min(data,function(d) { return d.value; }), d3.max(data, function(d) { return d.value; })
  ]);

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var line = d3.svg.line()
  .x(function(d) { return x(d.year); })
  .y(function(d) { return y(d.value); });

svg.append("path")
  .datum(data)
  .attr("d",line)
  .attr("fill","none")
  .attr("stroke","steelblue");

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Note:

With a bar graph each bar starts at a point returned by the ordinal scale, this is fine for bar graphs as each bar will be a certain width and the axis will account for this: The axis label will be aligned properly halfway between the beginning and end of the bar. However, with a line graph, the vertices of the line will be where each bar would have begun - and the labels will be half way between the vertices. So you may have to use an offset to align the ticks as you want along the x axis:

(relevant code:  .x(function(d) { return x(d.year) + x.rangeBand()/2; }) )

var data = [
{year:"2011/2012",value:6267.783164},
{year:"2012/2013",value:6385.832768},
{year:"2013/2014",value:6334.048158},
{year:"2014/2015",value:6359.295548},
{year:"2015/2016",value:6380.218338},
{year:"2016/2017",value:6519.040832},
{year:"2017/2018",value:6370.332847}
];

var width = 500;
var height = 200;
var margin = {top:10,left:10,bottom:30,right:10}

var x = d3.scale.ordinal()
  .rangeRoundBands([margin.left,width-margin.right])
  .domain(data.map(function(d) { return d.year }));

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var y = d3.scale.linear()
  .range([height-margin.bottom,margin.top])
  .domain([d3.min(data,function(d) { return d.value; }), d3.max(data, function(d) { return d.value; })
  ]);

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)
  .attr("height",height);

var line = d3.svg.line()
  .x(function(d) { return x(d.year) + x.rangeBand()/2; })
  .y(function(d) { return y(d.value); });

svg.append("path")
  .datum(data)
  .attr("d",line)
  .attr("fill","none")
  .attr("stroke","steelblue");

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (height - margin.bottom)  + ")")
    .call(xAxis);

.axis text {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
Ruby Array#select with an options hash to match on
I have an array of hashes that I would like to search on, and I would like to write a method that takes an options hash as an argument and return all elements in the array that match against all key/value pairs dynamically, and I'm having trouble figuring it out.

```<code>my_array = [
  {
    foo: 'a',
    bar: 'b',
    baz: 'c'
  },
  {
    foo: 1,
    bar: 2,
    baz: 3
  },
  {
    foo: 'A',
    bar: 'B',
    baz: 'C'
  },
  {
    foo: 11,
    bar: 12,
    baz: 13
  }
]

# takes an opts hash and returns all elements for which all
# all key/value pairs match
def search_by(opts)
  opts.each do |k, v|
    self.select { |f| f[k] == f[v] }
  end
end

my_array.search_by(foo: 'a', bar: 'b')
# should return { foo: 'a', bar: 'b', baz: 'c' }
</code>```

I've tried a couple different ways to dynamically compose a block to pass to #select based on similar questions on SO, but I haven't had much luck and haven't been able to find this exact use case.  What's the best way to dynamically #select with multiple conditions while only having to execute #select once?

答:
You can use Hash#>=:

Returns true if other is subset of hash or equals to hash.

```<code>my_array.select { |h| h >= finder }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
</code>```

Body:
I have an array of hashes that I would like to search on, and I would like to write a method that takes an options hash as an argument and return all elements in the array that match against all key/value pairs dynamically, and I'm having trouble figuring it out.

my_array = [
  {
    foo: 'a',
    bar: 'b',
    baz: 'c'
  },
  {
    foo: 1,
    bar: 2,
    baz: 3
  },
  {
    foo: 'A',
    bar: 'B',
    baz: 'C'
  },
  {
    foo: 11,
    bar: 12,
    baz: 13
  }
]

# takes an opts hash and returns all elements for which all
# all key/value pairs match
def search_by(opts)
  opts.each do |k, v|
    self.select { |f| f[k] == f[v] }
  end
end

my_array.search_by(foo: 'a', bar: 'b')
# should return { foo: 'a', bar: 'b', baz: 'c' }

I've tried a couple different ways to dynamically compose a block to pass to #select based on similar questions on SO, but I haven't had much luck and haven't been able to find this exact use case.  What's the best way to dynamically #select with multiple conditions while only having to execute #select once?

Body:
You can use Hash#>=:

Returns true if other is subset of hash or equals to hash.

my_array.select { |h| h >= finder }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]


问:
2-way binding in Vue 2.3 component
I understand the .sync modifier returned in Vue 2.3, and am using it for a simple child component which implements a 'multiple-choice' question and answer. The parent component calls the child like this:

```<code><question
  :stem="What is your favourite colour?"
  :options="['Blue', 'No, wait, aaaaargh!']
  :answer.sync="userChoice"
>
</code>```

The parent has a string data element userChoice to store the result from the child component. The child presents the question and radio buttons for the options. The essential bits of the child look like this (I'm using Quasar, hence q-radio):

```<code><template>
  <div>
    <h5>{{stem}}</h5>
    <div class="option" v-for="opt in options">
      <label >
        <q-radio v-model="option" :val="opt.val" @input="handleInput"></q-radio>
        {{opt.text}}
      </label>
    </div>
  </div>
</template>

export default {
  props: {
    stem: String,
    options: Array,
    answer: String
  },
  data: () => ({
    option: null
  }),
  methods: {
    handleInput () {
      this.$emit('update:answer', this.option)
    }
  }
}
</code>```

This is all working fine, apart from the fact that if the parent then changes the value of userChoice due to something else happening in the app, the child doesn't update the radio buttons. I had to include this watch in the child:

```<code>  watch: {
    answer () {
      this.option = this.answer
    }
  }
</code>```

But it feels a little redundant, and I was worried that emitting the event to update the parent's data would in fact cause the child 'watch' event to also fire. In this case it would have no effect other than wasting a few cycles, but if it was logging or counting anything, that would be a false positive...

Maybe that is the correct solution for true 2-way binding (i.e. dynamic Parent → Child, as well as Child → Parent). Did I miss something about how to connect the 'in' and 'out' data on both sides?

In case you're wondering, the most common case of the parent wanting to change 'userChoice' would be in response to a 'Clear Answers' button which would set userChoice back to an empty string. That should have the effect of 'unsetting' all the radio buttons.

答:
Your construction had some oddities that didn't work, but basically answer.sync works if you propagate it down to the q-radio component where the changing happens. Changing the answer in the parent is handled properly, but to clear values, it seems you need to set it to an object rather than null (I think this is because it needs to be assignable).

Update
Your setup of options is a notable thing that didn't work.

I use answer in the q-radio to control its checked state (v-model has special behavior in a radio, which is why I use value in conjunction with v-model). From your comment, it looks like q-radio wants to have a value it can set. You ought to be able to do that with a computed based on answer, which you would use instead of your option data item: the get returns answer, and the set does the emit. I have updated my snippet to use the val prop for q-radio plus the computed I describe. The proxyAnswer emits an update event, which is what the .sync modifier wants. I also implemented q-radio using a proxy computed, but that's just to get the behavior that should already be baked-into your q-radio.

(What I describe is effectively what you're doing with a data item and a watcher, but a computed is a nicer way to encapsulate that).

new Vue({
  el: '#app',
  data: {
    userChoice: null,
    options: ['Blue', 'No, wait, aaaaargh!'].map(v => ({
      value: v,
      text: v
    }))
  },
  components: {
    question: {
      props: {
        stem: String,
        options: Array,
        answer: String
      },
      computed: {
        proxyAnswer: {
          get() {
            return this.answer;
          },
          set(newValue) {
            this.$emit('update:answer', newValue);
          }
        }
      },
      components: {
        qRadio: {
          props: ['value', 'val'],
          computed: {
            proxyValue: {
              get() {
                return this.value;
              },
              set(newValue) {
                this.$emit('input', newValue);
              }
            }
          }
        }
      }
    }
  },
  methods: {
    clearSelection() {
      this.userChoice = {};
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id="app">
  <question stem="What is your favourite colour?" :options="options" :answer.sync="userChoice" inline-template>
    <div>
      <h5>{{stem}}</h5>
      <div class="option" v-for="opt in options">
        <div>Answer={{answer && answer.text}}, option={{opt.text}}</div>
        <label>
        <q-radio :val="opt" v-model="proxyAnswer" inline-template>
          <input type="radio" :value="val" v-model="proxyValue">
        </q-radio>
        {{opt.text}}
      </label>
      </div>
    </div>
  </question>
  <button @click="clearSelection">Clear</button>
</div></code>```

Title: 2-way binding in Vue 2.3 component

Body:
I understand the .sync modifier returned in Vue 2.3, and am using it for a simple child component which implements a 'multiple-choice' question and answer. The parent component calls the child like this:

<question
  :stem="What is your favourite colour?"
  :options="['Blue', 'No, wait, aaaaargh!']
  :answer.sync="userChoice"
>

The parent has a string data element userChoice to store the result from the child component. The child presents the question and radio buttons for the options. The essential bits of the child look like this (I'm using Quasar, hence q-radio):

<template>

{{stem}}

        <q-radio v-model="option" :val="opt.val" @input="handleInput"></q-radio>
        {{opt.text}}

</template>

export default {
  props: {
    stem: String,
    options: Array,
    answer: String
  },
  data: () => ({
    option: null
  }),
  methods: {
    handleInput () {
      this.$emit('update:answer', this.option)
    }
  }
}

This is all working fine, apart from the fact that if the parent then changes the value of userChoice due to something else happening in the app, the child doesn't update the radio buttons. I had to include this watch in the child:

  watch: {
    answer () {
      this.option = this.answer
    }
  }

But it feels a little redundant, and I was worried that emitting the event to update the parent's data would in fact cause the child 'watch' event to also fire. In this case it would have no effect other than wasting a few cycles, but if it was logging or counting anything, that would be a false positive...

Maybe that is the correct solution for true 2-way binding (i.e. dynamic Parent → Child, as well as Child → Parent). Did I miss something about how to connect the 'in' and 'out' data on both sides?

In case you're wondering, the most common case of the parent wanting to change 'userChoice' would be in response to a 'Clear Answers' button which would set userChoice back to an empty string. That should have the effect of 'unsetting' all the radio buttons.

Body:
Your construction had some oddities that didn't work, but basically answer.sync works if you propagate it down to the q-radio component where the changing happens. Changing the answer in the parent is handled properly, but to clear values, it seems you need to set it to an object rather than null (I think this is because it needs to be assignable).

Update
Your setup of options is a notable thing that didn't work.

I use answer in the q-radio to control its checked state (v-model has special behavior in a radio, which is why I use value in conjunction with v-model). From your comment, it looks like q-radio wants to have a value it can set. You ought to be able to do that with a computed based on answer, which you would use instead of your option data item: the get returns answer, and the set does the emit. I have updated my snippet to use the val prop for q-radio plus the computed I describe. The proxyAnswer emits an update event, which is what the .sync modifier wants. I also implemented q-radio using a proxy computed, but that's just to get the behavior that should already be baked-into your q-radio.

(What I describe is effectively what you're doing with a data item and a watcher, but a computed is a nicer way to encapsulate that).

new Vue({
  el: '#app',
  data: {
    userChoice: null,
    options: ['Blue', 'No, wait, aaaaargh!'].map(v => ({
      value: v,
      text: v
    }))
  },
  components: {
    question: {
      props: {
        stem: String,
        options: Array,
        answer: String
      },
      computed: {
        proxyAnswer: {
          get() {
            return this.answer;
          },
          set(newValue) {
            this.$emit('update:answer', newValue);
          }
        }
      },
      components: {
        qRadio: {
          props: ['value', 'val'],
          computed: {
            proxyValue: {
              get() {
                return this.value;
              },
              set(newValue) {
                this.$emit('input', newValue);
              }
            }
          }
        }
      }
    }
  },
  methods: {
    clearSelection() {
      this.userChoice = {};
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id="app">
  <question stem="What is your favourite colour?" :options="options" :answer.sync="userChoice" inline-template>
    <div>
      <h5>{{stem}}</h5>
      <div class="option" v-for="opt in options">
        <div>Answer={{answer && answer.text}}, option={{opt.text}}</div>
        <label>
        <q-radio :val="opt" v-model="proxyAnswer" inline-template>
          <input type="radio" :value="val" v-model="proxyValue">
        </q-radio>
        {{opt.text}}
      </label>
      </div>
    </div>
  </question>
  <button @click="clearSelection">Clear</button>
</div>


问:
Custom widget on QItemDelegate editor for QTableView
I have a QTableView showing a data from a custom model. I have a QItemDelegate for the edition on each of the cells. One column of the view has a custom widget comprised by a QLineEdit and a QCheckBox. When I click on the cells of this column the editor is shown and it works, but it doesn't fit the table cell. Moreover, when I enlarge a row and click on the cell, I can see the data of the cell behind the widget.

Is there a way that my widget behaves like a normal editing widget for a QItemDelegate on the view? i.e when created it uses all the vertical space of the cell?

This is my widget (simplified):

```<code>class MyWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)
        self.lineEdit = QtGui.QLineEdit(parent)
        self.checkBox = QtGui.QCheckBox(parent)
        self.checkBox.setChecked(False)
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.setSpacing(3)
        self.gridLayout.addWidget(self.lineEdit, 0, 0)
        self.gridLayout.addWidget(self.checkBox, 0, 1)
</code>```

My delegate (simplified):

```<code>class MyDelegate(QtGui.QItemDelegate):
    def __init__(self, parent = None):
        super(MyDelegate, self).__init__(parent)

    def createEditor(self, parent, option, index):
        return MyWidget(parent)

    def setModelData(self, editor, model, index):
        pass

    def setEditorData(self, editor, model, index):
        pass
</code>```

答:
There are a number of different problems:

The vertical size-policy of a QLineEdit is fixed by default, so it will not expand to fill the availabe space.

The layout has a default contents margin (i.e. padding) which may constrain the size of the contained widgets.

By default, a QWidget does not draw its own background automatically, so the cell's data may be visible underneath.

If the widget takes up all the space in the cell, it will no longer be possible to show that the cell is selected.

All these problems can be fixed as follows:

```<code>class MyWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)
        # create an inner widget
        widget = QtGui.QWidget(self)
        # disable widget transparency
        widget.setAutoFillBackground(True)
        # allow the line-edit to fully expand
        self.lineEdit = QtGui.QLineEdit(widget)
        self.lineEdit.setSizePolicy(QtGui.QSizePolicy(
            QtGui.QSizePolicy.MinimumExpanding,
            QtGui.QSizePolicy.MinimumExpanding))
        self.checkBox = QtGui.QCheckBox(widget)
        self.checkBox.setChecked(False)
        # trim space on right side of checkbox
        self.checkBox.setText('')
        hbox = QtGui.QHBoxLayout(widget)
        # remove the inner margin
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(3)
        hbox.addWidget(self.lineEdit)
        hbox.addWidget(self.checkBox)
        layout = QtGui.QVBoxLayout(self)
        # set the selection rectangle width
        layout.setContentsMargins(2, 2, 2, 2)
        layout.addWidget(widget)
</code>```

And will look like this:

Body:
I have a QTableView showing a data from a custom model. I have a QItemDelegate for the edition on each of the cells. One column of the view has a custom widget comprised by a QLineEdit and a QCheckBox. When I click on the cells of this column the editor is shown and it works, but it doesn't fit the table cell. Moreover, when I enlarge a row and click on the cell, I can see the data of the cell behind the widget.

Is there a way that my widget behaves like a normal editing widget for a QItemDelegate on the view? i.e when created it uses all the vertical space of the cell?

This is my widget (simplified):

class MyWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)
        self.lineEdit = QtGui.QLineEdit(parent)
        self.checkBox = QtGui.QCheckBox(parent)
        self.checkBox.setChecked(False)
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.setSpacing(3)
        self.gridLayout.addWidget(self.lineEdit, 0, 0)
        self.gridLayout.addWidget(self.checkBox, 0, 1)

My delegate (simplified):

class MyDelegate(QtGui.QItemDelegate):
    def __init__(self, parent = None):
        super(MyDelegate, self).__init__(parent)

    def createEditor(self, parent, option, index):
        return MyWidget(parent)

    def setModelData(self, editor, model, index):
        pass

    def setEditorData(self, editor, model, index):
        pass

Body:
There are a number of different problems:

The vertical size-policy of a QLineEdit is fixed by default, so it will not expand to fill the availabe space.

The layout has a default contents margin (i.e. padding) which may constrain the size of the contained widgets.

By default, a QWidget does not draw its own background automatically, so the cell's data may be visible underneath.

If the widget takes up all the space in the cell, it will no longer be possible to show that the cell is selected.

All these problems can be fixed as follows:

class MyWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)
        # create an inner widget
        widget = QtGui.QWidget(self)
        # disable widget transparency
        widget.setAutoFillBackground(True)
        # allow the line-edit to fully expand
        self.lineEdit = QtGui.QLineEdit(widget)
        self.lineEdit.setSizePolicy(QtGui.QSizePolicy(
            QtGui.QSizePolicy.MinimumExpanding,
            QtGui.QSizePolicy.MinimumExpanding))
        self.checkBox = QtGui.QCheckBox(widget)
        self.checkBox.setChecked(False)
        # trim space on right side of checkbox
        self.checkBox.setText('')
        hbox = QtGui.QHBoxLayout(widget)
        # remove the inner margin
        hbox.setContentsMargins(0, 0, 0, 0)
        hbox.setSpacing(3)
        hbox.addWidget(self.lineEdit)
        hbox.addWidget(self.checkBox)
        layout = QtGui.QVBoxLayout(self)
        # set the selection rectangle width
        layout.setContentsMargins(2, 2, 2, 2)
        layout.addWidget(widget)

And will look like this:


问:
Force to do flush to get new Primary key ID to store EmbeddedId
We are using JPA and we are using EmbeddedId in one of the Entity.

Tables are as bellow :

```<code>Role:
+-----------------------------+
| roleId | name | discription |
+-----------------------------+

Rights:
+-----------------------------+
| rightId | name | discription|
+-----------------------------+

rightrole
+--------------------------------------+
| roleId | rightId | some other column |
+--------------------------------------+
</code>```

Entity for role table is:

```<code>@Entity
@Table(name = "role")
public class Role {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Long roleID;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "role", fetch = FetchType.LAZY)
    private List<RightRole> rightRoleList;

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

Entity for rightrole table is:

```<code>    @Entity
    @Table(name = "rightrole")
    public class RightRole extends BaseEntity<RightRolePK> {

        private static final long serialVersionUID = 1L;

        @EmbeddedId
        protected RightRolePK rightRolePK;

        @JoinColumn(name = "roleID", referencedColumnName = "roleID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Role role;

        @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Right right;

        ......
     }

    @Embeddable
    public class RightRolePK implements Serializable {
    private static final long serialVersionUID = 1L;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
      private long roleID;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
     private long rightID;

   .....

}
</code>```

My problem is whenever I want to create new role with rights then first I have to store(persist) role object and then I have to do flush to get newly generated id for role. then and then i can put it in rightrole entity's object.

Is there any way by that i can set rightrole list in role object and persist it in one go.

This flush casing us performance bottle neck because for bulk insert we have to persist single single object.

we are using Auto Generated primary key.

答:
JPA 2.0 allows derived IDs, an expanded to support this better by adding @MapsId.  Keeping everything else the same but using:

```<code>@Entity
@Table(name = "rightrole")
public class RightRole extends BaseEntity<RightRolePK> {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    protected RightRolePK rightRolePK;

    @MapsId("roleID")
    @JoinColumn(name = "roleID", referencedColumnName = "roleID")
    @ManyToOne(fetch = FetchType.LAZY)
    private Role role;

    @MapsId("rightID")
    @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
    @ManyToOne(fetch = FetchType.LAZY)
    private Right right;

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

This will tell JPA that the value within the roleID and rightID attributes in your PK class are controlled by the relationship mapping, and it will set it after synchronizing to the database with the primary key value from the reference.  You just need to be sure you set the relationship before calling persist, as it doesn't have a primary key otherwise.

This works even if the referenced object is also composite.  Something that needs to reference RightRole would use RightRolePK though instead of a Long value:

```<code>@Entity
@Table(name = "wrong_right_role")
public class WrongRightRole{
    @EmbeddedId
    WrongRightRoleId wrongRightRoleId;

    @MapsId("rightRoleID")
    @JoinColumns({
        @JoinColumn(name = "roleID", referencedColumnName = "roleID"),
        @JoinColumn(name = "rightID", referencedColumnName = "rightID")
    })
    RightRole rightRole;

}

@Embeddable
public class WrongRightRolePK implements Serializable {
private static final long serialVersionUID = 1L;

  private RightRoleID rightRoleID;
  .....
}
</code>```

JPA also allows marking the right and role mappings with the @ID annotation, allowing you to remove the rightRolePK embeddedId from within the object, and use it as a primary key class instead.

Body:
We are using JPA and we are using EmbeddedId in one of the Entity.

Tables are as bellow :

Role:
+-----------------------------+
| roleId | name | discription |
+-----------------------------+

Rights:
+-----------------------------+
| rightId | name | discription|
+-----------------------------+

rightrole
+--------------------------------------+
| roleId | rightId | some other column |
+--------------------------------------+

Entity for role table is:

@Entity
@Table(name = "role")
public class Role {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Long roleID;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "role", fetch = FetchType.LAZY)
    private List<RightRole> rightRoleList;

.......
}

Entity for rightrole table is:

    @Entity
    @Table(name = "rightrole")
    public class RightRole extends BaseEntity<RightRolePK> {

        private static final long serialVersionUID = 1L;

        @EmbeddedId
        protected RightRolePK rightRolePK;

        @JoinColumn(name = "roleID", referencedColumnName = "roleID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Role role;

        @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Right right;

        ......
     }

    @Embeddable
    public class RightRolePK implements Serializable {
    private static final long serialVersionUID = 1L;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
      private long roleID;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
     private long rightID;

   .....

}

My problem is whenever I want to create new role with rights then first I have to store(persist) role object and then I have to do flush to get newly generated id for role. then and then i can put it in rightrole entity's object.

Is there any way by that i can set rightrole list in role object and persist it in one go.

This flush casing us performance bottle neck because for bulk insert we have to persist single single object.

we are using Auto Generated primary key.

Body:
JPA 2.0 allows derived IDs, an expanded to support this better by adding @MapsId.  Keeping everything else the same but using:

@Entity
@Table(name = "rightrole")
public class RightRole extends BaseEntity<RightRolePK> {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    protected RightRolePK rightRolePK;

    @MapsId("roleID")
    @JoinColumn(name = "roleID", referencedColumnName = "roleID")
    @ManyToOne(fetch = FetchType.LAZY)
    private Role role;

    @MapsId("rightID")
    @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
    @ManyToOne(fetch = FetchType.LAZY)
    private Right right;

    ......
 }

This will tell JPA that the value within the roleID and rightID attributes in your PK class are controlled by the relationship mapping, and it will set it after synchronizing to the database with the primary key value from the reference.  You just need to be sure you set the relationship before calling persist, as it doesn't have a primary key otherwise.

This works even if the referenced object is also composite.  Something that needs to reference RightRole would use RightRolePK though instead of a Long value:

@Entity
@Table(name = "wrong_right_role")
public class WrongRightRole{
    @EmbeddedId
    WrongRightRoleId wrongRightRoleId;

    @MapsId("rightRoleID")
    @JoinColumns({
        @JoinColumn(name = "roleID", referencedColumnName = "roleID"),
        @JoinColumn(name = "rightID", referencedColumnName = "rightID")
    })
    RightRole rightRole;

}

@Embeddable
public class WrongRightRolePK implements Serializable {
private static final long serialVersionUID = 1L;

  private RightRoleID rightRoleID;
  .....
}

JPA also allows marking the right and role mappings with the @ID annotation, allowing you to remove the rightRolePK embeddedId from within the object, and use it as a primary key class instead.


问:
Return only matches from substitution in Perl 5.8.8 (was: Perl "p" regex modifier equivalent)
I've got a script (source) to parse svn info to create a suitable string for Bash's $PS1. Unfortunately this doesn't work on one system I'm using which is running Perl 5.8.8 - It outputs all lines instead of only the matches. What would be the Perl 5.8.8 equivalent to the following?

```<code>__svn_ps1()
{
    local result=$(
        svn info 2>/dev/null | \
        perl -pe 's;^URL: .*?/((trunk)|(branches|tags)/([^/]*)).*;\2\4 ;p')
    if [ -n "$result" ]
    then
        printf "${1:- (%s)}" $result
    fi
}
</code>```

The output from Perl 5.10 contains only a space, parenthesis, one of branch name, tag name or trunk, and the end parenthesis. The output from Perl 5.8.8 (without the final p) contains this plus a parenthesized version of each space-separated part of the svn info output.

A possible workaround involves a simple grep '^URL: ' between the svn and perl commands, but I was hoping to avoid that since this will be executed for each Bash prompt.

答:
If you only want output from a line that matches, don't use the -p command-line switch. It prints the value of $_ at the end of each loop. You might want something with the -n command-line switch:

```<code> perl -ne 'print if s/.../.../'
</code>```

I'd do it in the same way for Perl v5.8 and v5.10. I'm not sure what you think the /p modifier is doing since you don't use the $`, $&, or $' variables or their per-match equivalents.

You can read about the command-line switches in perlrun.

ContentLicense: CC BY-SA 2.5

Body:
I've got a script (source) to parse svn info to create a suitable string for Bash's $PS1. Unfortunately this doesn't work on one system I'm using which is running Perl 5.8.8 - It outputs all lines instead of only the matches. What would be the Perl 5.8.8 equivalent to the following?

__svn_ps1()
{
    local result=$(
        svn info 2>/dev/null | \
        perl -pe 's;^URL: .*?/((trunk)|(branches|tags)/([^/]*)).*;\2\4 ;p')
    if [ -n "$result" ]
    then
        printf "${1:- (%s)}" $result
    fi
}

The output from Perl 5.10 contains only a space, parenthesis, one of branch name, tag name or trunk, and the end parenthesis. The output from Perl 5.8.8 (without the final p) contains this plus a parenthesized version of each space-separated part of the svn info output.

A possible workaround involves a simple grep '^URL: ' between the svn and perl commands, but I was hoping to avoid that since this will be executed for each Bash prompt.

Body:
If you only want output from a line that matches, don't use the -p command-line switch. It prints the value of $_ at the end of each loop. You might want something with the -n command-line switch:

 perl -ne 'print if s/.../.../'

I'd do it in the same way for Perl v5.8 and v5.10. I'm not sure what you think the /p modifier is doing since you don't use the $`, $&, or $' variables or their per-match equivalents.

You can read about the command-line switches in perlrun.


问:
Swift Getting Character from Keycode Using CGEvent
I have a key code from:

```<code>let keycode = event.GetIntegerValueField(.keyboardEventKeycode)
</code>```

Is there way to translate it into a character?

```<code>func keyboardGetUnicodeString(maxStringLength: Int, actualStringLength: UnsafeMutablePointer <Int>?, unicodeString: UnsafeMutablePointer <UniChar>?)
</code>```

It seems this is what I need, but it looks scary! Could someone explain how to call that function from swift? Thanks!

答:
```<code>var char = UniChar()
var length = 0
event.keyboardGetUnicodeString(maxStringLength: 1, actualStringLength: &length, unicodeString: &char)
</code>```

Body:
I have a key code from:

let keycode = event.GetIntegerValueField(.keyboardEventKeycode)

Is there way to translate it into a character?

func keyboardGetUnicodeString(maxStringLength: Int, actualStringLength: UnsafeMutablePointer <Int>?, unicodeString: UnsafeMutablePointer <UniChar>?)

It seems this is what I need, but it looks scary! Could someone explain how to call that function from swift? Thanks!


问:
JavaScript count items that have been run in an array
I'm very new to Javascript so i'm looking for a bit of help.
I have a webpage that loads a iframe and loops through loads of URLs. This all works after a bit of help.

However i now need a div showing the count of the completed urls, so everytime it does one it increases the count by one.

Any ideads?

答:
Just set the div's .innerHTML = the value of your index.

var urls1 = [
  'https://localhost:8500/SupportTools/t1.cfm',
  'https://localhost:8500/SupportTools/t2.cfm',
  'https://localhost:8500/SupportTools/t3.cfm',
  'https://localhost:8500/SupportTools/t4.cfm',
  'https://localhost:8500/SupportTools/t5.cfm'
];

function showUrl1(idx) {
  var f1 = document.getElementById("f1");
  f1.onload = function() {
    if (idx >= urls1.length) {
      return;
    }

    var next = ++idx;

    setTimeout(function() {
      if (next != null) {
        document.getElementById("counter").innerHTML = idx;
        showUrl1(next);
      }
    }, 500);
  }

  f1.src = urls1[idx];
}

function start() {
  showUrl1(0);
}

start();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <iframe class="show1" id="f1" src="about:blank"></iframe>
  <div id="counter" class="count1">0</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
Just set the div's .innerHTML = the value of your index.

var urls1 = [
  'https://localhost:8500/SupportTools/t1.cfm',
  'https://localhost:8500/SupportTools/t2.cfm',
  'https://localhost:8500/SupportTools/t3.cfm',
  'https://localhost:8500/SupportTools/t4.cfm',
  'https://localhost:8500/SupportTools/t5.cfm'
];

function showUrl1(idx) {
  var f1 = document.getElementById("f1");
  f1.onload = function() {
    if (idx >= urls1.length) {
      return;
    }

    var next = ++idx;

    setTimeout(function() {
      if (next != null) {
        document.getElementById("counter").innerHTML = idx;
        showUrl1(next);
      }
    }, 500);
  }

  f1.src = urls1[idx];
}

function start() {
  showUrl1(0);
}

start();

<div class="container">
  <iframe class="show1" id="f1" src="about:blank"></iframe>
  <div id="counter" class="count1">0</div>
</div>


问:
mongodb/mongoose - when to use subdocument and when to use new collection
I would like to know if there is a rule of thumb about when to use a new document and when to use a sub document. In sql database I used to break all realtions to seperate tables by the rule of normalization and connect them with keys , but I can't find a good approch about what to do in mongodb ( I don't know how other no-sql databases are handled).
Any help will be appreicated.
Kind regards.</p>

答:
Though no fixed rules, there are some general guidelines which are intuitive enough to follow while modeling data in noSql.

Nearly all cases of 1-1 can be handled with sub-documents. For example: A user has an address. All likelihood is that address would be unique for each user (in context of your system, say a social website). So, keeping address in another collection would be a waste of space and queries. Address sub-document is the best choice.

Another example: Hundreds of employees share a same building/address. In this case keeping 1-1 is a poor use of space and will cost you a lot of updates whenever a slight change happens in any of the addresses because it's being replicated across multiple employee documents as sub-document. Therefore, an address should have many employees i.e. 1 to many relationship

You must have noticed that in noSql there are multiple ways to represent 1 to many relationship.

Keep an array of references. Choose this if you're sure the size of the array won't get too big and preferably the document containing the array is not expected to be updated a lot.

Keep an array of sub-documents. A handy option if the sub-documents don't qualify for a separate collection and you don't run the risk of hitting 16Mb document size limit. (thanks greyfairer for reminding!)

Sql style foreign key. Use this if 1 and 2 are not good enough or you prefer this style over them

Modeling documents for retrieval, Document design considerations and Modeling Relationships from Couchbase (another noSql database) are really good reads and equally applicable to mongodb.


问:
Applescript Error -10810
I have an Applescript that runs fine on my Macbook Retina but fails on a Mac Mini.

Both are running MacOS 10.9.2.

After peeling the onion a bit I'm able to reproduce the problem with a one-line Applescript:

```<code>tell application "MidiPipe" to activate
</code>```

On the Mini that throws the error:

```<code>An error of type -10810 has occurred.
</code>```

On the Macbook the MidiPipe application opens.

MidiPipe works normally on the Mini when started from the Finder or from Launchpad.

Google provides no insight into this error.

答:
Could be nothing more than another mysterious grieving crap from Apple.

Today I have faced this myself, first time after using four different Mac Minis as build servers for Continuous Integration of Mobile apps for about two years or so.

My Jenkins runs the osascript from the bash script to build the app.

A few days ago the office experienced the power outage and all Macs went down. After powering them back on I have got this error at osascript execution on one of my Macs.

I have tried just to re-build - with the same result.

First thing I stumbled upon was https://jacobsalmela.com/2014/08/04/infamous-execution-error-error-type-10810-occurred-10810/ , but none of them applied to me.

Then I googled more general 10810 issue occurrences and went through couple of questions here on SO.

Still no luck.

Next I reached to the server via SSH using PuTTY and tried telling Terminal to do the very basic script like

```<code> osascript -e 'tell application "Terminal"
 activate
 tell window 1
 do script "counter=0; while true; do if [ \"$counter\" -gt \"10\" ]; then
     break; else counter=$((counter + 1)); sleep 1; fi; done; exit;"
 end tell
 end tell'
</code>```

This worked fine.

Then I tried to run the whole bash script that Jenkins used to execute. Everything went just perfect and the app was uploaded to HockeyApp as the result.

I came with the thought that the issue is that Jenkins runs it remotely on that Mac and finally I have tried just to re-build again and it magically worked fine this time.

No idea what it was, but since then I have performed three or more builds already and all of them were successful.

Note I haven't changed anything, and my script:

1) never used a full path;

2) always used an actual tell block;

3,4) nothing like that from the accepted answer was ever used.

So... Go away mysterious grieving crap! Go away! :)

Title: Applescript Error -10810

Body:
I have an Applescript that runs fine on my Macbook Retina but fails on a Mac Mini.

Both are running MacOS 10.9.2.

After peeling the onion a bit I'm able to reproduce the problem with a one-line Applescript:

tell application "MidiPipe" to activate

On the Mini that throws the error:

An error of type -10810 has occurred.

On the Macbook the MidiPipe application opens.

MidiPipe works normally on the Mini when started from the Finder or from Launchpad.

Google provides no insight into this error.

Body:
Could be nothing more than another mysterious grieving crap from Apple.

Today I have faced this myself, first time after using four different Mac Minis as build servers for Continuous Integration of Mobile apps for about two years or so.

My Jenkins runs the osascript from the bash script to build the app.

A few days ago the office experienced the power outage and all Macs went down. After powering them back on I have got this error at osascript execution on one of my Macs.

I have tried just to re-build - with the same result.

First thing I stumbled upon was https://jacobsalmela.com/2014/08/04/infamous-execution-error-error-type-10810-occurred-10810/ , but none of them applied to me.

Then I googled more general 10810 issue occurrences and went through couple of questions here on SO.

Still no luck.

Next I reached to the server via SSH using PuTTY and tried telling Terminal to do the very basic script like

 osascript -e 'tell application "Terminal"
 activate
 tell window 1
 do script "counter=0; while true; do if [ \"$counter\" -gt \"10\" ]; then
     break; else counter=$((counter + 1)); sleep 1; fi; done; exit;"
 end tell
 end tell'

This worked fine.

Then I tried to run the whole bash script that Jenkins used to execute. Everything went just perfect and the app was uploaded to HockeyApp as the result.

I came with the thought that the issue is that Jenkins runs it remotely on that Mac and finally I have tried just to re-build again and it magically worked fine this time.

No idea what it was, but since then I have performed three or more builds already and all of them were successful.

Note I haven't changed anything, and my script:

1) never used a full path;

2) always used an actual tell block;

3,4) nothing like that from the accepted answer was ever used.

So... Go away mysterious grieving crap! Go away! :)


问:
Why does Eclipse sometimes ignore my breakpoints?
I'm android developer and I use Eclipse.

Sometimes, when I am debugging my apps, Eclipse doesn't stop on my breakpoints. Eclipse shows a "v" symbol on the breakpoint.  I think this symbol means that Eclipse has passed the breakpoint without problems, but I would like Eclipse to stop when it reaches the breakpoint.

Of course, I have pressed the debug button (the icon with the green bug on it.)

How can I avoid this behavior?

答: Most likley your source and class files run out of sync. If this happens clean and rebuild your project. This should make the issue disappear.</p>


问:
How to remove cursor from a Map (Bukkit)
I'm currently developing a plugin which only renders an image to a map like this:

```<code>public class MapRendererTest extends MapRenderer {

    private Image image;

    public MapRendererTest(File file) {
        try {
            this.image = ImageIO.read(file);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void render(MapView mapView, MapCanvas mapCanvas, Player player) {
        mapCanvas.drawImage(0, 0, image);
    }
}
</code>```

everything works fine, but there is this little thing in the red circle that I want to remove but I don't know how.

Things I already tried

Setting an emtpy MapCursorCollection

MapView.setWorld to a world where no-one is playing.

Creating MapCursorCollection with a invisible cursor

It would be amazing if someone could help me with that.

Thanks in advance

答:
To get rid of the cursor, you have to remove all the other map renderers or at least the CraftMapRanderer.

In order to do this, you have to do the following:

```<code>@EventHandler
public void onMapInitialized(MapInitializeEvent e) {
    e.getMap().removeRenderer(e.getMap().getRenderers().get(0));
    e.getMap().addRenderer(new MapRendererTest(new File(Main.getInstance().getDataFolder() + "/image.png")));
}
</code>```

This only works of course if there is no other custom map renderer assigned to this map, so the only registered is the CraftMapRenderer.

If you have multiple MapRenderers you could loop through the list and remove them.

Body:
I'm currently developing a plugin which only renders an image to a map like this:

public class MapRendererTest extends MapRenderer {

    private Image image;

    public MapRendererTest(File file) {
        try {
            this.image = ImageIO.read(file);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void render(MapView mapView, MapCanvas mapCanvas, Player player) {
        mapCanvas.drawImage(0, 0, image);
    }
}

everything works fine, but there is this little thing in the red circle that I want to remove but I don't know how.

Things I already tried

Setting an emtpy MapCursorCollection

MapView.setWorld to a world where no-one is playing.

Creating MapCursorCollection with a invisible cursor

It would be amazing if someone could help me with that.

Thanks in advance

Body:
To get rid of the cursor, you have to remove all the other map renderers or at least the CraftMapRanderer.

In order to do this, you have to do the following:

@EventHandler
public void onMapInitialized(MapInitializeEvent e) {
    e.getMap().removeRenderer(e.getMap().getRenderers().get(0));
    e.getMap().addRenderer(new MapRendererTest(new File(Main.getInstance().getDataFolder() + "/image.png")));
}

This only works of course if there is no other custom map renderer assigned to this map, so the only registered is the CraftMapRenderer.

If you have multiple MapRenderers you could loop through the list and remove them.


问:
VHDL Testbench : Output not changing
I'm currently learning about writing testbenchs for my VHDL components. I am trying to test a clock synchronizer, just made up of two cascaded D-type flip flops. I have written a testbench, supplying a clock and appropriate input signal stimuli but I see no output changing when I simulate, it just remains at "00".

I would be very grateful for any assistance!

EDIT: the dff component is a standard Quartus component, not quite sure how to get at the internal code.

Here is the component VHDL:

```<code>    library ieee;
use ieee.numeric_std.all;
use ieee.std_logic_1164.all;

--This device is to synchronize external signals that are asynchronous to the
--system by use of two cascaded D-Type flip flops, in order to avoid metastability issues.

--Set the generic term Nbits as required for the number of asynchronous inputs to
--be synchronized to the system clock OUTPUT(0) corresponds to INPUT(0), ect.

entity CLOCK_SYNCHRONIZER is

    generic(Nbits : positive := 2);

    port
    (
        --Define inputs
        SYS_CLOCK   : in std_logic;
        RESET       : in std_logic;
        INPUT       : in std_logic_vector(Nbits-1 downto 0);

        --Define output
        OUTPUT      : out std_logic_vector(Nbits-1 downto 0) := (others=>'0')
    );
end entity;

architecture v1 of CLOCK_SYNCHRONIZER is

    --Declare signal for structural VHDL component wiring
    signal A : std_logic_vector(Nbits-1 downto 0);

    --Declare D-Type Flip-Flop
    component dff
        port(D : in std_logic; CLK : in std_logic; CLRN : in std_logic; Q : out std_logic);
    end component;

begin

    --Generate and wire number of synchronizers required
    g1 : for n in Nbits-1 downto 0 generate
        c1 : dff port map(D=>input(n), CLK=>sys_clock, Q=>A(n), CLRN=>reset);
        c2 : dff port map(D=>A(n), CLK=>sys_clock, Q=>output(n), CLRN=>reset);
    end generate;

end architecture v1;
</code>```

And here is the testbench:

```<code>   library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity testbench is
end entity;

architecture v1 of testbench is

    component CLOCK_SYNCHRONIZER

        generic(Nbits : positive := 2);

        port
        (
            --Define inputs
            SYS_CLOCK   : in std_logic;
            RESET       : in std_logic;
            INPUT       : in std_logic_vector(Nbits-1 downto 0);

            --Define output
            OUTPUT      : out std_logic_vector(Nbits-1 downto 0)
        );
    end component;

    constant Bus_width      : integer := 2;
    signal SYS_CLOCK        : std_logic := '0';
    signal RESET            : std_logic := '1';
    signal INPUT        : std_logic_vector(Bus_width-1 downto 0) := (others=>'0');
    signal OUTPUT       : std_logic_vector(Bus_width-1 downto 0) := (others=>'0');

begin

    C1 : CLOCK_SYNCHRONIZER
    generic map(Nbits=>Bus_width)
    port map(SYS_CLOCK=>SYS_CLOCK, RESET=>RESET, INPUT=>INPUT, OUTPUT=>OUTPUT);

    always : process
    begin
        for i in 0 to 50 loop
            INPUT <= "11";
            wait for 24ns;
            INPUT <= "00";
            wait for 24ns;
        end loop;
    WAIT;
    end process;

    clk : process
    begin

        for i in 0 to 50 loop
            SYS_CLOCK <= '1';
            wait for 5ns;
            SYS_CLOCK <= '0';
            wait for 5ns;
        end loop;
    WAIT;
    end process;

end architecture v1;
</code>```

答:
The problem is that you have not compiled an entity to bind to the dff component. See this example on EDA Playground, where you see the following warnings:

ELAB1 WARNING ELAB1_0026: "There is no default binding for component
  "dff". (No entity named "dff" was found)." "design.vhd" 45 0 ...
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__1/c1 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__1/c2 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__0/c1 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__0/c2 : dff not bound.

Given you have no configuration, this needs to have be called dff and must have exactly the same ports as the dff component, ie:

```<code>entity dff is
        port(D : in std_logic; CLK : in std_logic; CLRN : in std_logic; Q : out std_logic);
end entity;
</code>```

(Google "VHDL default binding rules")

This needs to model the functionality of the dff flip-flop. I have assumed the following functionality:

```<code>architecture v1 of dff is
begin

  process (CLK, CLRN)
  begin
    if CLRN = '0' then
      Q <= '0';
    elsif rising_edge(CLK) then
      Q <= D;
    end if;
  end process;

end architecture v1;
</code>```

You can see this now does something more sensible on EDA Playground. (I haven't checked to see whether it is doing the right thing.)

BTW: why are you initialising this output? That seems a strange thing to do:

```<code>OUTPUT      : out std_logic_vector(Nbits-1 downto 0) := (others=>'0')
</code>```

Title: VHDL Testbench : Output not changing

Body:
I'm currently learning about writing testbenchs for my VHDL components. I am trying to test a clock synchronizer, just made up of two cascaded D-type flip flops. I have written a testbench, supplying a clock and appropriate input signal stimuli but I see no output changing when I simulate, it just remains at "00".

I would be very grateful for any assistance!

EDIT: the dff component is a standard Quartus component, not quite sure how to get at the internal code.

Here is the component VHDL:

    library ieee;
use ieee.numeric_std.all;
use ieee.std_logic_1164.all;

--This device is to synchronize external signals that are asynchronous to the
--system by use of two cascaded D-Type flip flops, in order to avoid metastability issues.

--Set the generic term Nbits as required for the number of asynchronous inputs to
--be synchronized to the system clock OUTPUT(0) corresponds to INPUT(0), ect.

entity CLOCK_SYNCHRONIZER is

    generic(Nbits : positive := 2);

    port
    (
        --Define inputs
        SYS_CLOCK   : in std_logic;
        RESET       : in std_logic;
        INPUT       : in std_logic_vector(Nbits-1 downto 0);

        --Define output
        OUTPUT      : out std_logic_vector(Nbits-1 downto 0) := (others=>'0')
    );
end entity;

architecture v1 of CLOCK_SYNCHRONIZER is

    --Declare signal for structural VHDL component wiring
    signal A : std_logic_vector(Nbits-1 downto 0);

    --Declare D-Type Flip-Flop
    component dff
        port(D : in std_logic; CLK : in std_logic; CLRN : in std_logic; Q : out std_logic);
    end component;

begin

    --Generate and wire number of synchronizers required
    g1 : for n in Nbits-1 downto 0 generate
        c1 : dff port map(D=>input(n), CLK=>sys_clock, Q=>A(n), CLRN=>reset);
        c2 : dff port map(D=>A(n), CLK=>sys_clock, Q=>output(n), CLRN=>reset);
    end generate;

end architecture v1;

And here is the testbench:

   library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity testbench is
end entity;

architecture v1 of testbench is

    component CLOCK_SYNCHRONIZER

        generic(Nbits : positive := 2);

        port
        (
            --Define inputs
            SYS_CLOCK   : in std_logic;
            RESET       : in std_logic;
            INPUT       : in std_logic_vector(Nbits-1 downto 0);

            --Define output
            OUTPUT      : out std_logic_vector(Nbits-1 downto 0)
        );
    end component;

    constant Bus_width      : integer := 2;
    signal SYS_CLOCK        : std_logic := '0';
    signal RESET            : std_logic := '1';
    signal INPUT        : std_logic_vector(Bus_width-1 downto 0) := (others=>'0');
    signal OUTPUT       : std_logic_vector(Bus_width-1 downto 0) := (others=>'0');

begin

    C1 : CLOCK_SYNCHRONIZER
    generic map(Nbits=>Bus_width)
    port map(SYS_CLOCK=>SYS_CLOCK, RESET=>RESET, INPUT=>INPUT, OUTPUT=>OUTPUT);

    always : process
    begin
        for i in 0 to 50 loop
            INPUT <= "11";
            wait for 24ns;
            INPUT <= "00";
            wait for 24ns;
        end loop;
    WAIT;
    end process;

    clk : process
    begin

        for i in 0 to 50 loop
            SYS_CLOCK <= '1';
            wait for 5ns;
            SYS_CLOCK <= '0';
            wait for 5ns;
        end loop;
    WAIT;
    end process;

end architecture v1;

Body:
The problem is that you have not compiled an entity to bind to the dff component. See this example on EDA Playground, where you see the following warnings:

ELAB1 WARNING ELAB1_0026: "There is no default binding for component
  "dff". (No entity named "dff" was found)." "design.vhd" 45 0 ...
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__1/c1 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__1/c2 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__0/c1 : dff not bound.
  ELBREAD: Warning: ELBREAD_0037 Component /testbench/C1/g1__0/c2 : dff not bound.

Given you have no configuration, this needs to have be called dff and must have exactly the same ports as the dff component, ie:

entity dff is
        port(D : in std_logic; CLK : in std_logic; CLRN : in std_logic; Q : out std_logic);
end entity;

(Google "VHDL default binding rules")

This needs to model the functionality of the dff flip-flop. I have assumed the following functionality:

architecture v1 of dff is
begin

  process (CLK, CLRN)
  begin
    if CLRN = '0' then
      Q <= '0';
    elsif rising_edge(CLK) then
      Q <= D;
    end if;
  end process;

end architecture v1;

You can see this now does something more sensible on EDA Playground. (I haven't checked to see whether it is doing the right thing.)

BTW: why are you initialising this output? That seems a strange thing to do:

OUTPUT      : out std_logic_vector(Nbits-1 downto 0) := (others=>'0')


问:
Extracting C Function's Parameters Using C++ Metaprogramming (Example from "Practical C++ Metaprogramming")
The following is an example from "Practical C++ Metaprogramming" (pages 16/17):

```<code>#include <tuple>
#include <typeinfo>

template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (Args...)>
{
   using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template<typename F>
void some_magic_function(F f)
{
   // if F is in the form void(double*, double*)
   // make_tuple_of_params is std::tuple<double*, double*>
   make_tuple_of_params_t<F> params;

   // ...
}

void Foo(double* x, double* y) { }

int main()
{
   some_magic_function(Foo);
}
</code>```

It's failing to compile:

```<code>$ clang++ -std=c++14 MakeTuple.cpp
MakeTuple.cpp:14:5: error: implicit instantiation of undefined template 'make_tuple_of_params<void (*)(double *, double*)>'
</code>```

Is this because the non specialized version of make_tuple_of_params (lines 4 and 5 of the code above) is not defined?

答:
You actually need to different overloading, depending if you extracting it from a pointer or from a signature template argument, see below.

```<code>template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (*)(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template <typename F>
bool some_magic_function(F f) {
  // if F is in the form void(double*, double*)
  // make_tuple_of_params is std::tuple<double*, double*>
  return std::is_same<std::tuple<double*, double*>, make_tuple_of_params_t<F>>::value;
}

void Foo(double* x, double* y) {}

int main() {
  cerr << some_magic_function(Foo) << endl;
  cerr
    << std::is_same<std::tuple<int, int>, make_tuple_of_params_t<void(int, int)>>::value
    << endl;
  // The latter one might be handy in some of template metaprogramming constructs
  return 0;
}
</code>```

Sorry, have not look at the book pages, so do not know what the authro meant there.

Body:
The following is an example from "Practical C++ Metaprogramming" (pages 16/17):

#include <tuple>
#include <typeinfo>

template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (Args...)>
{
   using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template<typename F>
void some_magic_function(F f)
{
   // if F is in the form void(double*, double*)
   // make_tuple_of_params is std::tuple<double*, double*>
   make_tuple_of_params_t<F> params;

   // ...
}

void Foo(double* x, double* y) { }

int main()
{
   some_magic_function(Foo);
}

It's failing to compile:

$ clang++ -std=c++14 MakeTuple.cpp
MakeTuple.cpp:14:5: error: implicit instantiation of undefined template 'make_tuple_of_params<void (*)(double *, double*)>'

Is this because the non specialized version of make_tuple_of_params (lines 4 and 5 of the code above) is not defined?

Body:
You actually need to different overloading, depending if you extracting it from a pointer or from a signature template argument, see below.

template <typename F>
struct make_tuple_of_params;

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret (*)(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename Ret, typename... Args>
struct make_tuple_of_params<Ret(Args...)> {
  using type = std::tuple<Args...>;
};

template <typename F>
using make_tuple_of_params_t = typename make_tuple_of_params<F>::type;

template <typename F>
bool some_magic_function(F f) {
  // if F is in the form void(double*, double*)
  // make_tuple_of_params is std::tuple<double*, double*>
  return std::is_same<std::tuple<double*, double*>, make_tuple_of_params_t<F>>::value;
}

void Foo(double* x, double* y) {}

int main() {
  cerr << some_magic_function(Foo) << endl;
  cerr
    << std::is_same<std::tuple<int, int>, make_tuple_of_params_t<void(int, int)>>::value
    << endl;
  // The latter one might be handy in some of template metaprogramming constructs
  return 0;
}

Sorry, have not look at the book pages, so do not know what the authro meant there.


问:
Partitioning in window functions with same value in different chunk of rows
In the picture below you can example data. I would like to get first occurence of batch_start for each batch. As you can see (green highlight) batch 1522049 occurs in 2 chunks, one has 2 rows and second has 1 row.

```<code>SELECT FIRST_VALUE(batch_start) OVER (PARTITION BY batch ORDER BY batch_start)
</code>```

does not solve the problem, since it joins both chunks into one and result is '2013-01-29 10:27:23' for both of them.

Any idea how to distinguish these rows and get batch_start of each chunk of data?

答:
Maybe: select batch, min(batch_start) firstOccurance, max(batch_start) lastOccurance from yourTable group by batch

or try (keeping your part of query):
SELECT FIRST_VALUE(a.batch_start) OVER (PARTITION BY a.batch ORDER BY a.batch_start) from yourTable a
join (select batch, min(batch_start) firstOccurance, max(batch_end) lastOccurance from yourTable group by batch) b on a.batch = b.batch

Body:
In the picture below you can example data. I would like to get first occurence of batch_start for each batch. As you can see (green highlight) batch 1522049 occurs in 2 chunks, one has 2 rows and second has 1 row.

SELECT FIRST_VALUE(batch_start) OVER (PARTITION BY batch ORDER BY batch_start)

does not solve the problem, since it joins both chunks into one and result is '2013-01-29 10:27:23' for both of them.

Any idea how to distinguish these rows and get batch_start of each chunk of data?


问:
Changing names of parameterized tests
Is there a way to set my own custom test case names when using parameterized tests in JUnit4?

I'd like to change the default — [Test class].runTest[n] — to something meaningful.

答:
Since the parameter accessed (e.g. with "{0}" always returns the toString() representation, one workaround would be to make an anonymous implementation and override toString() in each case. For example:

```<code>public static Iterable<? extends Object> data() {
    return Arrays.asList(
        new MyObject(myParams...) {public String toString(){return "my custom test name";}},
        new MyObject(myParams...) {public String toString(){return "my other custom test name";}},
        //etc...
    );
}
</code>```

OwnerDisplayName: Epaga

Title: Changing names of parameterized tests

LastEditorDisplayName: Epaga

Body:
Since the parameter accessed (e.g. with "{0}" always returns the toString() representation, one workaround would be to make an anonymous implementation and override toString() in each case. For example:

public static Iterable<? extends Object> data() {
    return Arrays.asList(
        new MyObject(myParams...) {public String toString(){return "my custom test name";}},
        new MyObject(myParams...) {public String toString(){return "my other custom test name";}},
        //etc...
    );
}


问:
Visual C++ throws map exception because of comperator
I have a C++ code that is running on Linux but I get a bug in Visual C++ on Windows. The code is the following:

```<code>struct dependence {
    dependence() {}
    dependence(string CUid, LID sink, LID source, std::string var)
    : CUid(CUid), sink(sink), source(source), var(var) {}

    string CUid;

    LID sink = 0;
    LID source = 0;
    std::string var;
};

struct dependenceCompare {
    bool operator() (const dependence& lhs, const dependence& rhs) const{
    return ((lhs.CUid<rhs.CUid) || (lhs.source<rhs.source) || (lhs.sink < rhs.sink) || (lhs.var < rhs.var));

    }
};
</code>```

When running the code on Windows I get the following error:

Debug Assertion Failed!" c:\windows\system32\MSCP120D.dll c:\Program Files\Microsoft Visual Studio 12.0\VC\include\xtree line 1795 Expression: invalid operator<
  When I change the comparator to just one if clause, it works:

```<code>struct dependenceCompare {
    bool operator() (const dependence& lhs, const dependence& rhs) const{
        return ((lhs.CUid < rhs.CUid));
    }
};
</code>```

I have read this thread, but could not find out where the problem is and why it is working in Linux with cmake but not in Visual Studio C++.

答:
Something like a.i < b.i || a.j < b.j is not a "strict weak ordering" as required by things like std::map, because it means that given two items, each one can be less than the other.

It's common to see multi-field comparisons of this form:

```<code>if(a.i != b.i) return a.i < b.i;
if(a.j != b.j) return a.j < b.j;
return a.k < b.k;
</code>```

That's probably more like what you want: Giving precedence to one field, but using another field to break ties.

You can simplify that code by using std::tie

```<code>return (std::tie(a.i, a.j, a.k) < std::tie(b.i, b.j, b.k));
</code>```

For your code, it will be:

```<code>return ( std::tie(lhs.CUid, lhs.source, lhs.sink, lhs.var)
         < std::tie(rhs.CUid, rhs.source, rhs.sink, rhs.var));
</code>```

Body:
I have a C++ code that is running on Linux but I get a bug in Visual C++ on Windows. The code is the following:

struct dependence {
    dependence() {}
    dependence(string CUid, LID sink, LID source, std::string var)
    : CUid(CUid), sink(sink), source(source), var(var) {}

    string CUid;

    LID sink = 0;
    LID source = 0;
    std::string var;
};

struct dependenceCompare {
    bool operator() (const dependence& lhs, const dependence& rhs) const{
    return ((lhs.CUid<rhs.CUid) || (lhs.source<rhs.source) || (lhs.sink < rhs.sink) || (lhs.var < rhs.var));

    }
};

When running the code on Windows I get the following error:

Debug Assertion Failed!" c:\windows\system32\MSCP120D.dll c:\Program Files\Microsoft Visual Studio 12.0\VC\include\xtree line 1795 Expression: invalid operator<
  When I change the comparator to just one if clause, it works:

struct dependenceCompare {
    bool operator() (const dependence& lhs, const dependence& rhs) const{
        return ((lhs.CUid < rhs.CUid));
    }
};

I have read this thread, but could not find out where the problem is and why it is working in Linux with cmake but not in Visual Studio C++.

Body:
Something like a.i < b.i || a.j < b.j is not a "strict weak ordering" as required by things like std::map, because it means that given two items, each one can be less than the other.

It's common to see multi-field comparisons of this form:

if(a.i != b.i) return a.i < b.i;
if(a.j != b.j) return a.j < b.j;
return a.k < b.k;

That's probably more like what you want: Giving precedence to one field, but using another field to break ties.

You can simplify that code by using std::tie

return (std::tie(a.i, a.j, a.k) < std::tie(b.i, b.j, b.k));

For your code, it will be:

return ( std::tie(lhs.CUid, lhs.source, lhs.sink, lhs.var)
         < std::tie(rhs.CUid, rhs.source, rhs.sink, rhs.var));


问:
WPF Dynamic resource reference
HI

Am load a string xaml with DynamicResource assigned to a Background property. Is there a way to get the reference of the dynamic resource.

```<code>Background="{DynamicResource Color1}"
</code>```

I want to get the resource reference assigned to a Dependency property at runtime
Pl help

答:
Where is the DependencyProperty defined? On the same Window/UserControl? If you simply want to bind to the value of a DependencyProperty you probably want to use regular {Binding ...} syntax instead.

Example 1: If you are binding to a dependency property on a particular control named myControl you can declare it like below.

```<code>Background="{Binding ElementName=myControl, Path=Color1}"
</code>```

Example 2: If you don't want to rely on naming controls because it is so pasay in WPF and you are referencing a property defined on your Window you could do something like below.

```<code>Background="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Color1}"
</code>```

Title: WPF Dynamic resource reference

Body:
HI

Am load a string xaml with DynamicResource assigned to a Background property. Is there a way to get the reference of the dynamic resource.

Background="{DynamicResource Color1}"

I want to get the resource reference assigned to a Dependency property at runtime
Pl help

Body:
Where is the DependencyProperty defined? On the same Window/UserControl? If you simply want to bind to the value of a DependencyProperty you probably want to use regular {Binding ...} syntax instead.

Example 1: If you are binding to a dependency property on a particular control named myControl you can declare it like below.

Background="{Binding ElementName=myControl, Path=Color1}"

Example 2: If you don't want to rely on naming controls because it is so pasay in WPF and you are referencing a property defined on your Window you could do something like below.

Background="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Color1}"


问:
Where is EJB method run
I'm calling an EJB method remotly using next code:

```<code>RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();
</code>```

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?

答:
AppServers use JNDi to share information of EJBs. When you deploy EJB, a CORBA compliant stub is registered with JNDI service of the AppServer. By 'CORBA compliant stub' I mean this is something beyond RMI, and is platform independent architecture. So theoretically, the client of EJB could be a COBOL or C program too!

Clients always look up the JNDi service and ask for stub of the EJB. This stub naturally has to be serializable. Suffices to say that it contains enough information so that the client can create an object which acts as a proxy to the real EJB. So at this point, situation is, EJB object is on server, and a proxy is on client. By proxy I mean, it hides network level communication details.

Client code now calls methods on proxy, and these are transparently called over CORBA protocol to the EJB object on server.

So to answer your q, EJB object is always on server. It's proxy is constructed on client using the CORBA stub registered on JNDI service. The EJB server, JNDI service, and client can be on different machines. Usually the JNDI service is a part of the AppServer where EJB is deployed. The client is usually a web application usually deployed on same AppServer as where EJB is deployed, though not necessarily. Client is also sometimes a thick client like Swing based, or C#.NET based GUI app on client desktop/laptop.

Title: Where is EJB method run

Body:
I'm calling an EJB method remotly using next code:

RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?


问:
Allow to the user select two radio buttons in a group at the same time WPF
I am doing a WPF application and I need to allow the user to select exactly two radio buttons that belong to the same group.</p>

答: Radio buttons do not work that way.  You will have to use checkboxes and using the click event make sure that they do not choose more than two.</p>


问:
How to get the internal table data in excel format if the report runs in background?
Could you please tell me the way to get internal table data in excel file to be saved in local desktop (presentation server). Remember that the report runs in background.</p>

答:
Theoretically you can do this, if you create the file on a SAP AS and move this file using any shell file move command. However, it's a bad practice to make any connection from SAP AS to a user's machine.

The best solution here is to create the file on SAP AS. The user must download the file manually from the SAP AS. You can also send this file to a user for example per e-mail. The user will do no manual work in the last case.

Also a good practice is to use PI server functionality. It can deliver your file within a way the user wants to have.


问:
The timestamp in snapshot jar's maven-metadata.xml is more than a second than the actual jar's timestamp?
I encountered a quirky problem:

I used "mvn deploy" (Maven 3.3.9, Jenkins 2.45, Nexus 2.12.0) to deploy a snapshot jar to my nexus in jenkins, result as below (suppose the jar name is userdao.jar):

```<code>Uploaded: myNexusIp/nexus/content/repositories/snapshots/xxx/1.0-SNAPSHOT/userdao-1.0-20170512.111840-6.jar
Uploaded: myNexusIp/nexus/content/repositories/snapshots/xxx/1.0-SNAPSHOT/maven-metadata.xml
</code>```

The build was successful and everything was OK.

But when I built another maven project that depended above userdao.jar, error occurred as below:

```<code>Could not find artifact userdao:jar:1.0-20170512.111840-6 in public (http://myNexusIp/nexus/content/groups/public/)
</code>```

After positioning I found that the timestamp in maven-metadata.xml in the nexus was more than a second than the actual jar's timestamp!

As below:

in maven-metadata.xml: 1.0-20170512.111840-6

actual existing snapshot jar: userdao-1.0-20170512.111839-6.jar

Because userdao-1.0-20170512.111840-6.jar did not exist in Nexus, the
right one should be userdao-1.0-20170512.111839-6.jar, so it errors.

Who can tell me why and how to resolve it?

答:
I actually found the opposite.  After upgrading from Maven 3.3.9 to 3.5.0 I could reliably deploy artifacts where by the time stamps appearing in the metadata.xml files on Nexus were incorrect compared to the actual files that were deployed.

By downgrading (back to 3.3.9) everything worked correctly.  The metadata.xml versions and timestamps matched always.

Perhaps it's something to do with the Maven 3.5.0 upgrade to remove Aether?

Body:
I encountered a quirky problem:

I used "mvn deploy" (Maven 3.3.9, Jenkins 2.45, Nexus 2.12.0) to deploy a snapshot jar to my nexus in jenkins, result as below (suppose the jar name is userdao.jar):

Uploaded: myNexusIp/nexus/content/repositories/snapshots/xxx/1.0-SNAPSHOT/userdao-1.0-20170512.111840-6.jar
Uploaded: myNexusIp/nexus/content/repositories/snapshots/xxx/1.0-SNAPSHOT/maven-metadata.xml

The build was successful and everything was OK.

But when I built another maven project that depended above userdao.jar, error occurred as below:

Could not find artifact userdao:jar:1.0-20170512.111840-6 in public (http://myNexusIp/nexus/content/groups/public/)

After positioning I found that the timestamp in maven-metadata.xml in the nexus was more than a second than the actual jar's timestamp!

As below:

in maven-metadata.xml: 1.0-20170512.111840-6

actual existing snapshot jar: userdao-1.0-20170512.111839-6.jar

Because userdao-1.0-20170512.111840-6.jar did not exist in Nexus, the
right one should be userdao-1.0-20170512.111839-6.jar, so it errors.

Who can tell me why and how to resolve it?


问:
ASP.NET MVC and text/xml content type
I want to return a View() from an action, and the resulting response should have a content type of text/xml instead of the default text/html.

I have tried the following, with no success:

```<code>Response.ContentType = "text/xml";
return View();
</code>```

I know that you can specify the content type by returning ContentResult, but that doesn't render my View.

I'm hoping I don't need to render the view to a string then use return Content(), so I'm probably overlooking some easy way.

答:
Users control (ASCX) doesn't accept ContentType="text/xml".

Solution:

```<code>public ActionResult xxx()
  {
     Response.ContentType = "text/xml";
     return View("xxx.ascx");
  }
</code>```

Title: ASP.NET MVC and text/xml content type

Body:
I want to return a View() from an action, and the resulting response should have a content type of text/xml instead of the default text/html.

I have tried the following, with no success:

Response.ContentType = "text/xml";
return View();

I know that you can specify the content type by returning ContentResult, but that doesn't render my View.

I'm hoping I don't need to render the view to a string then use return Content(), so I'm probably overlooking some easy way.

Body:
Users control (ASCX) doesn't accept ContentType="text/xml".

Solution:

public ActionResult xxx()
  {
     Response.ContentType = "text/xml";
     return View("xxx.ascx");
  }


问:
Function that checks if the list contains a given as parameter value
So basically I want to write a function which checks if the list contains a given as parameter value.

For example:

```<code>l = ['ala', 'bala', 'alabala']
</code>```

答:
Simple function:

```<code>def isIn(item, list):
   return(item in list)

l = ['ala', 'bala', 'alabala']
print(isIn('bala',l))
</code>```

As an example. Please google the answer before posting the question, or try to show what you have tried in the future.

Fastest way to check if a value exist in a list

Shows any number of ways to do this

Body:
So basically I want to write a function which checks if the list contains a given as parameter value.

For example:

l = ['ala', 'bala', 'alabala']

Body:
Simple function:

def isIn(item, list):
   return(item in list)

l = ['ala', 'bala', 'alabala']
print(isIn('bala',l))

As an example. Please google the answer before posting the question, or try to show what you have tried in the future.

Fastest way to check if a value exist in a list

Shows any number of ways to do this