问:
Is WCF ready for real world?
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

```<code>Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to
</code>```

install some extension files. so it's
  lot of work for a new product.

```<code>2. I found it very hard to configure security settings. when i
</code>```

tried to configure for the first time
  it threw all kind of errors.

```<code>3. After installing WCF in IIS, sometimes it's trowing an exception
</code>```

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

```<code>and a lot more...
</code>```

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.

答:
I have done a lot of ranting against WCF lately. It is clunky, heavy and overdone but don't get me wrong it is extremely rich and flexible.

And yes, it is real world  ready, already used in thousands of large scale projects.

I have already used it in two projects.

Now, if all you need is lightweight, little-setup HTTP calls, use JSON+HTTP which is in ASP.NET MVC or the new WCF's separate HTTP stack.

Title: Is WCF ready for real world?

Body:
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to

install some extension files. so it's
  lot of work for a new product.

2. I found it very hard to configure security settings. when i

tried to configure for the first time
  it threw all kind of errors.

3. After installing WCF in IIS, sometimes it's trowing an exception

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

and a lot more...

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.


来源: stackexchange

问:
React - setState() Does not update leaf level attributes
I am using react and basic flux to do a data entry web app.
So I have a root component which communicates with a store, gets the complex data object which is something like this.

On the change of an option select element, I fire an action which would bring another relevant object with a similar structure to above.

I manage this massive object as the root state of my data entry page and pass down data as props to various components.

The leaf level of this object, I have bound the to an Input element. So it changes when the object changes. All of these changes trickled down from the following state change at the root component.

```<code> MeasurementStore.getAllMeasurements().then((measurements) => {
        this.setState({
            measurements : measurements
        });
    });
</code>```

But in my case, the values at the leaf level do not change corresponding to the state change. But when I add the following

```<code> MeasurementStore.getAllMeasurements().then((measurements) => {
        this.setState({
            measurements : {}
        });
        this.setState({
            measurements : measurements
        });
    });
</code>```

it starts working properly and the leaf-level values change accordingly. Why does this happen?

答:
Figured it out.
I was maintaining state in a reusable "custom" input that I had written so the changes were not trickling down as expected since the child element was basing on its own state.

removed state and its "props" all the way to the end!

Lessons learnt! always try to lift your state up!

ContentLicense: CC BY-SA 3.0

Body:
I am using react and basic flux to do a data entry web app.
So I have a root component which communicates with a store, gets the complex data object which is something like this.

On the change of an option select element, I fire an action which would bring another relevant object with a similar structure to above.

I manage this massive object as the root state of my data entry page and pass down data as props to various components.

The leaf level of this object, I have bound the to an Input element. So it changes when the object changes. All of these changes trickled down from the following state change at the root component.

 MeasurementStore.getAllMeasurements().then((measurements) => {
        this.setState({
            measurements : measurements
        });
    });

But in my case, the values at the leaf level do not change corresponding to the state change. But when I add the following

 MeasurementStore.getAllMeasurements().then((measurements) => {
        this.setState({
            measurements : {}
        });
        this.setState({
            measurements : measurements
        });
    });

it starts working properly and the leaf-level values change accordingly. Why does this happen?


问:
How can I select the first specific inner element?
Here is my HTML?

```<code><ul>
    <li>
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>
</code>```

And this is my jQuery code:

```<code>$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})
</code>```

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

答:
the first specific element

What alternative should I use instead of .find() ?

```<code>$(this).find('a:first')
</code>```

seems like only logical solution and easy to read by developer

Body:
Here is my HTML?

something

            link

And this is my jQuery code:

$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

Body:
the first specific element

What alternative should I use instead of .find() ?

$(this).find('a:first')

seems like only logical solution and easy to read by developer


问:
Connecting remote database in Xamarin Forms for IOS application
I have a project has two parts.

1- Windows form or WPF application that basically connects to database and write/read/update some basic text data (this part is already done).

2- On the other hand, I am currently developing an IOS app that can connect to remote database and read/write/update data.

What is the best way to connect the same SQLite or SQL database from both Windows forms app and IOS app.

Thanks in advance

答:
The best way is creating an API/WebService which will be the interface between the database and your clients: WPF, iOS App and any other client you might want to add in the future.

Using a WebService is more secure, I guess you wouldn't want your database username and password being everywhere.

Using a WebService allows you abstract the data layer. Not using an API and using the connection to the database directly from your Apps will tightly couple your apps with the structure of your tables and any single change that happens in the database will force you to do the changes in the apps.

With WebService you decide what information will be available to the ones consuming it.

There are many others Plus on using WebServices but hope this are enough to clear your doubt.


问:
How to render edges as cylinders?
I've loaded an OBJ polyhedron and I've used EdgesGeometry() to extract its edges:

```<code>var edges = new THREE.LineSegments(new THREE.EdgesGeometry(child.geometry), new THREE.LineBasicMaterial( {color: 0x000000}) );
</code>```

But I would like to render each edge as a cylinder with configurable radius. Something like this:

答:
A customizable solutuion, which you can start from:

```<code>var edgesGeom = new THREE.EdgesGeometry(dodecahedronGeom); //EdgesGeometry is a BufferGeometry

var thickness = 0.25; // radius of a cylinder

for (var i = 0; i < edgesGeom.attributes.position.count - 1; i+=2){

  // when you know that it's BufferGeometry, you can find vertices in this way
  var startPoint = new THREE.Vector3(
    edgesGeom.attributes.position.array[i * 3 + 0],
    edgesGeom.attributes.position.array[i * 3 + 1],
    edgesGeom.attributes.position.array[i * 3 + 2]
  );
    var endPoint = new THREE.Vector3(
    edgesGeom.attributes.position.array[i * 3 + 3],
    edgesGeom.attributes.position.array[i * 3 + 4],
    edgesGeom.attributes.position.array[i * 3 + 5]
  );

  var cylLength = new THREE.Vector3().subVectors(endPoint, startPoint).length(); // find the length of a cylinder
  var cylGeom = new THREE.CylinderBufferGeometry(thickness, thickness, cylLength, 16);
  cylGeom.translate(0, cylLength / 2, 0);
  cylGeom.rotateX(Math.PI / 2);
  var cyl = new THREE.Mesh(cylGeom, new THREE.MeshLambertMaterial({color: "blue"}));
  cyl.position.copy(startPoint);
  cyl.lookAt(endPoint);  // and do the trick with orienation
  scene.add(cyl);
}
</code>```

jsfiddle example

Title: How to render edges as cylinders?

Body:
I've loaded an OBJ polyhedron and I've used EdgesGeometry() to extract its edges:

var edges = new THREE.LineSegments(new THREE.EdgesGeometry(child.geometry), new THREE.LineBasicMaterial( {color: 0x000000}) );

But I would like to render each edge as a cylinder with configurable radius. Something like this:

Body:
A customizable solutuion, which you can start from:

var edgesGeom = new THREE.EdgesGeometry(dodecahedronGeom); //EdgesGeometry is a BufferGeometry

var thickness = 0.25; // radius of a cylinder

for (var i = 0; i < edgesGeom.attributes.position.count - 1; i+=2){

  // when you know that it's BufferGeometry, you can find vertices in this way
  var startPoint = new THREE.Vector3(
    edgesGeom.attributes.position.array[i * 3 + 0],
    edgesGeom.attributes.position.array[i * 3 + 1],
    edgesGeom.attributes.position.array[i * 3 + 2]
  );
    var endPoint = new THREE.Vector3(
    edgesGeom.attributes.position.array[i * 3 + 3],
    edgesGeom.attributes.position.array[i * 3 + 4],
    edgesGeom.attributes.position.array[i * 3 + 5]
  );

  var cylLength = new THREE.Vector3().subVectors(endPoint, startPoint).length(); // find the length of a cylinder
  var cylGeom = new THREE.CylinderBufferGeometry(thickness, thickness, cylLength, 16);
  cylGeom.translate(0, cylLength / 2, 0);
  cylGeom.rotateX(Math.PI / 2);
  var cyl = new THREE.Mesh(cylGeom, new THREE.MeshLambertMaterial({color: "blue"}));
  cyl.position.copy(startPoint);
  cyl.lookAt(endPoint);  // and do the trick with orienation
  scene.add(cyl);
}

jsfiddle example


问:
Convention for specifying extensions in cabalized project
For any .hs file, you can specify the language extensions you rely on like so:

```<code>{-# LANGUAGE Foo, Bar, Baz #-}
</code>```

A cabalized project can also specify language extensions on a per-project basis in the .cabal file:

```<code>extensions: Foo, Bar, Baz
</code>```

Which of these is considered "best practice"? Should all extensions used be listed in the .cabal file, as a form of documenting which compilers your package is compatible with? Or should all extensions be noted on a per-file basis, for the sake of making clear which files depend on which extensions? What about extensively documenting in both places? Or is best practice somewhere in-between?

答: Ok, both question and answer are very old. So I put some update on the state of extension'ness. If you using some harmless language extensions (like -XRecordWildCards, -XDeriveDataTypeable, -XTypeVariables) in a lot of modules or find it annoying to put {-# LANGUAGE ... #-} pragma at the top of level (because you may not be aware of some IDE's or tools that allow you to put language pragmas automatically) then you should use default-extensions: field. Notice, there's also other-extensions: field which is very confusing in my opinion and should never be used. See examples here.

Body:
For any .hs file, you can specify the language extensions you rely on like so:

{-# LANGUAGE Foo, Bar, Baz #-}

A cabalized project can also specify language extensions on a per-project basis in the .cabal file:

extensions: Foo, Bar, Baz

Which of these is considered "best practice"? Should all extensions used be listed in the .cabal file, as a form of documenting which compilers your package is compatible with? Or should all extensions be noted on a per-file basis, for the sake of making clear which files depend on which extensions? What about extensively documenting in both places? Or is best practice somewhere in-between?


问:
D3 small circle located on edge of radius of larger circle
I am working on a d3 visual with two circles where the smaller circle is placed on the edge of the radius of the larger circle.  A codepen of this is located here https://codepen.io/ajblack/pen/KqKpde.  I have a 200 pixel square SVG that I am placing these circles in, and then I have two values, uAssets and uAssetsCom that are dictating the sizes of the circles.  I create a ratio to ensure that the larger circle fits in the 200 pixel square using this code:

```<code>var ratioToFit = (200/uAssets)/2;
</code>```

Then I use cosine to calculate the distance between the outer radius of the large circle and the outer bound of the SVG container at a 45 degree angle:

```<code>var key = 100*((1-Math.cos(45*Math.PI/180))/Math.cos(45*Math.PI/180))
</code>```

To place the smaller circle I calculate cx and cy attributes as the radius of the inner circle plus this 'key'.

```<code>d3.select("#uAssetComCircle")
  .attr("cx", function(d){return (d.radius+key);})
  .attr("cy", function(d){return (d.radius+key);})
</code>```

This places the inner circle close to the radius of the larger circle but it's about 2 pixels off.  I can offset this with a hardcoded 2 pixel addition to cx and cy but I feel like I shouldn't have to.

Is my math off?

答:
Not sure I completely follow your calculations, but here's a quick refactor that introduces a few things:

A translation to base all the drawing from the center point of the SVG

A d3 scale that handles calculating from user coordinates to pixel coordinates.

<!DOCTYPE html>

  <link rel="stylesheet" href="style.css" />

```

Body:
I am working on a d3 visual with two circles where the smaller circle is placed on the edge of the radius of the larger circle.  A codepen of this is located here https://codepen.io/ajblack/pen/KqKpde.  I have a 200 pixel square SVG that I am placing these circles in, and then I have two values, uAssets and uAssetsCom that are dictating the sizes of the circles.  I create a ratio to ensure that the larger circle fits in the 200 pixel square using this code:

var ratioToFit = (200/uAssets)/2;

Then I use cosine to calculate the distance between the outer radius of the large circle and the outer bound of the SVG container at a 45 degree angle:

var key = 100*((1-Math.cos(45*Math.PI/180))/Math.cos(45*Math.PI/180))

To place the smaller circle I calculate cx and cy attributes as the radius of the inner circle plus this 'key'.

d3.select("#uAssetComCircle")
  .attr("cx", function(d){return (d.radius+key);})
  .attr("cy", function(d){return (d.radius+key);})

This places the inner circle close to the radius of the larger circle but it's about 2 pixels off.  I can offset this with a hardcoded 2 pixel addition to cx and cy but I feel like I shouldn't have to.

Is my math off?

Body:
Not sure I completely follow your calculations, but here's a quick refactor that introduces a few things:

A translation to base all the drawing from the center point of the SVG

A d3 scale that handles calculating from user coordinates to pixel coordinates.

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <script>
    var uAssets = 17;
    var uAssetsCom = 3;

    var svgContainer = d3.select("body").append("svg")
      .attr("width", 200)
      .attr("height", 200)
      .attr('id', 'circleContainer')
      .append("g")
      .attr("transform", "translate(" + 100 + "," + 100 + ")")

    var scale = d3.scaleLinear()
      .domain([0,uAssets])
      .range([0,100]);

    var jsonCircles = [{
      "radius": uAssets,
      "color": "green",
      "id": "uAssetCircle"
    }, {
      "radius": uAssetsCom,
      "color": "purple",
      "id": "uAssetComCircle"
    }];

    var circles = svgContainer.selectAll("circle")
      .data(jsonCircles)
      .enter()
      .append("circle");

    var circleAttributes = circles
      .attr("r", function(d) {
        return scale(d.radius);
      })
      .attr("id", function(d) {
        return d.id
      })
      .style("fill", function(d) {
        return d.color;
      });

    d3.select("#uAssetComCircle")
      .attr("cx", function(d) {
        return scale(uAssets) * Math.cos(45 * (Math.PI / 180));
      })
      .attr("cy", function(d) {
        return scale(uAssets) * Math.sin(45 * (Math.PI / 180));
      })
  </script>
</body>

</html>


答:
Method 1: Using Jquery's children and first

$('#myList').on('click', function() {
  var link = $('#myList').children('a').first();
  console.log(link.attr('href'));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">

      <div>something</div>
      <span>link</span>

  </li>
</ul></code>```

Method 2: Using the immediate children selector >

$('#myList').on('click', function() {
  var link = $('li > a:first');
  console.log(link.attr("href"));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">

      <div>something</div>
      <span>link</span>

  </li>
</ul></code>```

Title: How can I select the first specific inner element?

Body:
Method 1: Using Jquery's children and first

$('#myList').on('click', function() {
  var link = $('#myList').children('a').first();
  console.log(link.attr('href'));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">
    <a href="./link1">
      <div>something</div>
      <span><a href="./link2">link</a></span>
    </a>
  </li>
</ul>

Method 2: Using the immediate children selector >

$('#myList').on('click', function() {
  var link = $('li > a:first');
  console.log(link.attr("href"));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">
    <a href="./link1">
      <div>something</div>
      <span><a href="./link2">link</a></span>
    </a>
  </li>
</ul>


问:
Why are props getting from Redux not defined
I use the starter template from mern.io.
When I try to run the following code I get the error: "ReferenceError: props is not defined"

EventDetailPage.js :

```<code>import React, {PropTypes} from 'react';
import {connect} from 'react-redux';

// Import Actions
import {fetchEvent} from '../../EventActions';

// Import Selectors
import {getEvent} from '../../EventReducer';

function EventDetailPage(props) {
  return (
    <div>
      <h3>{props.event.name}</h3>
    </div>
  // null
  );
}

// Actions required to provide data for this component to render in server side.
EventDetailPage.need = [params => {
    return fetchEvent(params.id);
  }
];

// Retrieve data from store as props
function mapStateToProps(state, props) {
  return {
    event: getEvent(state, props.params.id)
  };
}

export default connect(mapStateToProps)(EventDetailPage);
</code>```

fetchEvent (The API call is working) :

```<code>export function fetchEvent(id) {
  return (dispatch) => {
    return callApi(`events/${id}`).then(res => dispatch(addEvent(res.event)));
  };
}
</code>```

getEvent :

```<code>export const getEvent = (state, id) => state.events.data.filter(event => event.id === id)[0];
</code>```

routes.js :

```<code><Route
  path="/events/:name-:id"
  getComponent={(nextState, cb) => {
    require.ensure([], require => {
      cb(null, require('./modules/Event/pages/EventDetailPage/EventDetailPage').default);
    });
  }}
/>
</code>```

答:
Here is how debugging works:

There are two places where you use the variable props:

```<code>      <h3>{props.event.name}</h3>
</code>```

, which suggests that you should test to call EventDetailPage(...) independently (unit test) to check that this function works well, and

```<code>function mapStateToProps(state, props) {
  return {
    event: getEvent(state, props.params.id)
</code>```

, which if it does not work would mean that Redux API is broken - it isn't -, but to make sure you can try to console.log(props) before returning.

From the code I can read, I think it fails somewhere that is not copied in your snippets, but since you don't provide the complete traceback (at least file and line number), it is quite difficult to know.

Body:
I use the starter template from mern.io.
When I try to run the following code I get the error: "ReferenceError: props is not defined"

EventDetailPage.js :

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';

// Import Actions
import {fetchEvent} from '../../EventActions';

// Import Selectors
import {getEvent} from '../../EventReducer';

function EventDetailPage(props) {
  return (

{props.event.name}

  // null
  );
}

// Actions required to provide data for this component to render in server side.
EventDetailPage.need = [params => {
    return fetchEvent(params.id);
  }
];

// Retrieve data from store as props
function mapStateToProps(state, props) {
  return {
    event: getEvent(state, props.params.id)
  };
}

export default connect(mapStateToProps)(EventDetailPage);

fetchEvent (The API call is working) :

export function fetchEvent(id) {
  return (dispatch) => {
    return callApi(`events/${id}`).then(res => dispatch(addEvent(res.event)));
  };
}

getEvent :

export const getEvent = (state, id) => state.events.data.filter(event => event.id === id)[0];

routes.js :

<Route
  path="/events/:name-:id"
  getComponent={(nextState, cb) => {
    require.ensure([], require => {
      cb(null, require('./modules/Event/pages/EventDetailPage/EventDetailPage').default);
    });
  }}
/>

Body:
Here is how debugging works:

There are two places where you use the variable props:

      <h3>{props.event.name}</h3>

, which suggests that you should test to call EventDetailPage(...) independently (unit test) to check that this function works well, and

function mapStateToProps(state, props) {
  return {
    event: getEvent(state, props.params.id)

, which if it does not work would mean that Redux API is broken - it isn't -, but to make sure you can try to console.log(props) before returning.

From the code I can read, I think it fails somewhere that is not copied in your snippets, but since you don't provide the complete traceback (at least file and line number), it is quite difficult to know.


问:
Prolog. Reverse nodes in a tree
I want to reverse the nodes in a binary tree like this :

[[ [ [[],1,[]], 5, []],
   7,
   [ [], 3, [[],4,[]]]],
 6,
 [ [ [], 10, []],
   8,
   [ [[],9,[]], 11, [[],2,[]]]]]
```

<p><img src="https://i.stack.imgur.com/cajcV.png" alt="enter image description here"></p>

<p>I can only use this ABN representation as lists and the following constructors and selectors of the abstract data type.</p>

<pre class="lang-erlang prettyprint-override"><code>empty([]).
root([_,N,_], N).
hi([HI,_,_],HI).     %left son
hd([_,_,HD],HD).     %right son
maketree(R,HI,HD,[HI,R,HD]).
</code>```

I want to know how could I make a swap predicate like this swap(A4,B). that working like this:

?- swap(A4,B).
B=[[[[[],2,[]],11,[[],9,[]]],8,[[],10,[]]],6,[[[[],4,[]],3,[]],7,[[],5,[[],1,[]]]]]
```

Thanks !

答:
For an abstract data type, you can treat your interface predicates as opaque:

% empty([]).
% root(Tree, Root).
left_child(Tree,Left):- hi(Tree,Left).
right_child(Tree,Right):- hd(Tree,Right).
mktree(Top,Left,Right,Tree):- maketree(Top,Left,Right,Tree).
```

<p>To swap two nodes in a tree, just</p>

<pre class="lang-erlang prettyprint-override"><code>swapped_tree(Tree, SwappedTree):-
    left_child(Tree, Left ),
    right_child(Tree, Right ),
    root(Tree, Root ),
    % and then combine them in a simple way,
    mktree( ..., ..., ..., SwappedTree).
</code>```

It is in Prolog just like it is in English.

But the nodes there stayed the same. To have the new tree to be the full mirror of the original, you'll want to treat the child nodes too in the same way as you do the whole tree, before creating the new, mirrored tree:

mirrored_tree(Tree, MirroredTree) :-
    .... ,
    .... ,
    .... ,
    mirrored_tree( ..., ... ),
    mirrored_tree( ..., ... ),
    .... .
```

Using the predicate you are still writing (as if it were already written) to solve sub-parts of the full problem which are of the same nature as the full problem, and recombining the results in some simple way to get the solution of the full problem, is the essence of recursion.

Title: Prolog. Reverse nodes in a tree

Body:
I want to reverse the nodes in a binary tree like this :

[[ [ [[],1,[]], 5, []],
   7,
   [ [], 3, [[],4,[]]]],
 6,
 [ [ [], 10, []],
   8,
   [ [[],9,[]], 11, [[],2,[]]]]]

I can only use this ABN representation as lists and the following constructors and selectors of the abstract data type.

empty([]).
root([_,N,_], N).
hi([HI,_,_],HI).     %left son
hd([_,_,HD],HD).     %right son
maketree(R,HI,HD,[HI,R,HD]).

I want to know how could I make a swap predicate like this swap(A4,B). that working like this:

?- swap(A4,B).
B=[[[[[],2,[]],11,[[],9,[]]],8,[[],10,[]]],6,[[[[],4,[]],3,[]],7,[[],5,[[],1,[]]]]]

Thanks !

Body:
For an abstract data type, you can treat your interface predicates as opaque:

% empty([]).
% root(Tree, Root).
left_child(Tree,Left):- hi(Tree,Left).
right_child(Tree,Right):- hd(Tree,Right).
mktree(Top,Left,Right,Tree):- maketree(Top,Left,Right,Tree).

To swap two nodes in a tree, just

swapped_tree(Tree, SwappedTree):-
    left_child(Tree, Left ),
    right_child(Tree, Right ),
    root(Tree, Root ),
    % and then combine them in a simple way,
    mktree( ..., ..., ..., SwappedTree).

It is in Prolog just like it is in English.

But the nodes there stayed the same. To have the new tree to be the full mirror of the original, you'll want to treat the child nodes too in the same way as you do the whole tree, before creating the new, mirrored tree:

mirrored_tree(Tree, MirroredTree) :-
    .... ,
    .... ,
    .... ,
    mirrored_tree( ..., ... ),
    mirrored_tree( ..., ... ),
    .... .

Using the predicate you are still writing (as if it were already written) to solve sub-parts of the full problem which are of the same nature as the full problem, and recombining the results in some simple way to get the solution of the full problem, is the essence of recursion.


答:
I skipped wcf.

The main reason is that it causes a LOT of extra code/work and very little benefit over existing mechanisms.

I used to go the asmx route, but I've found those are even too heavy for what we normally need.  Also I found that, at least a few years ago, a lot of the java frameworks for dealing with "web services" didn't play nice with some of the advanced things we needed.

Quite frankly doing regular httpwebrequests with posts/gets to an ashx file is dead simple, robust and dynamic.  Whereas you will spend a lot of time getting wcf working.

Of course, the only time I ever click the "designer" tab in visual studio is by accident.  Maybe I'm a hedonist...or just jaded from all the marketing speak around how these technologies make our apps more "interoperable".

ContentLicense: CC BY-SA 2.5

Title: Is WCF ready for real world?


问:
Get jenkins.BadHTTPException when try to get version info from jenkins run on docker
I installed docker container for Jenkins ver. 2.19.1.

```<code>docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                              NAMES
f03c10935bb3        jenkins             "/bin/tini -- /usr/lo"   29 hours ago        Up 3 hours          0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   cocky_colden
</code>```

Installed python-jenkins module to access jenkins server.

I tried first code sample given in docs.

```<code>import jenkins

server = jenkins.Jenkins('http://localhost:8080', username='admin', password='mytoken')
user = server.get_whoami()
version = server.get_version()
print('Hello %s from Jenkins %s' % (user['fullName'], version))
</code>```

But it gives error.

```<code>python /tmp/test.py
Traceback (most recent call last):
  File "/tmp/test.py", line 5, in <module>
    version = server.get_version()
  File "/usr/lib/python2.7/site-packages/jenkins/__init__.py", line 616, in get_version
    % self.server)
jenkins.BadHTTPException: Error communicating with server[http://localhost:8080/]
</code>```

I check the docs which mentioned:

From Jenkins vesion 1.426 onward you can specify an API token instead of your real password while authenticating the user against the Jenkins instance.

I used password instead of token but get same error.

I tried curl

```<code>curl -X POST http://localhost:8080/job/testjob/build \
> --data token=mytoken \
> --data-urlencode json='{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}'
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 403 No valid crumb was included in the request</title>
</head>
<body><h2>HTTP ERROR 403</h2>
<p>Problem accessing /job/testjob/build. Reason:
```    No valid crumb was included in the request```</p><hr><i><small>Powered by Jetty://</small></i><hr/>

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

I get token from Name-> Configure -> Show API Token...

Is there anything else I have to enable from jenkins side to access? means, API will get access to this server?

答:
There appears to be a minor bug in the get_version() function.

If the Jenkins server is setup with security enabled and IF the anonymous user doesn't have the 'Overall Read' rights then you need to pass the authorization key to urlopen()

i.e. in the file 'jenkins/__init__.py', the get_version() function needs to be changed from:

```<code>def get_version(self):
    try:
        request = Request(self._build_url(''))
        request.add_header('X-Jenkins', '0.0')
        response = urlopen(request, timeout=self.timeout)
</code>```

To:

```<code>def get_version(self):
    try:
        request = Request(self._build_url(''))
        if self.auth:
            request.add_header('Authorization', self.auth)
        request.add_header('X-Jenkins', '0.0')
        response = urlopen(request, timeout=self.timeout)
</code>```

To find where this module is on your system, run python and enter:

```<code>import jenkins
jenkins.__file__
</code>```

(I have reported the bug to the module authors)

Body:
I installed docker container for Jenkins ver. 2.19.1.

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                              NAMES
f03c10935bb3        jenkins             "/bin/tini -- /usr/lo"   29 hours ago        Up 3 hours          0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   cocky_colden

Installed python-jenkins module to access jenkins server.

I tried first code sample given in docs.

import jenkins

server = jenkins.Jenkins('http://localhost:8080', username='admin', password='mytoken')
user = server.get_whoami()
version = server.get_version()
print('Hello %s from Jenkins %s' % (user['fullName'], version))

But it gives error.

python /tmp/test.py
Traceback (most recent call last):
  File "/tmp/test.py", line 5, in <module>
    version = server.get_version()
  File "/usr/lib/python2.7/site-packages/jenkins/__init__.py", line 616, in get_version
    % self.server)
jenkins.BadHTTPException: Error communicating with server[http://localhost:8080/]

I check the docs which mentioned:

From Jenkins vesion 1.426 onward you can specify an API token instead of your real password while authenticating the user against the Jenkins instance.

I used password instead of token but get same error.

I tried curl

curl -X POST http://localhost:8080/job/testjob/build \
> --data token=mytoken \
> --data-urlencode json='{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}'

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 403 No valid crumb was included in the request</title>

HTTP ERROR 403

Problem accessing /job/testjob/build. Reason:

    No valid crumb was included in the request

Powered by Jetty://

I get token from Name-> Configure -> Show API Token...

Is there anything else I have to enable from jenkins side to access? means, API will get access to this server?

Body:
There appears to be a minor bug in the get_version() function.

If the Jenkins server is setup with security enabled and IF the anonymous user doesn't have the 'Overall Read' rights then you need to pass the authorization key to urlopen()

i.e. in the file 'jenkins/__init__.py', the get_version() function needs to be changed from:

def get_version(self):
    try:
        request = Request(self._build_url(''))
        request.add_header('X-Jenkins', '0.0')
        response = urlopen(request, timeout=self.timeout)

To:

def get_version(self):
    try:
        request = Request(self._build_url(''))
        if self.auth:
            request.add_header('Authorization', self.auth)
        request.add_header('X-Jenkins', '0.0')
        response = urlopen(request, timeout=self.timeout)

To find where this module is on your system, run python and enter:

import jenkins
jenkins.__file__

(I have reported the bug to the module authors)


问:
How to mapping from monoalphabetic cipher in java?

Encryption type being implemented: monoalphabetic cipher

For example,

step 1. -
step 2. -
step 3. -

result : -

I want to encrypt the plaintext as above.
How do you approach it?

答:
Try this plainText.charAt(i) - 'a' as the index of cipher

Example :

```<code>char[] cipher = "dstuvwxuzabcdefghiklmnopqr".toCharArray();

String plainText = "iloveyouz";

StringBuilder cipherText = new StringBuilder();
for (int i = 0; i < plainText.length(); i++) {
    cipherText.append(cipher[plainText.charAt(i) - 'a']);
}

System.out.println("Encrypted : " + cipherText.toString());

char[] original = new char[cipher.length];
for (int j = 0; j < original.length; j++) {
    original[cipher[j] - 'a'] = (char) ('a' + j);
}

StringBuilder decryption = new StringBuilder();

for (int i = 0; i < plainText.length(); i++) {
    decryption.append(original[cipherText.charAt(i) - 'a']);
}

System.out.println("Decrypted : " + decryption.toString());
</code>```

Output :

```<code>Encrypted : zcfnvqfmr
Decrypted : iloveyouz
</code>```

Note : You can preprocess the original generation process.

Body:
Try this plainText.charAt(i) - 'a' as the index of cipher

Example :

char[] cipher = "dstuvwxuzabcdefghiklmnopqr".toCharArray();

String plainText = "iloveyouz";

StringBuilder cipherText = new StringBuilder();
for (int i = 0; i < plainText.length(); i++) {
    cipherText.append(cipher[plainText.charAt(i) - 'a']);
}

System.out.println("Encrypted : " + cipherText.toString());

char[] original = new char[cipher.length];
for (int j = 0; j < original.length; j++) {
    original[cipher[j] - 'a'] = (char) ('a' + j);
}

StringBuilder decryption = new StringBuilder();

for (int i = 0; i < plainText.length(); i++) {
    decryption.append(original[cipherText.charAt(i) - 'a']);
}

System.out.println("Decrypted : " + decryption.toString());

Output :

Encrypted : zcfnvqfmr
Decrypted : iloveyouz

Note : You can preprocess the original generation process.


问:
boost logger doesn't rotate at midnight
```<code>logging::wsettings settings;
settings["Core"]["Filter"] = L"%Severity% >= " + level;
settings["Core"]["DisableLogging"] = false;
settings["Sinks.File"]["Destination"] = L"TextFile";
settings["Sinks.File"]["FileName"] = fileName;
settings["Sinks.File"]["Format"] = L"%TimeStamp% %Severity(format=\"%-7s\")% - %Message%";
settings["Sinks.File"]["AutoFlush"] = true;
settings["Sinks.File"]["TimeBasedRotation"] = L"00:00:00";
settings["Sinks.File"]["RotationSize"] = 10 * 1024 * 1024;
settings["Sinks.File"]["Target"] = filePath;
settings["Sinks.File"]["ScanForFiles"] = L"All";
settings["Sinks.File"]["Append"] = true;

auto previousLocale = std::locale::global(boost::locale::generator()(Constants::LOCALE));
logging::init_from_settings(settings);
logging::add_common_attributes();
</code>```

I can see logs on different days in same log file 'App_2017-05-31.0.log'

2017-05-31 20:07:29.115231 info    -
2017-05-31 20:07:29.115231 info    -
2017-06-01 01:38:45.139742 error   -
2017-06-01 03:01:42.303604 error   -
2017-06-01 19:56:59.995196 info    -
2017-06-01 19:57:00.385923 info    -
2017-06-02 01:37:05.281702 error   -
2017-06-02 02:52:08.488442 error   -
```

Do you know how to config logger properly, so it can rotate log files at midnight, and won't have logs on different days in same log file.

答: There is no TimeBasedRotation parameter. You can set either periodic rotation by setting RotationInterval to the number of seconds between rotations, or RotationTimePoint to the time point at which the rotation happens. The parameters are documented here.

Title: boost logger doesn't rotate at midnight

Body:
logging::wsettings settings;
settings["Core"]["Filter"] = L"%Severity% >= " + level;
settings["Core"]["DisableLogging"] = false;
settings["Sinks.File"]["Destination"] = L"TextFile";
settings["Sinks.File"]["FileName"] = fileName;
settings["Sinks.File"]["Format"] = L"%TimeStamp% %Severity(format=\"%-7s\")% - %Message%";
settings["Sinks.File"]["AutoFlush"] = true;
settings["Sinks.File"]["TimeBasedRotation"] = L"00:00:00";
settings["Sinks.File"]["RotationSize"] = 10 * 1024 * 1024;
settings["Sinks.File"]["Target"] = filePath;
settings["Sinks.File"]["ScanForFiles"] = L"All";
settings["Sinks.File"]["Append"] = true;

auto previousLocale = std::locale::global(boost::locale::generator()(Constants::LOCALE));
logging::init_from_settings(settings);
logging::add_common_attributes();

I can see logs on different days in same log file 'App_2017-05-31.0.log'

2017-05-31 20:07:29.115231 info    -
2017-05-31 20:07:29.115231 info    -
2017-06-01 01:38:45.139742 error   -
2017-06-01 03:01:42.303604 error   -
2017-06-01 19:56:59.995196 info    -
2017-06-01 19:57:00.385923 info    -
2017-06-02 01:37:05.281702 error   -
2017-06-02 02:52:08.488442 error   -

Do you know how to config logger properly, so it can rotate log files at midnight, and won't have logs on different days in same log file.


问:
Install laravel on xampp in arch linux
I have installed xampp in arch linux and also the composer using the command given below:

```<code>curl -sS https://getcomposer.org/installer |
sudo php -- --install-dir=/usr/local/bin --filename=composer
</code>```

I have also installed laravel using the following commands.

```<code>composer global require "laravel/installer=~1.1"
export PATH="~/.composer/vendor/bin:$PATH"
</code>```

But still, when I type laravel ne <project> I get the error

```<code>bash:laravel is not a command
</code>```

How can I check it is properly installed?

答:
Modify you shell script

```<code>sudo nano ~/.bashrc
</code>```

And add  this

```<code>export PATH="$PATH:~/.composer/vendor/bin"
</code>```

or this

```<code>export PATH="~/.config/composer/vendor/bin:$PATH"
</code>```

Title: Install laravel on xampp in arch linux

Body:
I have installed xampp in arch linux and also the composer using the command given below:

curl -sS https://getcomposer.org/installer |
sudo php -- --install-dir=/usr/local/bin --filename=composer

I have also installed laravel using the following commands.

composer global require "laravel/installer=~1.1"
export PATH="~/.composer/vendor/bin:$PATH"

But still, when I type laravel ne <project> I get the error

bash:laravel is not a command

How can I check it is properly installed?

Body:
Modify you shell script

sudo nano ~/.bashrc

And add  this

export PATH="$PATH:~/.composer/vendor/bin"

or this

export PATH="~/.config/composer/vendor/bin:$PATH"


问:
Sonarqube not starting as an windows service
I am trying to launch sonarqube as an windows service.

Steps that i followed.

1-InstalINTService.bat started

2-went into sonarqube properties-logon tab-

Entered network service in object name

When i try to start sonarqube as a service .I get the following error

My Sonar log

```<code>2015.02.27 13:58:50 INFO  app[o.s.p.m.Monitor] Process[web] is up
2015.02.27 14:05:57 INFO  app[o.s.p.m.TerminatorThread] Process[search] is stopping
</code>```

I could not see my Login Here .How can i add my login name here.

答: It might not recognizing the local system user. That's why we should try with some other options available on desk. In log on tab choose "Local Service" instead of "Network Service". It worked for me. </p>

Body:
I am trying to launch sonarqube as an windows service.

Steps that i followed.

1-InstalINTService.bat started

2-went into sonarqube properties-logon tab-

Entered network service in object name

When i try to start sonarqube as a service .I get the following error

My Sonar log

2015.02.27 13:58:50 INFO  app[o.s.p.m.Monitor] Process[web] is up
2015.02.27 14:05:57 INFO  app[o.s.p.m.TerminatorThread] Process[search] is stopping

I could not see my Login Here .How can i add my login name here.


问:
Can reverse proxy in Service Fabric be used with multiple windows containers?
I'm evaluating using SF or docker swarm for container orchestration and I can see service fabric has an edge by being able to use reverse proxy implementation which runs on all nodes in cluster. Problem is that I can see that based on cluster manifest only one port can be used as reverse proxy port and hence I'm not fully understanding how this can be utilized if you have multiple windows containers running with each of those running on their own port. I need to use port:port mapping only (with no HTTP rewrite), so ultimately wanted one to one reverse port mapping to each individual windows container running.
Is it possible to accomplish by using service fabric?

To be clear I have www.app1.com and www.app2.com hosted in 2 different containers, they don't need to talk to each other. I deploy those to service fabric, how do I use reverse proxy with single published external port to reach those containers externally?

答:
Yes you can use Reverse proxy with multiple containers. The idea is simple

Configure port to host mapping so your host knows which port your
application is listening

Configure container to container so your
container register a end point with service fabric. You can choose
the port for this endpoint. This will be registered with Naming
service and available for reverse proxy

Communication between containers can be done using reverse proxy using the service name and the port you specified. if you didn't specified the port number then service fabric will assign one for you and you can get it using environment variable.

Service Fabric team have excellent documentation about this here
https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-deploy-container-linux


问:
Javascript: auto-download file when link "clicked"
I found a similar question, posted in an older topic, but the answer given there did not work.  I am testing with Mozilla Firefox browser (latest version).

I have an array with imageLinks, and want to auto-trigger a download without user interaction. my code is given below:

```<code>for (var i=0; i<imageLinks.length; i++) {

if (imageLinks[i]) {

    console.log(imageLinks[i]);
    var link = document.createElement('a');
    link.href = imageLinks[i];
    link.download = 'imagefile';
    link.click();
    }
}
</code>```

However, in Forefox the images are opening in new tabs?

答:
I stumbled upon this snippet on a forum, and it seems to do the trick.  Note however that the browser will still ask the user whether s/he wants the file(s) to be saved, and where.  This query can be accepted as "automatically do this with files of this type", and from then onwards the downloads will be automatically saved to the local drive.

```<code>function simulateClick() {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    var a = document.getElementById('myLink');
    a.dispatchEvent(evt);
  }
</code>```

This function can be called on the array with image links, and the user selected images can be saved to the drive.  I am happy with this solution, since it's easier to implement than a ZIP-file with user selected images. The image galleries are small, so the downloads should be initialized rather quick.

Body:
I found a similar question, posted in an older topic, but the answer given there did not work.  I am testing with Mozilla Firefox browser (latest version).

I have an array with imageLinks, and want to auto-trigger a download without user interaction. my code is given below:

for (var i=0; i<imageLinks.length; i++) {

if (imageLinks[i]) {

    console.log(imageLinks[i]);
    var link = document.createElement('a');
    link.href = imageLinks[i];
    link.download = 'imagefile';
    link.click();
    }
}

However, in Forefox the images are opening in new tabs?

Body:
I stumbled upon this snippet on a forum, and it seems to do the trick.  Note however that the browser will still ask the user whether s/he wants the file(s) to be saved, and where.  This query can be accepted as "automatically do this with files of this type", and from then onwards the downloads will be automatically saved to the local drive.

function simulateClick() {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    var a = document.getElementById('myLink');
    a.dispatchEvent(evt);
  }

This function can be called on the array with image links, and the user selected images can be saved to the drive.  I am happy with this solution, since it's easier to implement than a ZIP-file with user selected images. The image galleries are small, so the downloads should be initialized rather quick.


问:
How to make C# recognize custom attributes in external .dll?
The code below successfully recognizes internal classes which are decorated with my custom "Module" attribute, I load the assembly like this:

```<code>Assembly assembly = Assembly.GetExecutingAssembly();
</code>```

However, when I load in an external module and look through its classes, it finds the classes in the external assembly but does not recognize the custom attributes:

```<code>Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
</code>```

What do I have to specify so that C# recognizes custom attributes in external .dlls the same as it does with the internal classes?

Here is the code that successfully runs through and recognizes internal classes decorated with my "Module" attribute:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace DynamicAssembly2
{
    class Program
    {
        static void Main(string[] args)
        {
            var modules = from t in GetModules()
                           select t;
            foreach (var module in modules)
            {
                ModuleAttribute[] moduleAttributes = GetModuleAttributes(module);
                Console.WriteLine(module.FullName);
                foreach (var moduleAttribute in moduleAttributes)
                {
                    Console.WriteLine(moduleAttribute.Description);
                }
            }
            Console.ReadLine();
        }

        public static IEnumerable<Type> GetModules()
        {
            //Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
            Assembly assembly = Assembly.GetExecutingAssembly();

            return GetAssemblyClasses(assembly)
                .Where((Type type) => {return IsAModule(type);});
        }

        public static IEnumerable<Type> GetAssemblyClasses(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                Console.WriteLine(type.FullName);
                yield return type;
            }
        }

        public static bool IsAModule(Type type)
        {
            return GetModuleAttribute(type) != null;
        }

        public static ModuleAttribute GetModuleAttribute(Type type)
        {
            ModuleAttribute[] moduleAttributes = GetModuleAttributes(type);
            Console.WriteLine(moduleAttributes.Length);
            if (moduleAttributes != null && moduleAttributes.Length != 0)
                return moduleAttributes[0];
            return null;
        }

        public static ModuleAttribute[] GetModuleAttributes(Type type)
        {
            return (ModuleAttribute[])type.GetCustomAttributes(typeof(ModuleAttribute), true);
        }

    }
}
</code>```

Here is my custom Mdoule attribute:

```<code>using System;

namespace DynamicAssembly2
{
    [AttributeUsage(AttributeTargets.Class)]
    public class ModuleAttribute : Attribute
    {
        public string Description { get; set; }
    }
}
</code>```

Here is a custom module:

```<code>namespace DynamicAssembly2
{
    [Module(Description="This is the main customer class.")]
    class Customers
    {
    }
}
</code>```

答:
I had the same problem.  If the attribute was defined in an internal *cs, I could get the attribute, but if it was defined in an external dll, I would just get null when I queried for it (no error), but no linker error either.

Apparently a custom Attribute defined in an DLL and the same custom Attribute defined in local code (*cs) will happily compile into one application without any warnings about multiple definitions (the name spaces are identical).  I got rid of the local code (*cs), and fixed the references and it worked.

OwnerDisplayName: Edward Tanguay

Body:
The code below successfully recognizes internal classes which are decorated with my custom "Module" attribute, I load the assembly like this:

Assembly assembly = Assembly.GetExecutingAssembly();

However, when I load in an external module and look through its classes, it finds the classes in the external assembly but does not recognize the custom attributes:

Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");

What do I have to specify so that C# recognizes custom attributes in external .dlls the same as it does with the internal classes?

Here is the code that successfully runs through and recognizes internal classes decorated with my "Module" attribute:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace DynamicAssembly2
{
    class Program
    {
        static void Main(string[] args)
        {
            var modules = from t in GetModules()
                           select t;
            foreach (var module in modules)
            {
                ModuleAttribute[] moduleAttributes = GetModuleAttributes(module);
                Console.WriteLine(module.FullName);
                foreach (var moduleAttribute in moduleAttributes)
                {
                    Console.WriteLine(moduleAttribute.Description);
                }
            }
            Console.ReadLine();
        }

        public static IEnumerable<Type> GetModules()
        {
            //Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
            Assembly assembly = Assembly.GetExecutingAssembly();

            return GetAssemblyClasses(assembly)
                .Where((Type type) => {return IsAModule(type);});
        }

        public static IEnumerable<Type> GetAssemblyClasses(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                Console.WriteLine(type.FullName);
                yield return type;
            }
        }

        public static bool IsAModule(Type type)
        {
            return GetModuleAttribute(type) != null;
        }

        public static ModuleAttribute GetModuleAttribute(Type type)
        {
            ModuleAttribute[] moduleAttributes = GetModuleAttributes(type);
            Console.WriteLine(moduleAttributes.Length);
            if (moduleAttributes != null && moduleAttributes.Length != 0)
                return moduleAttributes[0];
            return null;
        }

        public static ModuleAttribute[] GetModuleAttributes(Type type)
        {
            return (ModuleAttribute[])type.GetCustomAttributes(typeof(ModuleAttribute), true);
        }

    }
}

Here is my custom Mdoule attribute:

using System;

namespace DynamicAssembly2
{
    [AttributeUsage(AttributeTargets.Class)]
    public class ModuleAttribute : Attribute
    {
        public string Description { get; set; }
    }
}

Here is a custom module:

namespace DynamicAssembly2
{
    [Module(Description="This is the main customer class.")]
    class Customers
    {
    }
}


问:
Overlay lines with a varying number of points from a list using ggplot2
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

```<code>test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}
</code>```

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

答:
So this gets you want you want I think. Note that it works on your list that has a different number of points per vector - which of course is one main reason why one would a list instead of a dataframes.

Most if not all of the examples on SO for this scenario are working with dataframes instead of data in lists. Since the vectors have different lengths, links that address this by melting a dataframe to a long form do not apply.

However if you did happen to have a dataframe, which implies a set of vectors of the same length, then you could use melt. However using gather from tidyr would probably be a more modern idiom for this than melt from reshape2. Note that melt can also be used on lists, although I would have to research how it handles the id.

I also choose not to use a function from the lapply class because I wanted to emphasis the "wide data" to "long data" aspect - something I think a for loop does far better that lapply, which beginning users can find mysterious.

Anyway we should probably be using something from purrr now as that is a modern type-stable functional library.

Here is some code - using a for loop, so not the most compact, but unrolled to make it easy and quick to understand:

```<code>library(ggplot2)
test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i)
}

# Convert data to long form
df <- NULL
for(i in 1:10){
  ydat <- test[[i]]
  ndf <- data.frame(key=paste0("id",i),x=1:length(ydat),y=ydat)
  df <- rbind(df,ndf)
}

# plot it
ggplot(df) + geom_line(aes(x=x,y=y,color=key))
</code>```

Yielding:

Body:
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

Body:
So this gets you want you want I think. Note that it works on your list that has a different number of points per vector - which of course is one main reason why one would a list instead of a dataframes.

Most if not all of the examples on SO for this scenario are working with dataframes instead of data in lists. Since the vectors have different lengths, links that address this by melting a dataframe to a long form do not apply.

However if you did happen to have a dataframe, which implies a set of vectors of the same length, then you could use melt. However using gather from tidyr would probably be a more modern idiom for this than melt from reshape2. Note that melt can also be used on lists, although I would have to research how it handles the id.

I also choose not to use a function from the lapply class because I wanted to emphasis the "wide data" to "long data" aspect - something I think a for loop does far better that lapply, which beginning users can find mysterious.

Anyway we should probably be using something from purrr now as that is a modern type-stable functional library.

Here is some code - using a for loop, so not the most compact, but unrolled to make it easy and quick to understand:

library(ggplot2)
test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i)
}

# Convert data to long form
df <- NULL
for(i in 1:10){
  ydat <- test[[i]]
  ndf <- data.frame(key=paste0("id",i),x=1:length(ydat),y=ydat)
  df <- rbind(df,ndf)
}

# plot it
ggplot(df) + geom_line(aes(x=x,y=y,color=key))

Yielding:


问:
Angular JS manipulating dom by element from link function
we know that we can access dom from directive by element because element is injected in link function.

see the approach

```<code>var app = angular.module("myApp", []);

app.directive('busyBox',function(){
     return  {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function(){
            if(attrs.id=='btnadd')
            {

              var divElement = angular.element(document.body.querySelector('.parent')).append('<div class="child">Some text</div>');
        //     console.log(divElement);
             //  element.parent().find('.parent').append('<div>Some text</div>')
                //element.closest('.parent').append('<div class="child">child</div>')
              //angular.element(document).find('.parent').append('<div class="child">child</div>');
            }
            else if(attrs.id=='btnDel')
            {
            angular.element(document.body.querySelector('.child')).remove();
           //    m.removeChild(m.firstChild);
            }
          });

        }
        }
})
</code>```

the above code is working but if i do not use angular.element() instead if i use element(document.body.querySelector('.parent')) the code is not working.

the element is injected in link function link: function(scope, element, attrs)
when element is there in directive then why should i use angular.element() ?

please tell me how could i use element from directive to access dom instead of angular.element().

thanks

答:
The element exposed to the postLink function is a jqLite class object which is a tiny, API-compatible subset of jQuery that allows AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most commonly needed functionality with the goal of having a very small footprint.

The find()  method is limited to lookups by tag name. If you want the find() method to work with class selectors, load jQuery before the angular.js file.

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or jqLite.

To use jQuery, simply ensure it is loaded before the angular.js file. You can also use the ngJq directive to specify that jqlite should be used over jQuery, or to use a specific version of jQuery if multiple versions exist on the page.

— AngularJS angular.element API Reference

Can't we use element. closest function instead of find to get the div?

The jQuery closest function is not part of AngularJS jqLite. To use the closest function with the element value exposed to the directive postLink function, load the jQuery library before loading the AngularJS library.

For the list of jqLite functions, see AngularJS angular.element API Reference

Body:
we know that we can access dom from directive by element because element is injected in link function.

see the approach

var app = angular.module("myApp", []);

app.directive('busyBox',function(){
     return  {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function(){
            if(attrs.id=='btnadd')
            {

              var divElement = angular.element(document.body.querySelector('.parent')).append('
Some text
');
        //     console.log(divElement);
             //  element.parent().find('.parent').append('
Some text
')
                //element.closest('.parent').append('
child
')
              //angular.element(document).find('.parent').append('
child
');
            }
            else if(attrs.id=='btnDel')
            {
            angular.element(document.body.querySelector('.child')).remove();
           //    m.removeChild(m.firstChild);
            }
          });

        }
        }
})

the above code is working but if i do not use angular.element() instead if i use element(document.body.querySelector('.parent')) the code is not working.

the element is injected in link function link: function(scope, element, attrs)
when element is there in directive then why should i use angular.element() ?

please tell me how could i use element from directive to access dom instead of angular.element().

thanks


问:
assign a column value to another column
I want to assign a column value to another column using case when.

Here, I want to assign 'CountAll' column to another columns.

I tried to fix it but it gives me an error like 'invalid identifier'. Need your help.

```<code>select cast(sysdate  as timestamp(0)) SAMPLE_TIME, SQL_ID, Count(*) as "CountAll", WAIT_TIME, WAIT_CLASS,
case when wait_time!=0 then 1 end as "CPU",
case when wait_time=0 and wait_class='Scheduler' then CountAll end as "Scheduler",
case when wait_time=0 and wait_class='User I/O' then Count1 end as "User I/O",
case when wait_time=0 and wait_class='System I/O' then Count1 end as "System I/O",
case when wait_time=0 and wait_class='Concurrency' then Count1 end as "Concurrency"
FROM  gv$session
</code>```

答:
My guess is that you want something like this:</p>

```<code>select cast(sysdate  as timestamp(0)) as SAMPLE_TIME, SQL_ID,
       Count(*) as CountAll,
       sum(case when wait_time <> 0 then 1 else 0 end) as "CPU",
       sum(case when wait_time = 0 and wait_class = 'Scheduler' then 1 else 0 end) as Scheduler,
       sum(case when wait_time = 0 and wait_class = 'User I/O' then 1 else 0 end) as "User I/O",
       sum(case when wait_time = 0 and wait_class = 'System I/O' then 1 else 0 end) as "System I/O",
       sum(case when wait_time = 0 and wait_class = 'Concurrency' then 1 else 0 end) as "Concurrency"
FROM gv$session
GROUP BY cast(sysdate  as timestamp(0)) as SAMPLE_TIME, SQL_ID;
</code>```

Title: assign a column value to another column

Body:
I want to assign a column value to another column using case when.

Here, I want to assign 'CountAll' column to another columns.

I tried to fix it but it gives me an error like 'invalid identifier'. Need your help.

select cast(sysdate  as timestamp(0)) SAMPLE_TIME, SQL_ID, Count(*) as "CountAll", WAIT_TIME, WAIT_CLASS,
case when wait_time!=0 then 1 end as "CPU",
case when wait_time=0 and wait_class='Scheduler' then CountAll end as "Scheduler",
case when wait_time=0 and wait_class='User I/O' then Count1 end as "User I/O",
case when wait_time=0 and wait_class='System I/O' then Count1 end as "System I/O",
case when wait_time=0 and wait_class='Concurrency' then Count1 end as "Concurrency"
FROM  gv$session

Body:
My guess is that you want something like this:

select cast(sysdate  as timestamp(0)) as SAMPLE_TIME, SQL_ID,
       Count(*) as CountAll,
       sum(case when wait_time <> 0 then 1 else 0 end) as "CPU",
       sum(case when wait_time = 0 and wait_class = 'Scheduler' then 1 else 0 end) as Scheduler,
       sum(case when wait_time = 0 and wait_class = 'User I/O' then 1 else 0 end) as "User I/O",
       sum(case when wait_time = 0 and wait_class = 'System I/O' then 1 else 0 end) as "System I/O",
       sum(case when wait_time = 0 and wait_class = 'Concurrency' then 1 else 0 end) as "Concurrency"
FROM gv$session
GROUP BY cast(sysdate  as timestamp(0)) as SAMPLE_TIME, SQL_ID;


问:
How to implement a binary search method to find matching string in two different text files
So i have two different text files. The first text file contains:

```<code>Apple
Banana
Berry
Lemon
Orange
</code>```

The second one contains:

```<code>Banana
Juice
Kiwi
Strawberry
Water
</code>```

The matching string I want outputted is "banana". I know how to implement this using hashsets, arraylists, and etc. But i want to use a binary search method. But I keep getting stuck because instead of dealing with integers, I am dealing with strings. Here is what I have so far:

```<code>public static boolean BinarySearch() throws FileNotFoundException {
        String compare;

        java.io.File firstlist= new java.io.File("firstlist.txt");
        Scanner scanner1= new Scanner(firstlist);

        java.io.File secondlist= new java.io.File("secondlist.txt");
        Scanner scanner2= new Scanner(secondlist);

        ArrayList<String> list= new ArrayList<>();
        while (scanner2.hasNextLine()){
            names.add(scanner2.nextLine());
        }

        int low =0;
        int high = list.size() -1;

        for(int i=0; i<list.size(); i++){
            compare=scanner1.nextLine();
            scanner2= new Scanner(list);

            while (high>=low){
                int middle = (low+high)/2;
                if (list.get(middle) == list.get(0)){
                    return 1;
                }
                if (list.get(middle) < list.get(0))
            }

        }
    }
</code>```

答:
Two main ideas of binary search:

sorted list

comparision function

As I understand, your strings in files are sorted using alphabetic order. String.compareTo is what you need for binary search, when you make desision about left or right part:

```<code>while (leftIndex < rightIndex) {
    int middleIndex = (rightIndex + leftIndex) / 2;
    String middle = strings[middleIndex];
    if (target.compareTo(middle) < 0) {
        rightIndex = middleIndex;
    } else {
        leftIndex = middle;
    }
}
</code>```

Body:
So i have two different text files. The first text file contains:

Apple
Banana
Berry
Lemon
Orange

The second one contains:

Banana
Juice
Kiwi
Strawberry
Water

The matching string I want outputted is "banana". I know how to implement this using hashsets, arraylists, and etc. But i want to use a binary search method. But I keep getting stuck because instead of dealing with integers, I am dealing with strings. Here is what I have so far:

public static boolean BinarySearch() throws FileNotFoundException {
        String compare;

        java.io.File firstlist= new java.io.File("firstlist.txt");
        Scanner scanner1= new Scanner(firstlist);

        java.io.File secondlist= new java.io.File("secondlist.txt");
        Scanner scanner2= new Scanner(secondlist);

        ArrayList<String> list= new ArrayList<>();
        while (scanner2.hasNextLine()){
            names.add(scanner2.nextLine());
        }

        int low =0;
        int high = list.size() -1;

        for(int i=0; i<list.size(); i++){
            compare=scanner1.nextLine();
            scanner2= new Scanner(list);

            while (high>=low){
                int middle = (low+high)/2;
                if (list.get(middle) == list.get(0)){
                    return 1;
                }
                if (list.get(middle) < list.get(0))
            }

        }
    }

Body:
Two main ideas of binary search:

sorted list

comparision function

As I understand, your strings in files are sorted using alphabetic order. String.compareTo is what you need for binary search, when you make desision about left or right part:

while (leftIndex < rightIndex) {
    int middleIndex = (rightIndex + leftIndex) / 2;
    String middle = strings[middleIndex];
    if (target.compareTo(middle) < 0) {
        rightIndex = middleIndex;
    } else {
        leftIndex = middle;
    }
}


问:
How to get all url parameters in asp.net mvc?
My test url:

```<code>localhost:61578/?type=promotion&foo=bar
</code>```

I usually use this way to get the value of type parameter:

```<code>public IActionResult Index(string type)
{
    // type = "promotion"
}
</code>```

My question: How to detect all parameters in the url? I want to prevent to access the page with some unknown parameter.

Something like this:

```<code>public IActionResult Index(string type, string foo)
{
    if (!string.IsNullOrEmpty(foo))
    {
        return BadRequest(); // page 404
    }
}
</code>```

The problem is: I don't know exactly the name what user enters. So, it can be:

```<code>localhost:61578/?bar=baz&type=promotion
</code>```

答:
You can use the HttpContext Type to grab the query string

```<code>var context = HttpContext.Current;
</code>```

then, you can grab the entire query string:

```<code>var queryString = context.Request.QueryString

// "bar=baz&type=promotion"
</code>```

or, you can get a list of objects:

```<code>var query = context.Request.Query.Select(_ => new
{
    Key = _.Key.ToString(),
    Value = _.Value.ToString()
});

// { Key = "bar", Value = "baz" }
// { Key = "type", Value = "promotion" }
</code>```

or, you could make a dictionary:

```<code>Dictionary<string, string>queryKvp = context.Request.GetQueryNameValuePairs()
    .ToDictionary(_=> _.Key, _=> _.Value, StringComparer.OrdinalIgnoreCase);

// queryKvp["bar"] = "baz"
// queryKvp["type"] = "promotion"
</code>```

Body:
My test url:

localhost:61578/?type=promotion&foo=bar

I usually use this way to get the value of type parameter:

public IActionResult Index(string type)
{
    // type = "promotion"
}

My question: How to detect all parameters in the url? I want to prevent to access the page with some unknown parameter.

Something like this:

public IActionResult Index(string type, string foo)
{
    if (!string.IsNullOrEmpty(foo))
    {
        return BadRequest(); // page 404
    }
}

The problem is: I don't know exactly the name what user enters. So, it can be:

localhost:61578/?bar=baz&type=promotion

Body:
You can use the HttpContext Type to grab the query string

var context = HttpContext.Current;

then, you can grab the entire query string:

var queryString = context.Request.QueryString

// "bar=baz&type=promotion"

or, you can get a list of objects:

var query = context.Request.Query.Select(_ => new
{
    Key = _.Key.ToString(),
    Value = _.Value.ToString()
});

// { Key = "bar", Value = "baz" }
// { Key = "type", Value = "promotion" }

or, you could make a dictionary:

Dictionary<string, string>queryKvp = context.Request.GetQueryNameValuePairs()
    .ToDictionary(_=> _.Key, _=> _.Value, StringComparer.OrdinalIgnoreCase);

// queryKvp["bar"] = "baz"
// queryKvp["type"] = "promotion"


问:
how to integrate zksforce with native ios and create custom login to get fields of sales force user
i try this to custom login with user name and password + security token. but it return error or exception like

```<code>Terminating app due to uncaught exception 'INVALID_LOGIN', reason: 'INVALID_LOGIN: Invalid username, password, security token; or user locked out.'
*** First throw call stack:
(
    0   CoreFoundation                      0x018fb5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x0167e8b6 objc_exception_throw + 44
    2   lead miner sales force              0x0001932a -[ZKBaseClient sendRequest:name:returnRoot:] + 2266
    3   lead miner sales force              0x0001882a -[ZKBaseClient sendRequest:name:] + 90
    4   lead miner sales force              0x00004516 -[ZKSoapLogin login] + 358
    5   lead miner sales force              0x000107c1 -[ZKSforceClient soapLogin:] + 65
    6   lead miner sales force              0x00010965 -[ZKSforceClient login:password:] + 277
    7   lead miner sales force              0x0000b0fb -[loginViewController loginbutton:] + 315
    8   libobjc.A.dylib                     0x01690874 -[NSObject performSelector:withObject:withObject:] + 77
    9   UIKit                               0x003ee0c2 -[UIApplication sendAction:to:from:forEvent:] + 108
    10  UIKit                               0x003ee04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
    11  UIKit                               0x004e60c1 -[UIControl sendAction:to:forEvent:] + 66
    12  UIKit                               0x004e6484 -[UIControl _sendActionsForEvents:withEvent:] + 577
    13  UIKit                               0x004e5733 -[UIControl touchesEnded:withEvent:] + 641
    14  UIKit                               0x0042b51d -[UIWindow _sendTouchesForEvent:] + 852
    15  UIKit                               0x0042c184 -[UIWindow sendEvent:] + 1232
    16  UIKit                               0x003ffe86 -[UIApplication sendEvent:] + 242
    17  UIKit                               0x003ea18f _UIApplicationHandleEventQueue + 11421
    18  CoreFoundation                      0x0188483f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    19  CoreFoundation                      0x018841cb __CFRunLoopDoSources0 + 235
    20  CoreFoundation                      0x018a129e __CFRunLoopRun + 910
    21  CoreFoundation                      0x018a0ac3 CFRunLoopRunSpecific + 467
    22  CoreFoundation                      0x018a08db CFRunLoopRunInMode + 123
    23  GraphicsServices                    0x038a09e2 GSEventRunModal + 192
    24  GraphicsServices                    0x038a0809 GSEventRun + 104
    25  UIKit                               0x003ecd3b UIApplicationMain + 1225
    26  lead miner sales force              0x0001bd42 main + 130
    27  libdyld.dylib                       0x020a370d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type ZKSoapException
</code>```

Thank you for kind replay....

```<code>-(IBAction)loginbutton:(id)sender
{

NSString *username=[NSString stringWithFormat:@"%@",usernamefield.text];
NSString *password=[NSString stringWithFormat:@"%@",passwordfield.text];

ZKSforceClient *sforce = [[ZKSforceClient alloc] init];
[sforce login:username password:password];

ZKDescribeSObject *taskDescribe = [sforce describeSObject:@"Task"];
NSLog(@"url for the new Task page is %@", [taskDescribe urlNew]);
[sforce release];
}
</code>```

答:
In swift you can use this.

```<code>let username = "abc@gmail.com"
let password = "1234" + "yourtoken"
let client = ZKSforceClient()
client.performLogin(username, password: password, fail:{ (fail) in
            print(fail)

        }) { (success) in
            print(success)

        }
</code>```

It will give you proper exception handling with fail and success.Hope it will work!!

Body:
i try this to custom login with user name and password + security token. but it return error or exception like

Terminating app due to uncaught exception 'INVALID_LOGIN', reason: 'INVALID_LOGIN: Invalid username, password, security token; or user locked out.'
*** First throw call stack:
(
    0   CoreFoundation                      0x018fb5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x0167e8b6 objc_exception_throw + 44
    2   lead miner sales force              0x0001932a -[ZKBaseClient sendRequest:name:returnRoot:] + 2266
    3   lead miner sales force              0x0001882a -[ZKBaseClient sendRequest:name:] + 90
    4   lead miner sales force              0x00004516 -[ZKSoapLogin login] + 358
    5   lead miner sales force              0x000107c1 -[ZKSforceClient soapLogin:] + 65
    6   lead miner sales force              0x00010965 -[ZKSforceClient login:password:] + 277
    7   lead miner sales force              0x0000b0fb -[loginViewController loginbutton:] + 315
    8   libobjc.A.dylib                     0x01690874 -[NSObject performSelector:withObject:withObject:] + 77
    9   UIKit                               0x003ee0c2 -[UIApplication sendAction:to:from:forEvent:] + 108
    10  UIKit                               0x003ee04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
    11  UIKit                               0x004e60c1 -[UIControl sendAction:to:forEvent:] + 66
    12  UIKit                               0x004e6484 -[UIControl _sendActionsForEvents:withEvent:] + 577
    13  UIKit                               0x004e5733 -[UIControl touchesEnded:withEvent:] + 641
    14  UIKit                               0x0042b51d -[UIWindow _sendTouchesForEvent:] + 852
    15  UIKit                               0x0042c184 -[UIWindow sendEvent:] + 1232
    16  UIKit                               0x003ffe86 -[UIApplication sendEvent:] + 242
    17  UIKit                               0x003ea18f _UIApplicationHandleEventQueue + 11421
    18  CoreFoundation                      0x0188483f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    19  CoreFoundation                      0x018841cb __CFRunLoopDoSources0 + 235
    20  CoreFoundation                      0x018a129e __CFRunLoopRun + 910
    21  CoreFoundation                      0x018a0ac3 CFRunLoopRunSpecific + 467
    22  CoreFoundation                      0x018a08db CFRunLoopRunInMode + 123
    23  GraphicsServices                    0x038a09e2 GSEventRunModal + 192
    24  GraphicsServices                    0x038a0809 GSEventRun + 104
    25  UIKit                               0x003ecd3b UIApplicationMain + 1225
    26  lead miner sales force              0x0001bd42 main + 130
    27  libdyld.dylib                       0x020a370d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type ZKSoapException

Thank you for kind replay....

-(IBAction)loginbutton:(id)sender
{

NSString *username=[NSString stringWithFormat:@"%@",usernamefield.text];
NSString *password=[NSString stringWithFormat:@"%@",passwordfield.text];

ZKSforceClient *sforce = [[ZKSforceClient alloc] init];
[sforce login:username password:password];

ZKDescribeSObject *taskDescribe = [sforce describeSObject:@"Task"];
NSLog(@"url for the new Task page is %@", [taskDescribe urlNew]);
[sforce release];
}

Body:
In swift you can use this.

let username = "abc@gmail.com"
let password = "1234" + "yourtoken"
let client = ZKSforceClient()
client.performLogin(username, password: password, fail:{ (fail) in
            print(fail)

        }) { (success) in
            print(success)

        }

It will give you proper exception handling with fail and success.Hope it will work!!


问:
In Complexity Analysis why is ++ considered to be 2 operations?
In my Computer Science II class, the professor considers ++,--,*=, etc. to be 2 operations. However, at the Assembly level this is not really two operations. Can someone explain or is this just for the sake of simplicity?</p>

答:
I am gonna throw a few guesses.

Is your professor is referring to interpreted languages?

++i is different than i++ maybe he's referring to that?

Maybe his assembly lang of choice needs the intermediate storage variable?

```<code>add reg_temp, reg_i, 1
mov reg_i, reg_temp
</code>```

Body:
I am gonna throw a few guesses.

Is your professor is referring to interpreted languages?

++i is different than i++ maybe he's referring to that?

Maybe his assembly lang of choice needs the intermediate storage variable?

add reg_temp, reg_i, 1
mov reg_i, reg_temp


问:
How to determine whether a file has been closed
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.

I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).

Any suggestions?

答:
You can check it with select and poll. Select will return EBADF if a file descriptor is closed:

```<code>fd_set rfds;
struct timeval tv = { 0, 1 };
int retval;

FD_ZERO(&rfds);
FD_SET(fd, &rfds);

retval = select(1, &rfds, NULL, NULL, &tv);
if (retval == -1 && errno == EBADF)
  // File is closed
</code>```

NOTE that I've not tested this code but the documentation tells this.

Also that this is not exactly precise since errno can be EBADF for different reasons too.

EDIT: Another thing: If you open a file right after closing another it will most likely have the same fd as the previous, so this only works semi-decent if you want to check if all files have been closed.

Body:
You can check it with select and poll. Select will return EBADF if a file descriptor is closed:

fd_set rfds;
struct timeval tv = { 0, 1 };
int retval;

FD_ZERO(&rfds);
FD_SET(fd, &rfds);

retval = select(1, &rfds, NULL, NULL, &tv);
if (retval == -1 && errno == EBADF)
  // File is closed

NOTE that I've not tested this code but the documentation tells this.

Also that this is not exactly precise since errno can be EBADF for different reasons too.

EDIT: Another thing: If you open a file right after closing another it will most likely have the same fd as the previous, so this only works semi-decent if you want to check if all files have been closed.


问:
CSV to JSON using Golang - some data is skipped while printing in Web Browser
I have read one excel csv file using Golang and wanted to print them to web browser as JSON Data for every GET request you make,But every time I print the JSON Data in Web browser some data gets skipped. I have double checked those data are in csv file but not getting printed in web browser. Any help you can suggest me ? Thanks in advance

```<code>package main

import (
"encoding/csv"
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"os"
)

var csvData [][]string
var Record IRIS
var i int = 0

func init() {
    csvFile, err := os.Open("IRIS.csv")
    if err != nil {
       fmt.Println(err)
     }

    reader := csv.NewReader(csvFile)
    reader.FieldsPerRecord = -1
    csvData, _ = reader.ReadAll()

    if err != nil {
            fmt.Println(err)
            os.Exit(1)
    }
        defer csvFile.Close()
}
 type IRIS struct {
    ID          string
    SepalLength string
    SepalWidth  string
    PetalLength string
    PetalWidth  string
    Species     string
 }

func main() {
    router := httprouter.New()
    router.GET("/stream/content/data", StreamDataHandler)
    fmt.Println(http.ListenAndServe("127.0.0.1:9090", router))
}
func StreamDataHandler(res http.ResponseWriter, req *http.Request, p      httprouter.Params) {
    res.Header().Set("Access-Control-Allow-Origin", "*")

    // read data from CSV file
    Record.ID = csvData[i][0]
    Record.SepalLength = csvData[i][1]
    Record.SepalWidth = csvData[i][2]
    Record.PetalLength = csvData[i][3]
    Record.PetalWidth = csvData[i][4]
    Record.Species = csvData[i][5]

    jsondata, err := json.Marshal(Record) // convert to JSON

    if err != nil {
            fmt.Println(err)
            os.Exit(1)
    }

    i = i + 1

    fmt.Fprintf(res, string(jsondata))
    return
}
</code>```

OUTPUT:

{"ID":"2","SepalLength":"4.9","SepalWidth":"3","PetalLength":"1.4","PetalWidth":"0.2","Species":"setosa"}

{"ID":"6","SepalLength":"5.4","SepalWidth":"3.9","PetalLength":"1.7","PetalWidth":"0.4","Species":"setosa"}

{"ID":"7","SepalLength":"5.7","SepalWidth":"4.4","PetalLength":"1.5","PetalWidth":"0.4","Species":"setosa"}

.
.
.

Why this is happening ?

I actually wanted to print all the values (without skipping any) like streaming of data every 2 second from Excel CSV file

答:
There's a race condition in your handler on accesses made to i. Multiple goroutines will execute the i = i + 1 statement resulting in several possible values for i. Use of a mutex should fix the issue:

```<code>// ...

var i int = 0
var m sync.Mutex

// ...

func StreamDataHandler(res http.ResponseWriter, req *http.Request, p      httprouter.Params) {
    // ...

    m.Lock()
    defer m.Unlock()
    i = i + 1

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

However, if you want to continuously fetch the values using http Get, a better solution would be to include last index fetched in the response and add this value (after incrementing it, for example) as a request parameter in the next request to indicate the next required index. This way you don't need to maintain i in your handler.

Body:
I have read one excel csv file using Golang and wanted to print them to web browser as JSON Data for every GET request you make,But every time I print the JSON Data in Web browser some data gets skipped. I have double checked those data are in csv file but not getting printed in web browser. Any help you can suggest me ? Thanks in advance

package main

import (
"encoding/csv"
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"os"
)

var csvData [][]string
var Record IRIS
var i int = 0

func init() {
    csvFile, err := os.Open("IRIS.csv")
    if err != nil {
       fmt.Println(err)
     }

    reader := csv.NewReader(csvFile)
    reader.FieldsPerRecord = -1
    csvData, _ = reader.ReadAll()

    if err != nil {
            fmt.Println(err)
            os.Exit(1)
    }
        defer csvFile.Close()
}
 type IRIS struct {
    ID          string
    SepalLength string
    SepalWidth  string
    PetalLength string
    PetalWidth  string
    Species     string
 }

func main() {
    router := httprouter.New()
    router.GET("/stream/content/data", StreamDataHandler)
    fmt.Println(http.ListenAndServe("127.0.0.1:9090", router))
}
func StreamDataHandler(res http.ResponseWriter, req *http.Request, p      httprouter.Params) {
    res.Header().Set("Access-Control-Allow-Origin", "*")

    // read data from CSV file
    Record.ID = csvData[i][0]
    Record.SepalLength = csvData[i][1]
    Record.SepalWidth = csvData[i][2]
    Record.PetalLength = csvData[i][3]
    Record.PetalWidth = csvData[i][4]
    Record.Species = csvData[i][5]

    jsondata, err := json.Marshal(Record) // convert to JSON

    if err != nil {
            fmt.Println(err)
            os.Exit(1)
    }

    i = i + 1

    fmt.Fprintf(res, string(jsondata))
    return
}

OUTPUT:

{"ID":"2","SepalLength":"4.9","SepalWidth":"3","PetalLength":"1.4","PetalWidth":"0.2","Species":"setosa"}

{"ID":"6","SepalLength":"5.4","SepalWidth":"3.9","PetalLength":"1.7","PetalWidth":"0.4","Species":"setosa"}

{"ID":"7","SepalLength":"5.7","SepalWidth":"4.4","PetalLength":"1.5","PetalWidth":"0.4","Species":"setosa"}

.
.
.

Why this is happening ?

I actually wanted to print all the values (without skipping any) like streaming of data every 2 second from Excel CSV file

Body:
There's a race condition in your handler on accesses made to i. Multiple goroutines will execute the i = i + 1 statement resulting in several possible values for i. Use of a mutex should fix the issue:

// ...

var i int = 0
var m sync.Mutex

// ...

func StreamDataHandler(res http.ResponseWriter, req *http.Request, p      httprouter.Params) {
    // ...

    m.Lock()
    defer m.Unlock()
    i = i + 1

    // ...
}

However, if you want to continuously fetch the values using http Get, a better solution would be to include last index fetched in the response and add this value (after incrementing it, for example) as a request parameter in the next request to indicate the next required index. This way you don't need to maintain i in your handler.


问:
Why this SQL query does not work?
I wrote this query but I get the following error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'BEGIN INSERT
  INTO forum_topics_track (userid, topic_id, `c' at line 3

I guess it is self explanatory but my goal is to check if the record exists and if it doesn't, to insert it.

```<code>IF NOT EXISTS
                (SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}')
            BEGIN
                INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
                VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
            END;
</code>```

答:
A faster alternative would be to have a UNIQUE INDEX on userid and topic_id.

```<code>CREATE UNIQUE INDEX forum_topics_track_ndx ON forum_topics_track(userid, topic_id);
</code>```

Then you could do

```<code>INSERT IGNORE INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
            VALUES ('{$topic_id}', '{$category_id}', '{$userid}');
</code>```

which would always succeed (possibly doing nothing if the data already is there).

Or you could look into the ON DUPLICATE KEY UPDATE trick.

Title: Why this SQL query does not work?

Body:
I wrote this query but I get the following error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'BEGIN INSERT
  INTO forum_topics_track (userid, topic_id, `c' at line 3

I guess it is self explanatory but my goal is to check if the record exists and if it doesn't, to insert it.

IF NOT EXISTS
                (SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}')
            BEGIN
                INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
                VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
            END;

Body:
A faster alternative would be to have a UNIQUE INDEX on userid and topic_id.

CREATE UNIQUE INDEX forum_topics_track_ndx ON forum_topics_track(userid, topic_id);

Then you could do

INSERT IGNORE INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
            VALUES ('{$topic_id}', '{$category_id}', '{$userid}');

which would always succeed (possibly doing nothing if the data already is there).

Or you could look into the ON DUPLICATE KEY UPDATE trick.


问:
Fetch User detail with his role in laravel 5.4
My Application have below setup

Users table:
id
roleid
firstname
email
password

Roles table:
id
userid
rolename

There will be total 4 fixed roles and those will be assigned to users.

Now i want related role name when i do login with user.So in laravel eloquent model how can i define the relationships and how can i fetch and display?

I am new to laravel 5.4

答:
If your relation between user and roles is One To Many

Have a read on below link. You'll get the idea.

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many


问:
Using "order" property starts divs at the bottom and gradually rises as I add more
As the title suggests I am messing around with display: flex and order:. When I start with my first ordered div (order: 0;) It will start at the top of my page. When I add in my first (order: 1;) it begins at the bottom of the page and so on so forth. What else is weird is that as I add more divs to the order it gradually moves them up on the page to where they should have originally started.

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 100%;
  height: 100px;
  text-align: center;
}

.lime {
  width: 100%;
  order: 0;
  background-color: lime;
}

.red {
  width: 50%;
  order: 1;
  background-color: red;
}

.orange {
  width: 50%;
  order: 2;
  background-color: orange;
}

.teal {
  width: 100%;
  order: 3;
  background-color: teal;
}

.light_blue {
  width: 20%;
  order: 4;
  background-color: lightblue;
}

.dark_blue {
  width: 60%;
  order: 5;
  background-color: darkblue;
}

.green {
  width: 20%;
  order: 6;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div class="box lime"></div>
    <div class="box dark_blue"></div>
    <div class="box light_blue"></div>
    <div class="box green"></div>
    <div class="box red"></div>
    <div class="box orange"></div>
    <div class="box teal"></div>
  </div>
</body></code>```

I guess my question here is why is this happening and why is it only working as intended after I add my .green {width: 20%; order: 6; background-color: green;} at the end of my css?

答:
Your markup is working as expected, (and it only works as intended after you set order:6, because until then the default value for that element was order:0)

Remember with order:

By default, flex items are laid out in the source order. However, the
  order property controls the order in which they appear in the flex
  container.

However you can simplify your use of orders in the code by just using the orders  4,5 and 6 in the same elements you are using it.

body {
  margin: 0
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  height: 100px;
}

.lime {
  background-color: lime;
}

.red {
  background-color: red;
}

.orange {
  background-color: orange;
}

.teal {
  background-color: teal;
}

.light_blue {
  order: 4;
  background-color: lightblue;
}

.dark_blue {
  flex: 0 60%;
  order: 5;
  background-color: darkblue;
}

.green {
  order: 6;
  background-color: green;
}

.fifthish {
  flex: 0 20%
}

.half {
  flex: 0 50%
}

.full {
  flex: 0 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box lime full"></div>
  <div class="box dark_blue"></div>
  <div class="box light_blue fifthish"></div>
  <div class="box green fifthish"></div>
  <div class="box red half"></div>
  <div class="box orange half"></div>
  <div class="box teal full"></div>
</div></code>```

Body:
As the title suggests I am messing around with display: flex and order:. When I start with my first ordered div (order: 0;) It will start at the top of my page. When I add in my first (order: 1;) it begins at the bottom of the page and so on so forth. What else is weird is that as I add more divs to the order it gradually moves them up on the page to where they should have originally started.

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 100%;
  height: 100px;
  text-align: center;
}

.lime {
  width: 100%;
  order: 0;
  background-color: lime;
}

.red {
  width: 50%;
  order: 1;
  background-color: red;
}

.orange {
  width: 50%;
  order: 2;
  background-color: orange;
}

.teal {
  width: 100%;
  order: 3;
  background-color: teal;
}

.light_blue {
  width: 20%;
  order: 4;
  background-color: lightblue;
}

.dark_blue {
  width: 60%;
  order: 5;
  background-color: darkblue;
}

.green {
  width: 20%;
  order: 6;
  background-color: green;
}

I guess my question here is why is this happening and why is it only working as intended after I add my .green {width: 20%; order: 6; background-color: green;} at the end of my css?

Body:
Your markup is working as expected, (and it only works as intended after you set order:6, because until then the default value for that element was order:0)

Remember with order:

By default, flex items are laid out in the source order. However, the
  order property controls the order in which they appear in the flex
  container.

However you can simplify your use of orders in the code by just using the orders  4,5 and 6 in the same elements you are using it.

body {
  margin: 0
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  height: 100px;
}

.lime {
  background-color: lime;
}

.red {
  background-color: red;
}

.orange {
  background-color: orange;
}

.teal {
  background-color: teal;
}

.light_blue {
  order: 4;
  background-color: lightblue;
}

.dark_blue {
  flex: 0 60%;
  order: 5;
  background-color: darkblue;
}

.green {
  order: 6;
  background-color: green;
}

.fifthish {
  flex: 0 20%
}

.half {
  flex: 0 50%
}

.full {
  flex: 0 100%
}

<div class="container">
  <div class="box lime full"></div>
  <div class="box dark_blue"></div>
  <div class="box light_blue fifthish"></div>
  <div class="box green fifthish"></div>
  <div class="box red half"></div>
  <div class="box orange half"></div>
  <div class="box teal full"></div>
</div>


答:
This is the wrong way to implement the logic.  If you want each user and topic to appear in forum_topics_track one time, then have the database enforce the constraint.  This is easy with a unique index or constraint:

```<code>create unique index unq_forum_topics_track_user_topic on forum_topics_track(user_id, topic_id);
</code>```

Then, you can do an insert and ignore or handle the error:

```<code>INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
    VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
    ON DUPLICATE KEY UPDATE userid = VALUES(userid);
</code>```

No IF is needed in the logic.  In fact, using IF just invites problems due to race conditions and doesn't really guarantee anything in the database.

Title: Why this SQL query does not work?

Body:
This is the wrong way to implement the logic.  If you want each user and topic to appear in forum_topics_track one time, then have the database enforce the constraint.  This is easy with a unique index or constraint:

create unique index unq_forum_topics_track_user_topic on forum_topics_track(user_id, topic_id);

Then, you can do an insert and ignore or handle the error:

INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
    VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
    ON DUPLICATE KEY UPDATE userid = VALUES(userid);

No IF is needed in the logic.  In fact, using IF just invites problems due to race conditions and doesn't really guarantee anything in the database.