问:
How to upload PHP and MySQL into a webserver
I am developing a site in vertigoserver. Now I need to test the webpage in webserver.

I am using the webserver Host-Europe VirtualServer 3.0.

Now what are the steps I need to upload the PHP pages?

What is the software needed to upload MySQL queries?

Are there any tutorials or suggestions?

答:
Okay, you got a virtual machine and don't know how to upload stuff? This has been discussed in Host-Europe forums for a while. If you don't know the basics you probably don't want to run a server on your own. If you don't know how to use Linux don't start with a machine which can get you in a lot of trouble. A hosting package is probably better you at the moment.

The problem I have is you didn't specify what OS you have. If you're using Linux with Plesk you want to activate FTP, etc. If you are using Linux without Plesk you want to upload the PHP files with WinSCP and over SSH (SCP).

If you are running Windows with Plesk use FTP. If not, you should install an FTP server on the machine.

Regarding the MySQL stuff you're probably best off installing a webfrontend for MySQL.

!DON'T FORGET TO SECURE IT!

OwnerDisplayName: venkatachalam

LastEditorDisplayName: Paul Dixon

OwnerDisplayName: Thomaschaaf


来源: stackexchange

问:
Google Earth API for Android
I want to ask if Google Earth API is avaialble for developing android application.
If google earth api is not available for android, are there any map api which can be used off network on android?</p>

答:
You can use the open source AndNav library for offline mapping.  The API is very similar to the Android Google Maps one.  The code can be found here: http://code.google.com/p/andnav/

Their wiki has a lot of good information and downloads for map tile packs.

ContentLicense: CC BY-SA 2.5

Title: Google Earth API for Android


问:
Docusign API limits and violations
I want to make the below three calls one by one immediately  from my app. All are get calls to Docusign and all are  different urls but same envelope id .

Is it possible to do make below three calls immediately from my app or we need to make call after 15 minutes.. for go live?

Calls:

```<code>baseUrl + "/envelopes/" + envelopeId+ "/documents/combined";

baseUrl+"/envelopes/"+envelopeId+"/recipients/1/tabs";

baseUrl + "/envelopes/" + envelopeId + "/documents/certificate";
</code>```

答:
From Documentation

You may not exceed 1 GET request per unique envelope endpoint per 15 minutes.

You can make the first two calls within the 15 minute window as they are invoking unique endpoints.

However you cannot repeat the call to the same endPoint within the 15 minute window for the same envelope.

API Limit Violations:

Example: Calling the GetDocument Api within 5 minutes.

Calls

```<code>11:00 AM
GET baseUrl + "/envelopes/F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4/documents/combined"

11:05AM
GET baseUrl + "/envelopes/F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4/documents/combined"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Docusign API limits and violations

Body:
I want to make the below three calls one by one immediately  from my app. All are get calls to Docusign and all are  different urls but same envelope id .

Is it possible to do make below three calls immediately from my app or we need to make call after 15 minutes.. for go live?

Calls:

baseUrl + "/envelopes/" + envelopeId+ "/documents/combined";

baseUrl+"/envelopes/"+envelopeId+"/recipients/1/tabs";

baseUrl + "/envelopes/" + envelopeId + "/documents/certificate";

Body:
From Documentation

You may not exceed 1 GET request per unique envelope endpoint per 15 minutes.

You can make the first two calls within the 15 minute window as they are invoking unique endpoints.

However you cannot repeat the call to the same endPoint within the 15 minute window for the same envelope.

API Limit Violations:

Example: Calling the GetDocument Api within 5 minutes.

Calls

11:00 AM
GET baseUrl + "/envelopes/F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4/documents/combined"

11:05AM
GET baseUrl + "/envelopes/F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4/documents/combined"


问:
How do I pause CSS transition?
I need to pause a CSS transition at any time during the transition. I know there is a solution with calculating the current value of the transitioning property and applying it directly, however this gave me "jumping" results in Safari and IE11.

What I though of is to increase the transition-duration value to something big, that is in my theory should have almost paused the transition, but it seems it's not the case:

https://jsfiddle.net/j8p0msff/

```<code>$('#pause').on('click', function() {
    $('.ball').css('transition-duration: 5000s');
});
</code>```

Any other ideas? Thanks!

答:
Transitions

A solution would be to remove the transition class and save the current state of styles (margin-leftin the example) when stopping. And when starting just add the transition class again.

var boxOne = document.getElementsByClassName('box')[0];
var running = false;

var toggleTransition = function() {
  if(!running)
  {
    boxOne.classList.add('horizTranslate');
  } else {
    var computedStyle = window.getComputedStyle(boxOne),
        marginLeft = computedStyle.getPropertyValue('margin-left');
    boxOne.style.marginLeft = marginLeft;
    boxOne.classList.remove('horizTranslate');
  }

  running = !running;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  margin: 30px;
  height: 50px;
  width: 50px;
  background-color: blue;
}
.box.horizTranslate {
  -webkit-transition: 3s;
  -moz-transition: 3s;
  -ms-transition: 3s;
  -o-transition: 3s;
  transition: 3s;
  margin-left: 50% !important;
}</code>```

<button class='toggleButton' onclick='toggleTransition()'>Toggle</button>```
</div>
</div>
</p>

<p><strong>Animations</strong></p>

<p>You could use: <code>animation-play-state</code></p>

<p>With e.g. Javascript: <code>document.getElementById('myId').style.animationPlayState = 'paused'</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var toggleAnimation = function(){
  state = document.getElementById('myId').style.animationPlayState == 'paused' ? 'running' : 'paused';
  document.getElementById('myId').style.animationPlayState = state;
}</code>```

div#myId {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
    -webkit-animation-play-state: running; /* Safari 4.0 - 8.0 */
    animation: mymove 5s infinite;
    animation-play-state: running;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='myId'></div>

<button onclick="toggleAnimation()">Toggle Animation</button></code>```

Title: How do I pause CSS transition?

Body:
I need to pause a CSS transition at any time during the transition. I know there is a solution with calculating the current value of the transitioning property and applying it directly, however this gave me "jumping" results in Safari and IE11.

What I though of is to increase the transition-duration value to something big, that is in my theory should have almost paused the transition, but it seems it's not the case:

https://jsfiddle.net/j8p0msff/

$('#pause').on('click', function() {
    $('.ball').css('transition-duration: 5000s');
});

Any other ideas? Thanks!

Body:
Transitions

A solution would be to remove the transition class and save the current state of styles (margin-leftin the example) when stopping. And when starting just add the transition class again.

var boxOne = document.getElementsByClassName('box')[0];
var running = false;

var toggleTransition = function() {
  if(!running)
  {
    boxOne.classList.add('horizTranslate');
  } else {
    var computedStyle = window.getComputedStyle(boxOne),
        marginLeft = computedStyle.getPropertyValue('margin-left');
    boxOne.style.marginLeft = marginLeft;
    boxOne.classList.remove('horizTranslate');
  }

  running = !running;
}

.box {
  margin: 30px;
  height: 50px;
  width: 50px;
  background-color: blue;
}
.box.horizTranslate {
  -webkit-transition: 3s;
  -moz-transition: 3s;
  -ms-transition: 3s;
  -o-transition: 3s;
  transition: 3s;
  margin-left: 50% !important;
}

<div class='box'></div>
<button class='toggleButton' onclick='toggleTransition()'>Toggle</button>

Animations

You could use: animation-play-state

With e.g. Javascript: document.getElementById('myId').style.animationPlayState = 'paused'

var toggleAnimation = function(){
  state = document.getElementById('myId').style.animationPlayState == 'paused' ? 'running' : 'paused';
  document.getElementById('myId').style.animationPlayState = state;
}

div#myId {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
    -webkit-animation-play-state: running; /* Safari 4.0 - 8.0 */
    animation: mymove 5s infinite;
    animation-play-state: running;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}

<div id='myId'></div>

<button onclick="toggleAnimation()">Toggle Animation</button>


问:
Java Garbage Collector - Not running normally at regular intervals
I have a program that is constantly running. Normally, it seems to garbage collect, and remain under about 8MB of memory usage. However, every weekend, it refuses to garbage collect unless I make an explicit call to it. However, if it nears the maximum heap size, it will still garbage collect. However the only reason this issue was noticed, is because it actually crashed from running out of memory on one weekend i.e. it must have reached the maximum heap size, and not run the garbage collector.

The following image (click to see) is a graph of the program's memory usage over a day. On the sides of the graph, you can see the normal behaviour of the program's memory usage, but the first large peak is what seems to start over the weekend. This particular graph is a strange example, because after I made an explicit call to the garbage collector, it ran successfully, but then it went and climbed back to the maximum heap size and successfully garbage collected on it's own twice.

What is going on here?

EDIT:

Ok, from the comments, it seems I haven't provided enough information. The program simply receives a stream of UDP packets, which are placed in a queue (set to have a maximum size of 1000 objects), which are then processed to have their data stored in a database. On average, it gets about 80 packets per second, but can peak to 150. It's running under Windows Server 2008.

The thing is, this activity is fairly consistent, and if anything, at the time that the memory usage starts it's steady climb, the activity should be lower, not higher. Mind you, the graph I posted above is the only one I have that extends back that far, since I only changed the Java Visual VM wrapper to keep graph data back far enough to see it this week, so I have no idea if it's exactly the same time every week, because I can't watch it over the weekend, as it's on a private network, and I'm not at work on the weekend.

Here is a graph of the next day:

This is pretty much what the memory usage looks like every other day of the week. The program is never restarted, and we only tell it to garbage collect on a Monday morning because of this issue. One week we tried restarting it on a Friday afternoon, and it still started climbing sometime over the weekend, so the time that we restart it doesn't seem to have anything to do with the memory usage next week.

The fact that it successfully garbage collects all those objects when we tell it to implies to me that the objects are collectable, it's just not doing it until it reaches the maximum heap size, or we explicitly call the garbage collector. A heap dump doesn't tell us anything, because when we try to perform one, it suddenly runs the garbage collector, and then outputs a heap dump, which of course looks perfectly normal at this point.

So I suppose I have two questions: Why is it suddenly not garbage collecting the way it does the rest of the week, and why is it that on one occassion, the garbage collection that occurs when it reaches the maximum heap size was unable to collect all those objects (i.e. why would there be references to so many objects that one time, when every other time there must not be)?

UPDATE:

This morning has been an interesting one. As I mentioned in the comments, the program is running on a client's system. Our contact in the client organisation reports that at 1am, this program failed, and he had to restart it manually when he got into work this morning, and that once again, the server time was incorrect. This is an issue we've had with them in the past, but until now, the issue never seemed to be related.

Looking through the logs that our program produces, we can deduce the following information:

At 01:00, the server has somehow resynced it's time, setting it to 00:28.

At 00:45 (according to the new, incorrect server time), one of the message processing threads in the program has thrown an out of memory error.

However, the other message processing thread (there are two types of messages we receive, they are processed slightly differently, but they are both constantly coming in), continues to run, and as usual, the memory usage continues to climb with no garbage collection (as seen from the graphs we have been recording, once again).

At 00:56, the logs stop, until about 7am when the program was restarted by our client. However, the memory usage graph, for this time, was still steadily increasing.

Unfortunately, because of the change in server time, this makes the times on our memory usage graph unreliable. However, it seems to be that it tried to garbage collect, failed, increased the heap space to the maximum available size, and killed that thread all at once. Now that the maximum heap space has increased, it's happy to use all of it without performing a major garbage collection.

So now I ask this: if the server time changes suddenly like it did, can that cause a problem with the garbage collection process?

答:
However the only reason this issue was noticed, is because it actually crashed from running out of memory on one weekend i.e. it must have reached the maximum heap size, and not run the garbage collector.

I think your diagnosis is incorrect.  Unless there is something seriously broken about your JVM, then the application will only throw an OOME after it has just run a full garbage collect, and discovered that it still doesn't have enough free heap to proceed*.

I suspect that what is going on here is one or more of the following:

Your application has a slow memory leak.  Each time you restart the application, the leaked memory gets reclaimed.  So, if you restart the application regularly during the week, this could explain why it only crashes on the weekend.

Your application is doing computations that require varying amounts of memory to complete.  On that weekend, someone sent it a request that required more memory that was available.

Running the GC by hand is not actually going to solve the problem in either case.  What you need to do is to investigate the possibility of memory leaks, and also look at the application memory size to see if it is large enough for the tasks that are being performed.

If you can capture heap stats over a long period, a memory leak will show up as a downwards trend over time in the amount of memory available after full garbage collections.  (That is the height of the longest "teeth" of the sawtooth pattern.)  A workload-related memory shortage will probably show up as an occasional sharp downwards trend in the same measure over a relatively short period of time, followed by a recovery.  You may see both, then you could have both things happening.

* Actually, the criteria for deciding when to give up with an OOME are a bit more complicated than this.  They depend on certain JVM tuning options, and can include the percentage of time spent running the GC.

FOLLOWUP

@Ogre - I'd need a lot more information about your application to be able to answer that question (about memory leaks) with any specificity.

With your new evidence, there are two further possibilities:

Your application may be getting stuck in a loop that leaks memory as a result of the clock time-warping.

The clock time-warping may cause the GC to think that it is taking too large a percentage of run time and trigger an OOME as a result.  This behaviour depends on your JVM settings.

Either way, you should lean hard on your client to get them to stop adjusting the system clock like that.  (A 32 minute timewarp is way too much!!).  Get them to install a system service to keep the clock in sync with network time hour by hour (or more frequent).  Critically, get them to use a service with an option to adjusts the clock in small increments.

(Re the 2nd bullet: there is a GC monitoring mechanism in the JVM that measures the percentage of overall time that the JVM is spending running the GC, relative to doing useful work.  This is designed to prevent the JVM from grinding to a halt when your application is really running out of memory.

This mechanism would be implemented by sampling the wall-clock time at various points.  But if the wall-clock time is timewarped at a critical point, it is easy to see how the JVM may think that a particular GC run took much longer than it actually did ... and trigger the OOME.)


问:
ChartJS: Mapping Non numeric Y and X
I'm trying to map non numeric y and x and for some reason it does not work.

E.g.

```<code>xLabels: ["January", "February", "March", "April", "May", "June", "July"],
yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
</code>```

And when i try to change:

```<code>data: ['Request Added', 'Request Viewed']
</code>```

with

```<code>data: [{x: "January", y: 'Request Added'}, ...]
</code>```

Graph does not show a thing

Also i tried to use scales.yAxis.ticks.callback to modify and map against an array but that didnt work out either.

```<code>[0: 'Request Added', 1: 'Request Viewed']
</code>```

EDIT: Essentially I need something like this

```<code>Request Added           x           x
Request Viewed                 x
Request Accepted               x    x
                    January, Feb, March
</code>```

Basically a copy of this: https://answers.splunk.com/answers/85938/scatter-plot-with-non-numeric-y-values.html

Which also suggests to map against an array, but the callback in Y-ticks makes no freaking sense.. ? As i add labelY : [1,2,3,4,5,6] The Third argument of callback "values" is equal to [-2-1 0 1 2].

答:
In order to use a category scale for both the X and Y axis, you must use the traditional data format of an array of values.  Per the chart.js api docs...

Scatter line charts can be created by changing the X axis to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties

This implies that you can only use the data format {x: ' ', y: ' '} when at least the X axis is a linear scale (but I'm betting it only works if both the X and Y axis are linear).

Since you are limited to only using an array of values for your data, you must use at least 2 datasets in order to plot multiple values on the X axis (like what you are trying to do).

Here is a chart configuration that gives what you are looking for.

```<code>var ctx = document.getElementById("canvas").getContext("2d");
var myLine = new Chart(ctx, {
  type: 'line',
  data: {
    xLabels: ["January", "February", "March", "April", "May", "June", "July"],
    yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
    datasets: [{
      label: "My First dataset",
      data: ['Request Added', 'Request Viewed', 'Request Added'],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }, {
      label: "My First dataset",
      data: [null, 'Request Accepted', 'Request Accepted'],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }]
  },
  options: {
    responsive: true,
    title:{
      display: true,
      text: 'Chart.js - Non Numeric X and Y Axis'
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Month'
        }
      }],
      yAxes: [{
        type: 'category',
        position: 'left',
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Request State'
        },
        ticks: {
          reverse: true
        },
      }]
    }
  }
});
</code>```

You can see what it looks like from this codepen.

If you are for whatever reason tied to using the {x: ' ', y: ' '} dataformat, then you will have to change both your scales to linear, map your data to numerical values, then use the ticks.callback property to map your numerical ticks back to string values.

Here is an example that demonstrates this approach.

```<code>var xMap = ["January", "February", "March", "April", "May", "June", "July"];
var yMap = ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'];

var mapDataPoint = function(xValue, yValue) {
  return {
    x: xMap.indexOf(xValue),
    y: yMap.indexOf(yValue)
  };
};

var ctx2 = document.getElementById("canvas2").getContext("2d");
var myLine2 = new Chart(ctx2, {
  type: 'line',
  data: {
    datasets: [{
      label: "My First dataset",
      data: [
        mapDataPoint("January", "Request Added"),
        mapDataPoint("February", "Request Viewed"),
        mapDataPoint("February", "Request Accepted"),
        mapDataPoint("March", "Request Added"),
        mapDataPoint("March", "Request Accepted"),
      ],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js - Scatter Chart Mapping X and Y to Non Numeric'
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Month'
        },
        ticks: {
          min: 0,
          max: xMap.length - 1,
          callback: function(value) {
            return xMap[value];
          },
        },
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Request State'
        },
        ticks: {
          reverse: true,
          min: 0,
          max: yMap.length - 1,
          callback: function(value) {
            return yMap[value];
          },
        },
      }]
    }
  }
});
</code>```

You can see this in action at the same codepen.

ContentLicense: CC BY-SA 4.0

Title: ChartJS: Mapping Non numeric Y and X

Body:
I'm trying to map non numeric y and x and for some reason it does not work.

E.g.

xLabels: ["January", "February", "March", "April", "May", "June", "July"],
yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],

And when i try to change:

data: ['Request Added', 'Request Viewed']

with

data: [{x: "January", y: 'Request Added'}, ...]

Graph does not show a thing

Also i tried to use scales.yAxis.ticks.callback to modify and map against an array but that didnt work out either.

[0: 'Request Added', 1: 'Request Viewed']

EDIT: Essentially I need something like this

Request Added           x           x
Request Viewed                 x
Request Accepted               x    x
                    January, Feb, March

Basically a copy of this: https://answers.splunk.com/answers/85938/scatter-plot-with-non-numeric-y-values.html

Which also suggests to map against an array, but the callback in Y-ticks makes no freaking sense.. ? As i add labelY : [1,2,3,4,5,6] The Third argument of callback "values" is equal to [-2-1 0 1 2].

Body:
In order to use a category scale for both the X and Y axis, you must use the traditional data format of an array of values.  Per the chart.js api docs...

Scatter line charts can be created by changing the X axis to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties

This implies that you can only use the data format {x: ' ', y: ' '} when at least the X axis is a linear scale (but I'm betting it only works if both the X and Y axis are linear).

Since you are limited to only using an array of values for your data, you must use at least 2 datasets in order to plot multiple values on the X axis (like what you are trying to do).

Here is a chart configuration that gives what you are looking for.

var ctx = document.getElementById("canvas").getContext("2d");
var myLine = new Chart(ctx, {
  type: 'line',
  data: {
    xLabels: ["January", "February", "March", "April", "May", "June", "July"],
    yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
    datasets: [{
      label: "My First dataset",
      data: ['Request Added', 'Request Viewed', 'Request Added'],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }, {
      label: "My First dataset",
      data: [null, 'Request Accepted', 'Request Accepted'],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }]
  },
  options: {
    responsive: true,
    title:{
      display: true,
      text: 'Chart.js - Non Numeric X and Y Axis'
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Month'
        }
      }],
      yAxes: [{
        type: 'category',
        position: 'left',
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Request State'
        },
        ticks: {
          reverse: true
        },
      }]
    }
  }
});

You can see what it looks like from this codepen.

If you are for whatever reason tied to using the {x: ' ', y: ' '} dataformat, then you will have to change both your scales to linear, map your data to numerical values, then use the ticks.callback property to map your numerical ticks back to string values.

Here is an example that demonstrates this approach.

var xMap = ["January", "February", "March", "April", "May", "June", "July"];
var yMap = ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'];

var mapDataPoint = function(xValue, yValue) {
  return {
    x: xMap.indexOf(xValue),
    y: yMap.indexOf(yValue)
  };
};

var ctx2 = document.getElementById("canvas2").getContext("2d");
var myLine2 = new Chart(ctx2, {
  type: 'line',
  data: {
    datasets: [{
      label: "My First dataset",
      data: [
        mapDataPoint("January", "Request Added"),
        mapDataPoint("February", "Request Viewed"),
        mapDataPoint("February", "Request Accepted"),
        mapDataPoint("March", "Request Added"),
        mapDataPoint("March", "Request Accepted"),
      ],
      fill: false,
      showLine: false,
      borderColor: chartColors.red,
      backgroundColor: chartColors.red
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js - Scatter Chart Mapping X and Y to Non Numeric'
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Month'
        },
        ticks: {
          min: 0,
          max: xMap.length - 1,
          callback: function(value) {
            return xMap[value];
          },
        },
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Request State'
        },
        ticks: {
          reverse: true,
          min: 0,
          max: yMap.length - 1,
          callback: function(value) {
            return yMap[value];
          },
        },
      }]
    }
  }
});

You can see this in action at the same codepen.


问:
Combining one or more characters (`+?`) and positive lookahead (?=)
I have a string like this:

```<code>"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",
</code>```

I want to match the first double quote in this part:

```<code>"resourceType":
</code>```

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

```<code>".+?
</code>```

and then I want to add positive lookahead part ?=":

```<code>".+??=":
</code>```

but I get syntax error. What's the syntax for combining them?

答:
This is what you need. Use a lookahead group. The group is part of the syntax for lookahead.

```<code>".+?(?=")
</code>```

Here's a good link that describes lookahead. http://www.regular-expressions.info/lookaround.html

UPDATE: remove extraneous suggestion, add comments to explanation.

Body:
I have a string like this:

"resourceType": "com.bmc.arsys.rx.services.view.domain.ContainerViewComponentDefinition",

I want to match the first double quote in this part:

"resourceType":

So I construct a regexp to find ", then one or more characters (greedy) followed by ": literals, so I have the first part:

".+?

and then I want to add positive lookahead part ?=":

".+??=":

but I get syntax error. What's the syntax for combining them?

Body:
This is what you need. Use a lookahead group. The group is part of the syntax for lookahead.

".+?(?=")

Here's a good link that describes lookahead. http://www.regular-expressions.info/lookaround.html

UPDATE: remove extraneous suggestion, add comments to explanation.


问:
bcp_init rturns access violation
I am trying to do bulk copy in sql server using odbc in c++.
here is my code:

```<code>#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <odbcss.h>
#include<tchar.h>

SQLHENV henv = SQL_NULL_HENV;
HDBC hdbc1 = SQL_NULL_HDBC, hdbc2 = SQL_NULL_HDBC;
SQLHSTMT hstmt2 = SQL_NULL_HSTMT;

void Cleanup() {
   if (hstmt2 != SQL_NULL_HSTMT)
      SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);

   if (hdbc1 != SQL_NULL_HDBC) {
      SQLDisconnect(hdbc1);
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
   }

   if (hdbc2 != SQL_NULL_HDBC) {
      SQLDisconnect(hdbc2);
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc2);
   }

   if (henv != SQL_NULL_HENV)
      SQLFreeHandle(SQL_HANDLE_ENV, henv);
}
void HandleDiagnosticRecord (SQLHANDLE      hHandle,
                             SQLSMALLINT    hType,
                             RETCODE        RetCode)
{
    SQLSMALLINT iRec = 0;
    SQLINTEGER  iError;
    WCHAR       wszMessage[1000];
    WCHAR       wszState[SQL_SQLSTATE_SIZE+1];

    if (RetCode == SQL_INVALID_HANDLE)
    {
        fwprintf(stderr, L"Invalid handle!\n");
        return;
    }

    while (SQLGetDiagRec(hType,
                         hHandle,
                         ++iRec,
                         wszState,
                         &iError,
                         wszMessage,
                         (SQLSMALLINT)(sizeof(wszMessage) / sizeof(WCHAR)),
                         (SQLSMALLINT *)NULL) == SQL_SUCCESS)
    {
        // Hide data truncated..
        if (wcsncmp(wszState, L"01004", 5))
        {
            fwprintf(stderr, L"[%5.5s] %s (%d)\n", wszState, wszMessage, iError);
        }
    }

}

#define TRYODBC(h, ht, x)   {   RETCODE rc = x;\
                             if (rc != SQL_SUCCESS) \
                                { \
                                    HandleDiagnosticRecord (h, ht, rc); \
                                } \
                                if (rc == SQL_ERROR) \
                                { \
                                    fwprintf(stderr, L"Error in " L#x L"\n"); \
                                    Sleep(30000); \
                                }  \
                            }

void extract_error(
      char *fn,
      SQLHANDLE handle,
      SQLSMALLINT type)
  {
    SQLINTEGER i = 0;
    SQLINTEGER native;
    SQLWCHAR state[ 7 ];
    SQLWCHAR text[256];
    SQLSMALLINT len;
    SQLRETURN ret;
    fprintf(stderr,
            "\n"
            "The driver reported the following diagnostics whilst running "
            "%s\n\n",
            fn);

    do
    {
      ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
      sizeof(text), &len );
      if (SQL_SUCCEEDED(ret))
      printf("%s:%ld:%ld:%s\n", state, i, native, text);
    }
    while( ret == SQL_SUCCESS );
  }

int main() {
   RETCODE retcode;

   // BCP variables.
   char *terminator = "\0";

   // bcp_done takes a different format return code because it returns number of rows bulk copied
   // after the last bcp_batch call.
   DBINT cRowsDone = 0;

   // Set up separate return code for bcp_sendrow so it is not using the same retcode as SQLFetch.
   RETCODE SendRet;

   // Allocate the ODBC environment and save handle.
   retcode = SQLAllocHandle (SQL_HANDLE_ENV, NULL, &henv);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLAllocHandle(Env) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Notify ODBC that this is an ODBC 3.0 app.
   retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLSetEnvAttr(ODBC version) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Allocate ODBC connection handle, set bulk copy mode, and connect.
   retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLAllocHandle(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   retcode = SQLSetConnectAttr(hdbc1, SQL_COPT_SS_BCP, (void *)SQL_BCP_ON, SQL_IS_INTEGER);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLSetConnectAttr(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   // sample uses Integrated Security, create the SQL Server DSN using Windows NT authentication
   SQLWCHAR dsn[30] = L"mssqltest"; //Name DNS
   SQLWCHAR user[10] = L"di_test";
   SQLWCHAR pass[10] = L"di_test";
   SQLWCHAR tb[20]=L"information1";

   retcode = SQLConnectW(hdbc1, (SQLWCHAR *)dsn, SQL_NTS, (SQLWCHAR *) user, SQL_NTS, (SQLWCHAR *) pass, SQL_NTS);
   if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) {
      printf("SQLConnect() Failed\n\n");
      Cleanup();
      return(9);
   }
    //  TRYODBC(hdbc1, SQL_HANDLE_DBC, retcode);
   // Initialize the bulk copy.

   retcode = bcp_init(hdbc1,L"information1", NULL, NULL, DB_IN);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_init(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   //Define our array
   SQLINTEGER custIDs[] = { 1, 2, 3, 4};

   // Bind the program variables for the bulk copy.
   retcode = bcp_bind(hdbc1, (BYTE *)custIDs[0], 4, SQL_VARLEN_DATA, NULL, (INT)NULL, SQLINT4, 2);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_bind(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Could normally use strlen to calculate the bcp_bind cbTerm parameter, but this terminator
   // is a null byte (\0), which gives strlen a value of 0. Explicitly give cbTerm a value of 1.
   retcode = bcp_bind(hdbc1, (BYTE *)custIDs[0], 4, SQL_VARLEN_DATA, NULL, (INT)NULL, SQLINT4, 3);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_bind(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   if ( (SendRet = bcp_sendrow(hdbc1) ) != SUCCEED ) {
         printf("bcp_sendrow(hdbc1) Failed\n\n");
         Cleanup();
         return(9);
      }

   cRowsDone = bcp_done(hdbc1);
   if ( (cRowsDone == -1) ) {
      printf("bcp_done(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   printf("Number of rows bulk copied after last bcp_batch call = %d.\n", cRowsDone);

   // Cleanup.
   SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);
   SQLDisconnect(hdbc1);
   SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
   SQLDisconnect(hdbc2);
   SQLFreeHandle(SQL_HANDLE_DBC, hdbc2);
   SQLFreeHandle(SQL_HANDLE_ENV, henv);
   }
</code>```

in the line:

```<code>   retcode = bcp_init(hdbc1,L"information1", NULL, NULL, DB_IN);
</code>```

I get an exception which says, access violation. I recieve no error but an exception.
Does anyone know how should I solve this problem?

答:
I've been using bcp_xxxx functions since 12-15 years in one win32 program. That program was compiled on VS6 and is still on production today.

I recently rewrote the project on VS2015 (finally…). And I had issues with bcp_xxxx functions like you too.

The original VS6 program had these files included:

```<code>#include <sql.h>
#include <sqlext.h>
#include "C:\Program Files\Microsoft SQL Server\80\Tools\DevTools\Include\odbcss.h"
</code>```

SQLDriverConnect() function was used with a connection string containing Driver=SQL Server.

The odbcbcp.lib was added to the linker libraries list. No issues.

The program has been completely revisited for  VS2015, changing when appropriate ODBC functions to their version 3.x, and allowing 32 or 64 bit binaries with UNICODE or ANSI charsets.

Recent documentation suggests to use sqlncli.h header and sqlncli11.lib when using bcp_xxxx functions:

```<code>#include <sql.h>
#include <sqlext.h>
#define _SQLNCLI_ODBC_
#ifdef _WIN64
#include "C:\Program Files\Microsoft SQL Server\110\SDK\Include\sqlncli.h"
#else
#include "C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Include\sqlncli.h"
#endif
</code>```

I did it like suggested, and... crash.

I then linked back to odbcbcp.lib, and it works like a charm.

So, I started to search how to use sqlncli11.lib and I found the ODBC connection string should contain Driver=SQL Server Native Client 11.0.

In brief:

- (1) Driver=SQL Server with odbcbcp.lib works

- (2) Driver=SQL Server with sqlncli11.lib makes bcp_init() to crash

- (3) Driver=SQL Server Native Client 11.0 with odbcbcp.lib makes bcp_init() to fail (it returns FAIL=0)

- (4) Driver=SQL Server Native Client 11.0 with sqlncli11.lib works.

Options (1) and (4) are working.

But I found too that using option (4) allows queries to run significantly faster !

So I’ll keep that last one.

Hope this helps.

Title: bcp_init rturns access violation

Body:
I am trying to do bulk copy in sql server using odbc in c++.
here is my code:

#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <odbcss.h>
#include<tchar.h>

SQLHENV henv = SQL_NULL_HENV;
HDBC hdbc1 = SQL_NULL_HDBC, hdbc2 = SQL_NULL_HDBC;
SQLHSTMT hstmt2 = SQL_NULL_HSTMT;

void Cleanup() {
   if (hstmt2 != SQL_NULL_HSTMT)
      SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);

   if (hdbc1 != SQL_NULL_HDBC) {
      SQLDisconnect(hdbc1);
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
   }

   if (hdbc2 != SQL_NULL_HDBC) {
      SQLDisconnect(hdbc2);
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc2);
   }

   if (henv != SQL_NULL_HENV)
      SQLFreeHandle(SQL_HANDLE_ENV, henv);
}
void HandleDiagnosticRecord (SQLHANDLE      hHandle,
                             SQLSMALLINT    hType,
                             RETCODE        RetCode)
{
    SQLSMALLINT iRec = 0;
    SQLINTEGER  iError;
    WCHAR       wszMessage[1000];
    WCHAR       wszState[SQL_SQLSTATE_SIZE+1];

    if (RetCode == SQL_INVALID_HANDLE)
    {
        fwprintf(stderr, L"Invalid handle!\n");
        return;
    }

    while (SQLGetDiagRec(hType,
                         hHandle,
                         ++iRec,
                         wszState,
                         &iError,
                         wszMessage,
                         (SQLSMALLINT)(sizeof(wszMessage) / sizeof(WCHAR)),
                         (SQLSMALLINT *)NULL) == SQL_SUCCESS)
    {
        // Hide data truncated..
        if (wcsncmp(wszState, L"01004", 5))
        {
            fwprintf(stderr, L"[%5.5s] %s (%d)\n", wszState, wszMessage, iError);
        }
    }

}

#define TRYODBC(h, ht, x)   {   RETCODE rc = x;\
                             if (rc != SQL_SUCCESS) \
                                { \
                                    HandleDiagnosticRecord (h, ht, rc); \
                                } \
                                if (rc == SQL_ERROR) \
                                { \
                                    fwprintf(stderr, L"Error in " L#x L"\n"); \
                                    Sleep(30000); \
                                }  \
                            }

void extract_error(
      char *fn,
      SQLHANDLE handle,
      SQLSMALLINT type)
  {
    SQLINTEGER i = 0;
    SQLINTEGER native;
    SQLWCHAR state[ 7 ];
    SQLWCHAR text[256];
    SQLSMALLINT len;
    SQLRETURN ret;
    fprintf(stderr,
            "\n"
            "The driver reported the following diagnostics whilst running "
            "%s\n\n",
            fn);

    do
    {
      ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
      sizeof(text), &len );
      if (SQL_SUCCEEDED(ret))
      printf("%s:%ld:%ld:%s\n", state, i, native, text);
    }
    while( ret == SQL_SUCCESS );
  }

int main() {
   RETCODE retcode;

   // BCP variables.
   char *terminator = "\0";

   // bcp_done takes a different format return code because it returns number of rows bulk copied
   // after the last bcp_batch call.
   DBINT cRowsDone = 0;

   // Set up separate return code for bcp_sendrow so it is not using the same retcode as SQLFetch.
   RETCODE SendRet;

   // Allocate the ODBC environment and save handle.
   retcode = SQLAllocHandle (SQL_HANDLE_ENV, NULL, &henv);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLAllocHandle(Env) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Notify ODBC that this is an ODBC 3.0 app.
   retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLSetEnvAttr(ODBC version) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Allocate ODBC connection handle, set bulk copy mode, and connect.
   retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLAllocHandle(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   retcode = SQLSetConnectAttr(hdbc1, SQL_COPT_SS_BCP, (void *)SQL_BCP_ON, SQL_IS_INTEGER);
   if ( (retcode != SQL_SUCCESS_WITH_INFO) && (retcode != SQL_SUCCESS)) {
      printf("SQLSetConnectAttr(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   // sample uses Integrated Security, create the SQL Server DSN using Windows NT authentication
   SQLWCHAR dsn[30] = L"mssqltest"; //Name DNS
   SQLWCHAR user[10] = L"di_test";
   SQLWCHAR pass[10] = L"di_test";
   SQLWCHAR tb[20]=L"information1";

   retcode = SQLConnectW(hdbc1, (SQLWCHAR *)dsn, SQL_NTS, (SQLWCHAR *) user, SQL_NTS, (SQLWCHAR *) pass, SQL_NTS);
   if ( (retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO) ) {
      printf("SQLConnect() Failed\n\n");
      Cleanup();
      return(9);
   }
    //  TRYODBC(hdbc1, SQL_HANDLE_DBC, retcode);
   // Initialize the bulk copy.

   retcode = bcp_init(hdbc1,L"information1", NULL, NULL, DB_IN);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_init(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   //Define our array
   SQLINTEGER custIDs[] = { 1, 2, 3, 4};

   // Bind the program variables for the bulk copy.
   retcode = bcp_bind(hdbc1, (BYTE *)custIDs[0], 4, SQL_VARLEN_DATA, NULL, (INT)NULL, SQLINT4, 2);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_bind(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   // Could normally use strlen to calculate the bcp_bind cbTerm parameter, but this terminator
   // is a null byte (\0), which gives strlen a value of 0. Explicitly give cbTerm a value of 1.
   retcode = bcp_bind(hdbc1, (BYTE *)custIDs[0], 4, SQL_VARLEN_DATA, NULL, (INT)NULL, SQLINT4, 3);
   if ( (retcode != SUCCEED) ) {
      printf("bcp_bind(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   if ( (SendRet = bcp_sendrow(hdbc1) ) != SUCCEED ) {
         printf("bcp_sendrow(hdbc1) Failed\n\n");
         Cleanup();
         return(9);
      }

   cRowsDone = bcp_done(hdbc1);
   if ( (cRowsDone == -1) ) {
      printf("bcp_done(hdbc1) Failed\n\n");
      Cleanup();
      return(9);
   }

   printf("Number of rows bulk copied after last bcp_batch call = %d.\n", cRowsDone);

   // Cleanup.
   SQLFreeHandle(SQL_HANDLE_STMT, hstmt2);
   SQLDisconnect(hdbc1);
   SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
   SQLDisconnect(hdbc2);
   SQLFreeHandle(SQL_HANDLE_DBC, hdbc2);
   SQLFreeHandle(SQL_HANDLE_ENV, henv);
   }

in the line:

   retcode = bcp_init(hdbc1,L"information1", NULL, NULL, DB_IN);

I get an exception which says, access violation. I recieve no error but an exception.
Does anyone know how should I solve this problem?

Body:
I've been using bcp_xxxx functions since 12-15 years in one win32 program. That program was compiled on VS6 and is still on production today.

I recently rewrote the project on VS2015 (finally…). And I had issues with bcp_xxxx functions like you too.

The original VS6 program had these files included:

#include <sql.h>
#include <sqlext.h>
#include "C:\Program Files\Microsoft SQL Server\80\Tools\DevTools\Include\odbcss.h"

SQLDriverConnect() function was used with a connection string containing Driver=SQL Server.

The odbcbcp.lib was added to the linker libraries list. No issues.

The program has been completely revisited for  VS2015, changing when appropriate ODBC functions to their version 3.x, and allowing 32 or 64 bit binaries with UNICODE or ANSI charsets.

Recent documentation suggests to use sqlncli.h header and sqlncli11.lib when using bcp_xxxx functions:

#include <sql.h>
#include <sqlext.h>
#define _SQLNCLI_ODBC_
#ifdef _WIN64
#include "C:\Program Files\Microsoft SQL Server\110\SDK\Include\sqlncli.h"
#else
#include "C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Include\sqlncli.h"
#endif

I did it like suggested, and... crash.

I then linked back to odbcbcp.lib, and it works like a charm.

So, I started to search how to use sqlncli11.lib and I found the ODBC connection string should contain Driver=SQL Server Native Client 11.0.

In brief:

- (1) Driver=SQL Server with odbcbcp.lib works

- (2) Driver=SQL Server with sqlncli11.lib makes bcp_init() to crash

- (3) Driver=SQL Server Native Client 11.0 with odbcbcp.lib makes bcp_init() to fail (it returns FAIL=0)

- (4) Driver=SQL Server Native Client 11.0 with sqlncli11.lib works.

Options (1) and (4) are working.

But I found too that using option (4) allows queries to run significantly faster !

So I’ll keep that last one.

Hope this helps.


问:
TimeSpan property in Azure Table Storage
I have an entity with a TimeSpan property I want to save in Azure Table Storage. When I attempt to save the entity I get the error:

Can't cast to unsupported type 'TimeSpan'

Is there some way to do an automatic conversion or some other way to support TimeSpan?

答:
In order to store a TimeSpan into a CloudTable, I'm using a long property that does the translation with the TimeSpan property:

```<code>public class MyEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
{
    public TimeSpan MyDuration { get; set; }

    // Workaround the fact that TableEntity does not automatically store a `TimeSpan`
    public long MyDurationTicks
    {
        get { return MyDuration.Ticks; }
        set { MyDuration = TimeSpan.FromTicks(value); }
    }
}
</code>```

Body:
In order to store a TimeSpan into a CloudTable, I'm using a long property that does the translation with the TimeSpan property:

public class MyEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
{
    public TimeSpan MyDuration { get; set; }

    // Workaround the fact that TableEntity does not automatically store a `TimeSpan`
    public long MyDurationTicks
    {
        get { return MyDuration.Ticks; }
        set { MyDuration = TimeSpan.FromTicks(value); }
    }
}


问:
QT Creator:how to change the menu font size?
I use QT Creator on surface pro4 and the font of menu is too small:

what should i do to change the font size?

version:5.5

答:
There is no such option. You have to modify the DPI scaling of windows, which will make all "legacy" shell applications appear larger to compensate for the high DPI of the device.

If you don't want to modify the settings, you might want to try running creator with an QT_SCALE_FACTOR=2 env var or so.

Create a startScaled.cmd in creator's exe directory with the content:

```<code>@echo off
set QT_SCALE_FACTOR=2
qtcreator.exe
</code>```

And use this to start creator up-scaled.

Body:
There is no such option. You have to modify the DPI scaling of windows, which will make all "legacy" shell applications appear larger to compensate for the high DPI of the device.

If you don't want to modify the settings, you might want to try running creator with an QT_SCALE_FACTOR=2 env var or so.

Create a startScaled.cmd in creator's exe directory with the content:

@echo off
set QT_SCALE_FACTOR=2
qtcreator.exe

And use this to start creator up-scaled.


问:
Schedule a job in Unix
I am pretty new to Unix environment.

I am trying to schedule two tasks in Unix server. The second task is dependent on the result of the first task. So, I want to run the first task. If there is no error then I want the second task to run automatically. But if the first task fails, I want to reschedule the first task again after 30 minutes.

I have no idea where to start from.

答:
You don't need cron for this. A simple shell script is all you need:

#!/bin/sh

while :; do             # Loop until the break statement is hit
   if task1; then       # If task1 is successful
      task2             # then run task2
      break             # and we're done.
   else                 # otherwise task1 failed
      sleep 1800        # and we wait 30min
   fi                   # repeat
done
```

<p>Note that <code>task1</code> must indicate <em>success</em> with an exit status of 0, and failure with nonzero.</p>

<p>As Wumpus sharply observes, this can be simplified to</p>

<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
until task1; do
   sleep 1800
done
task2
</code>```

Title: Schedule a job in Unix

Body:
You don't need cron for this. A simple shell script is all you need:

#!/bin/sh

while :; do             # Loop until the break statement is hit
   if task1; then       # If task1 is successful
      task2             # then run task2
      break             # and we're done.
   else                 # otherwise task1 failed
      sleep 1800        # and we wait 30min
   fi                   # repeat
done

Note that task1 must indicate success with an exit status of 0, and failure with nonzero.

As Wumpus sharply observes, this can be simplified to

#!/bin/sh
until task1; do
   sleep 1800
done
task2


问:
Consuming an AJAX Enabled REST Service From Another Project
I have an AJAX Enabled REST Web Service self hosted at http://localhost/machinename/ and a test project running at http://localhost:59103/ hosted on a .NET Development Server.  I've added my script reference to my test project and referenced the js ( http://localhost/machinename/js/ ) however, when the REST calls are invoked, it keeps trying to call http://localhost:59103/machinename/Method/, which doesn't exist because that's not where my service is hosted, and it's not where I'm telling it my service exists.

My question is 2 fold:

Why doesn't it call out to the correct endpoint?

Can I make it call out to the correct endpoint?

答:
I think this has to do with the JavaScript sandbox security model, where JS is only allowed to issue requests to the origin server from which the page (not the JS script!) was loaded. This seems to happen in your case: The host identifier is stripped out of the URI.

This is a known issue, of course. You might want to look at JSONP as one possible way around this.


问:
How to draw Gson model for this difficult json (mapping RUB,USD,EUR to map)?
```<code>{
  "page": 1,
  "pages": 1,
  "rows": [
    {
      "context": false,
      "created": 1490782661,
      "RUB": {
        "currency": "RUB",
        "created": 1490761924,
        "rate_buy": 5.53,
        "rate_sell": 5.57,
        "context": false
      },
      "EUR": {
        "currency": "EUR",
        "created": 1490770163,
        "rate_buy": 340,
        "rate_sell": 342,
        "context": false
      },
      "USD": {
        "currency": "USD",
        "created": 1490782661,
        "rate_buy": 315.3,
        "rate_sell": 316.1,
        "context": false
      }
    },
    {
      "context": false,
      "created": 1490779161,
      "RUB": {
        "currency": "RUB",
        "created": 1490761924,
        "rate_buy": 5.53,
        "rate_sell": 5.57,
        "context": false
      },
      "EUR": {
        "currency": "EUR",
        "created": 1490770163,
        "rate_buy": 340,
        "rate_sell": 342,
        "context": false
      },
      "USD": {
        "currency": "USD",
        "created": 1490779161,
        "rate_buy": 315.1,
        "rate_sell": 315.9,
        "context": false
      }
    },
    {
      "context": false,
      "created": 1490772405,
      "RUB": {
        "currency": "RUB",
        "created": 1490761924,
        "rate_buy": 5.53,
        "rate_sell": 5.57,
        "context": false
      },
      "EUR": {
        "currency": "EUR",
        "created": 1490770163,
        "rate_buy": 340,
        "rate_sell": 342,
        "context": false
      },
      "USD": {
        "currency": "USD",
        "created": 1490772405,
        "rate_buy": 314.9,
        "rate_sell": 315.7,
        "context": false
      }
    }
  ],
  "total": "132"
}
</code>```

答:
Don't always trust automatic by-schema generators as they cannot generate robust and efficient mappings for non-trivial cases. Thus, the suggested online tool that's extremely popular here cannot generate a good mapping as well due to at least:

The top-most JSON object looks like a generic server response, so it can be parameterized.

The dates in the JSON document are represented in Unix epoch style, so it would be an int or long from that tool point of view.

The currency names will be hardcoded as fields, so you'll be bound to 3 currencies unless you're going enhance the mappings, but still losing Map flexibility.

First off, let's define the mappings:

final class Response<T> {

    // Note a few things:
    // - Gson can deserialize final fields, and these are incoming data supposed to be read-only
    // - There are no getters for brevity, these are just incoming data bags anyway
    // - If `final`, primitive types like `int` should not be initialized with `0` (javac inlines such constants)
    //   so we're cheating making them look like constants...
    @SerializedName("page") final int page = Integer.valueOf(0);
    @SerializedName("pages") final int pages = Integer.valueOf(0);
    @SerializedName("rows") final List<T> rows = null;
    @SerializedName("total") final int total = Integer.valueOf(0);

}
```

<p>Unlike the previous class, the <code>Rate</code> class cannot be deserialized using the reflection strategy where Gson is usually is at its best. The class has a constructor so we can instantiate it ourselves:</p>

<pre class="lang-java prettyprint-override"><code>final class Rate {

    final boolean context;
    final Date created;
    final Map<String, Currency> currencies;

    Rate(final boolean context, final Date created, final Map<String, Currency> currencies) {
        this.context = context;
        this.created = created;
        this.currencies = currencies;
    }

}
</code>```

final class Currency {

    @SerializedName("currency") final String currency = null;
    @SerializedName("created") final Date created = null;
    @SerializedName("rate_buy") final double rateBuy = Double.valueOf(0);
    @SerializedName("rate_sell") final double rateSell = Double.valueOf(0);
    @SerializedName("context") final boolean context = Boolean.valueOf(false);

}
```

<p>Next, two deserializers are needed: for dates and rates.</p>

<pre class="lang-java prettyprint-override"><code>final class DateJsonDeserializer
        implements JsonDeserializer<Date> {

    // No state? So it can be a singleton
    private static final JsonDeserializer<Date> dateJsonDeserializer = new DateJsonDeserializer();

    private DateJsonDeserializer() {
    }

    // But not letting client code know if it's a singleton or not -- it's encapsulated
    static JsonDeserializer<Date> getDateJsonDeserializer() {
        return dateJsonDeserializer;
    }

    @Override
    public Date deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        // jsonElement.getAsLong() would work either
        // But even longs can have their own deserialization strategy
        // Note `* 1000` -- `java.util.Date` accepts milliseconds while Unix epoch is "seconds-based"
        return new Date((Long) context.deserialize(jsonElement, long.class) * 1000);
    }

}
</code>```

final class RateJsonDeserializer
        implements JsonDeserializer<Rate> {

    private static final JsonDeserializer<Rate> rateJsonDeserializer = new RateJsonDeserializer();

    private RateJsonDeserializer() {
    }

    static JsonDeserializer<Rate> getRateJsonDeserializer() {
        return rateJsonDeserializer;
    }

    @Override
    public Rate deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        final JsonObject jsonObject = jsonElement.getAsJsonObject();
        boolean rateContext = false;
        Date rateCreated = null;
        final Map<String, Currency> rateCurrencies = new LinkedHashMap<>();
        // Analyzing rate JSON documents for each key/value pair
        for ( final Entry<String, JsonElement> entry : jsonObject.entrySet() ) {
            final String key = entry.getKey();
            final JsonElement value = entry.getValue();
            switch ( key ) {
            case "context":
                rateContext = context.deserialize(value, boolean.class);
                break;
            case "created":
                rateCreated = context.deserialize(value, Date.class);
                break;
            default:
                rateCurrencies.put(key, context.deserialize(value, Currency.class));
                break;
            }
        }
        // So that we can "unwrap" its layout and "flatten" the currencies map
        return new Rate(rateContext, rateCreated, rateCurrencies);
    }

}
```

<p>Now, the way it's used:</p>

```private static final TypeToken<Response<Rate>> currencyRatesResponseTypeToken = new TypeToken<Response<Rate>>() {
};

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, getDateJsonDeserializer())
        .registerTypeAdapter(Rate.class, getRateJsonDeserializer())
        .create();

public static void main(final String... args) {
    final Response<Rate> response = gson.fromJson(JSON, currencyRatesResponseTypeToken.getType());
    System.out.println(response.page + "/" + response.pages + " (" + response.total + ")");
    for ( final Rate rate : response.rows ) {
        System.out.println(rate.created);
        for ( final Entry<String, Currency> entry : rate.currencies.entrySet() ) {
            final Currency currency = entry.getValue();
            System.out.println("* " + entry.getKey() + " <== " + currency.currency + " (" + currency.rateBuy + "/" + currency.rateSell + ") " + currency.created);
        }
    }
}
```

The demo output:

1/1 (132)

  Wed Mar 29 13:17:41 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (315.3/316.1) Wed Mar 29 13:17:41 EEST 2017

  Wed Mar 29 12:19:21 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (315.1/315.9) Wed Mar 29 12:19:21 EEST 2017

  Wed Mar 29 10:26:45 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (314.9/315.7) Wed Mar 29 10:26:45 EEST 2017

Body:
Don't always trust automatic by-schema generators as they cannot generate robust and efficient mappings for non-trivial cases. Thus, the suggested online tool that's extremely popular here cannot generate a good mapping as well due to at least:

The top-most JSON object looks like a generic server response, so it can be parameterized.

The dates in the JSON document are represented in Unix epoch style, so it would be an int or long from that tool point of view.

The currency names will be hardcoded as fields, so you'll be bound to 3 currencies unless you're going enhance the mappings, but still losing Map flexibility.

First off, let's define the mappings:

final class Response<T> {

    // Note a few things:
    // - Gson can deserialize final fields, and these are incoming data supposed to be read-only
    // - There are no getters for brevity, these are just incoming data bags anyway
    // - If `final`, primitive types like `int` should not be initialized with `0` (javac inlines such constants)
    //   so we're cheating making them look like constants...
    @SerializedName("page") final int page = Integer.valueOf(0);
    @SerializedName("pages") final int pages = Integer.valueOf(0);
    @SerializedName("rows") final List<T> rows = null;
    @SerializedName("total") final int total = Integer.valueOf(0);

}

Unlike the previous class, the Rate class cannot be deserialized using the reflection strategy where Gson is usually is at its best. The class has a constructor so we can instantiate it ourselves:

final class Rate {

    final boolean context;
    final Date created;
    final Map<String, Currency> currencies;

    Rate(final boolean context, final Date created, final Map<String, Currency> currencies) {
        this.context = context;
        this.created = created;
        this.currencies = currencies;
    }

}

final class Currency {

    @SerializedName("currency") final String currency = null;
    @SerializedName("created") final Date created = null;
    @SerializedName("rate_buy") final double rateBuy = Double.valueOf(0);
    @SerializedName("rate_sell") final double rateSell = Double.valueOf(0);
    @SerializedName("context") final boolean context = Boolean.valueOf(false);

}

Next, two deserializers are needed: for dates and rates.

final class DateJsonDeserializer
        implements JsonDeserializer<Date> {

    // No state? So it can be a singleton
    private static final JsonDeserializer<Date> dateJsonDeserializer = new DateJsonDeserializer();

    private DateJsonDeserializer() {
    }

    // But not letting client code know if it's a singleton or not -- it's encapsulated
    static JsonDeserializer<Date> getDateJsonDeserializer() {
        return dateJsonDeserializer;
    }

    @Override
    public Date deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        // jsonElement.getAsLong() would work either
        // But even longs can have their own deserialization strategy
        // Note `* 1000` -- `java.util.Date` accepts milliseconds while Unix epoch is "seconds-based"
        return new Date((Long) context.deserialize(jsonElement, long.class) * 1000);
    }

}

final class RateJsonDeserializer
        implements JsonDeserializer<Rate> {

    private static final JsonDeserializer<Rate> rateJsonDeserializer = new RateJsonDeserializer();

    private RateJsonDeserializer() {
    }

    static JsonDeserializer<Rate> getRateJsonDeserializer() {
        return rateJsonDeserializer;
    }

    @Override
    public Rate deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        final JsonObject jsonObject = jsonElement.getAsJsonObject();
        boolean rateContext = false;
        Date rateCreated = null;
        final Map<String, Currency> rateCurrencies = new LinkedHashMap<>();
        // Analyzing rate JSON documents for each key/value pair
        for ( final Entry<String, JsonElement> entry : jsonObject.entrySet() ) {
            final String key = entry.getKey();
            final JsonElement value = entry.getValue();
            switch ( key ) {
            case "context":
                rateContext = context.deserialize(value, boolean.class);
                break;
            case "created":
                rateCreated = context.deserialize(value, Date.class);
                break;
            default:
                rateCurrencies.put(key, context.deserialize(value, Currency.class));
                break;
            }
        }
        // So that we can "unwrap" its layout and "flatten" the currencies map
        return new Rate(rateContext, rateCreated, rateCurrencies);
    }

}

Now, the way it's used:

private static final TypeToken<Response<Rate>> currencyRatesResponseTypeToken = new TypeToken<Response<Rate>>() {
};

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, getDateJsonDeserializer())
        .registerTypeAdapter(Rate.class, getRateJsonDeserializer())
        .create();

public static void main(final String... args) {
    final Response<Rate> response = gson.fromJson(JSON, currencyRatesResponseTypeToken.getType());
    System.out.println(response.page + "/" + response.pages + " (" + response.total + ")");
    for ( final Rate rate : response.rows ) {
        System.out.println(rate.created);
        for ( final Entry<String, Currency> entry : rate.currencies.entrySet() ) {
            final Currency currency = entry.getValue();
            System.out.println("* " + entry.getKey() + " <== " + currency.currency + " (" + currency.rateBuy + "/" + currency.rateSell + ") " + currency.created);
        }
    }
}

The demo output:

1/1 (132)

  Wed Mar 29 13:17:41 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (315.3/316.1) Wed Mar 29 13:17:41 EEST 2017

  Wed Mar 29 12:19:21 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (315.1/315.9) Wed Mar 29 12:19:21 EEST 2017

  Wed Mar 29 10:26:45 EEST 2017

  * RUB <== RUB (5.53/5.57) Wed Mar 29 07:32:04 EEST 2017

  * EUR <== EUR (340.0/342.0) Wed Mar 29 09:49:23 EEST 2017

  * USD <== USD (314.9/315.7) Wed Mar 29 10:26:45 EEST 2017


问:
MPAndroidChart: How do I remove gridlines?
In my LineChart beside the lines that are shown on the full numbers parallel to the x-axis, many horizontal gridlines are shown:

How can I get rid of these lines?

答:
Those look like axis lines. You can toggle the axis lines by calling setDrawGridLines(false) on each Chart axis. For example, to clear all of them simply do something like this.

```<code>LineChart myChart = ...;
myChart.getXAxis().setDrawGridLines(false);
myChart.getAxisLeft().setDrawGridLines(false);
myChart.getAxisRight().setDrawGridLines(false);
</code>```

Body:
Those look like axis lines. You can toggle the axis lines by calling setDrawGridLines(false) on each Chart axis. For example, to clear all of them simply do something like this.

LineChart myChart = ...;
myChart.getXAxis().setDrawGridLines(false);
myChart.getAxisLeft().setDrawGridLines(false);
myChart.getAxisRight().setDrawGridLines(false);


问:
angular 2 login with spring security
im trying to integrate spring security with a custom angular 2 login, that is a specific endpoint of my app is protected with spring security, trying to access it will redirect to /login that is handled in angular 2. as things stands now i have no clue as to how to perform the login and grant access to the backend API once logged.

i am configuring spring security as follows:

```<code>@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .cors().and()
        .authorizeRequests()
        .antMatchers("/api/someEndpoint/**")
        .hasRole(ADMIN_ROLE).and().formLogin()
        .loginPage("/login").and().logout();
}

@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
</code>```

as I had the default login everything worked fine, but I have found myself unable to create a working angular 2 login integration.
I tried the following code in angular 2 to no avail:

```<code>login(loginDetails:Object) {
    console.log(loginDetails)
    const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
const body = JSON.stringify(loginDetails);
    console.log(headers);
    console.log(body);
return this.http.post(this.loginUrl, body, options)
}
</code>```

as far as I know spring security defaults for username and password variable names are "username" and "password", which i am sure are being passed in the request body so when passing some invalid user data like {"username":"admin", "password" : "pass"}I should be redirected to /login?error or something, and when successfully authenticated I should be redirected to /welcome and stay authenticated

I have the user and pass defined in my db and my custom userDetailsService checks against it
 any answers, comments or questions are welcome

答:
Once you're working with an API you've to use the HTTP Basic authentication.
It's also required to use HTTPS to prevent the main-in-middle attack.

To implement HTTP Basic with Angular the login service would look like this:

```<code>login (loginDetails: any): Observable<LoginResponse> { // custom class, may be empty for now

    let headers = new Headers({
      'Authorization': 'Basic ' + btoa(loginDetails.login + ':' + loginDetails.pass),
      'X-Requested-With': 'XMLHttpRequest' // to suppress 401 browser popup
    });

    let options = new RequestOptions({
      headers: headers
    });

    return this.http.post(this.loginUrl, {}, options)
      .catch(e => this.handleError(e)); // handle 401 error - bad credentials
}
</code>```

... then you subscribe this in the caller component:

```<code>loginNow() {
   this
     .loginService
     .login(this.loginDetails)
     .subscribe(next => {
        this.router.navigateByUrl("/"); // login succeed
     }, error => {
        this.error = "Bad credentials"; // or extract smth from <error> object
     });
}
</code>```

Then you can use the loginNow() method inside component templates like (click)="loginNow().

As soon as the server will accept an authorization, JSESSIONID will be stored in your browser automatically because of Spring Security features and you won't be forced to send the credentials each time you access private resources.

Your login server method may look like this:

```<code>@PreAuthorize("hasRole('USER')")
@PostMapping("/login")
public ResponseEntity login() {
    return new ResponseEntity<>(HttpStatus.OK);
}
</code>```

... it would reject with 401 UNAUTHORIZED when the authorization fails or accept with 200 SUCCESS when it's not.

How to setup a server in the proper way there's a number of Spring Security demo projects present: https://github.com/spring-guides/tut-spring-security-and-angular-js

Title: angular 2 login with spring security

Body:
im trying to integrate spring security with a custom angular 2 login, that is a specific endpoint of my app is protected with spring security, trying to access it will redirect to /login that is handled in angular 2. as things stands now i have no clue as to how to perform the login and grant access to the backend API once logged.

i am configuring spring security as follows:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .cors().and()
        .authorizeRequests()
        .antMatchers("/api/someEndpoint/**")
        .hasRole(ADMIN_ROLE).and().formLogin()
        .loginPage("/login").and().logout();
}

@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

as I had the default login everything worked fine, but I have found myself unable to create a working angular 2 login integration.
I tried the following code in angular 2 to no avail:

login(loginDetails:Object) {
    console.log(loginDetails)
    const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
const body = JSON.stringify(loginDetails);
    console.log(headers);
    console.log(body);
return this.http.post(this.loginUrl, body, options)
}

as far as I know spring security defaults for username and password variable names are "username" and "password", which i am sure are being passed in the request body so when passing some invalid user data like {"username":"admin", "password" : "pass"}I should be redirected to /login?error or something, and when successfully authenticated I should be redirected to /welcome and stay authenticated

I have the user and pass defined in my db and my custom userDetailsService checks against it
 any answers, comments or questions are welcome

Body:
Once you're working with an API you've to use the HTTP Basic authentication.
It's also required to use HTTPS to prevent the main-in-middle attack.

To implement HTTP Basic with Angular the login service would look like this:

login (loginDetails: any): Observable<LoginResponse> { // custom class, may be empty for now

    let headers = new Headers({
      'Authorization': 'Basic ' + btoa(loginDetails.login + ':' + loginDetails.pass),
      'X-Requested-With': 'XMLHttpRequest' // to suppress 401 browser popup
    });

    let options = new RequestOptions({
      headers: headers
    });

    return this.http.post(this.loginUrl, {}, options)
      .catch(e => this.handleError(e)); // handle 401 error - bad credentials
}

... then you subscribe this in the caller component:

loginNow() {
   this
     .loginService
     .login(this.loginDetails)
     .subscribe(next => {
        this.router.navigateByUrl("/"); // login succeed
     }, error => {
        this.error = "Bad credentials"; // or extract smth from <error> object
     });
}

Then you can use the loginNow() method inside component templates like (click)="loginNow().

As soon as the server will accept an authorization, JSESSIONID will be stored in your browser automatically because of Spring Security features and you won't be forced to send the credentials each time you access private resources.

Your login server method may look like this:

@PreAuthorize("hasRole('USER')")
@PostMapping("/login")
public ResponseEntity login() {
    return new ResponseEntity<>(HttpStatus.OK);
}

... it would reject with 401 UNAUTHORIZED when the authorization fails or accept with 200 SUCCESS when it's not.

How to setup a server in the proper way there's a number of Spring Security demo projects present: https://github.com/spring-guides/tut-spring-security-and-angular-js


问:
Git ignore whitelisting all files in a subdirectory, recursively
My software project is modular. Some files are committed by the developer under assigned subdirectories, other are uncompressed to provide an environment runtime (web resources) for development and shall not be committed.

```<code>- webapp
   - common (provided)
   - error (provided)
   - secure
      - admin (provided)
      - audit (provided)
      - ftt (provided)
   - WEB-INF (to ignore)
</code>```

I want to ignore everything under webapp except all files under /webapp/secure/ftt and its subdirectories.

I tried

```<code>/webapp
!/webapp/secure/ftt
</code>```

But Git still ignores ftt.

I expect those directories to contain only .jsp and .js files. But I can't know what happens in the future (e.g. gif, pdf, etc)

How can I tell Git to whitelist files under /webapp/secure/ftt and ignore everything else under /webapp?

From my research I found it may be impossible without listing each specific subdirectory and file pattern.

[Add] after @DevDonkey comment I tried to empty my entire gitignore file and leave what he posted

```<code>/webapp/*
!/webapp/secure/ftt
</code>```

Along with plenties of useless files (e.g. .class files) that are now candidate for indexing, because as I said I emptied the gitignore, I find sample.jsp still ignored

答:
how about

```<code>/webapp/*
!/webapp/secure/ftt
</code>```

works for me locally. Note the addition of the slash and wildcard, so git keeps the root folder, but then processes the rest.

Body:
My software project is modular. Some files are committed by the developer under assigned subdirectories, other are uncompressed to provide an environment runtime (web resources) for development and shall not be committed.

- webapp
   - common (provided)
   - error (provided)
   - secure
      - admin (provided)
      - audit (provided)
      - ftt (provided)
   - WEB-INF (to ignore)

I want to ignore everything under webapp except all files under /webapp/secure/ftt and its subdirectories.

I tried

/webapp
!/webapp/secure/ftt

But Git still ignores ftt.

I expect those directories to contain only .jsp and .js files. But I can't know what happens in the future (e.g. gif, pdf, etc)

How can I tell Git to whitelist files under /webapp/secure/ftt and ignore everything else under /webapp?

From my research I found it may be impossible without listing each specific subdirectory and file pattern.

[Add] after @DevDonkey comment I tried to empty my entire gitignore file and leave what he posted

/webapp/*
!/webapp/secure/ftt

Along with plenties of useless files (e.g. .class files) that are now candidate for indexing, because as I said I emptied the gitignore, I find sample.jsp still ignored

Body:
how about

/webapp/*
!/webapp/secure/ftt

works for me locally. Note the addition of the slash and wildcard, so git keeps the root folder, but then processes the rest.


问:
Dynamically use different class depending on current namespace
I would like my class to inherit methods off of its parent, I've done this by extending the class. But i would also like to instantiate a class using the basename(without namespace) and have the correct class be instantiate, chosen based on the current namespace and then fall back to a 'common' class if it doesn't exist.

example

```<code><?php

namespace common\models {

    class Account extends Model{}
    class Orders extends Model{}

    class Customer extends Model{

        use common\models\Account;

        public static function getAccountClass(){
            echo get_class(new Account());
        }
        public static function getOrdersClass(){
            echo get_class(new Order());
        }
    }
}

namespace frontend\models {

    class Account extends common\models\Account {}

    class Customer extends common\models\customer {

    }
}
</code>```

I would like the common\models\Customer::getAccountClass() to output common\models\Account

and

frontend\models\Customer::getAccountClass() to output frontend\models\Account

but as frontend\models\Orders doesn't exist frontend\models\Customer::getOrdersClass() will still output common\models\Orders

答:
Did you try to use full namespace like this : </p>

```<code>use common\models\Account as A2;
public static function getAccountClass(){
     echo get_class(new A2());
}
</code>```

<p>or </p>

```<code>public static function getAccountClass(){
    echo get_class(new common\models\Account());
}
</code>```

Body:
I would like my class to inherit methods off of its parent, I've done this by extending the class. But i would also like to instantiate a class using the basename(without namespace) and have the correct class be instantiate, chosen based on the current namespace and then fall back to a 'common' class if it doesn't exist.

example

<?php

namespace common\models {

    class Account extends Model{}
    class Orders extends Model{}

    class Customer extends Model{

        use common\models\Account;

        public static function getAccountClass(){
            echo get_class(new Account());
        }
        public static function getOrdersClass(){
            echo get_class(new Order());
        }
    }
}

namespace frontend\models {

    class Account extends common\models\Account {}

    class Customer extends common\models\customer {

    }
}

I would like the common\models\Customer::getAccountClass() to output common\models\Account

and

frontend\models\Customer::getAccountClass() to output frontend\models\Account

but as frontend\models\Orders doesn't exist frontend\models\Customer::getOrdersClass() will still output common\models\Orders

Body:
Did you try to use full namespace like this :

use common\models\Account as A2;
public static function getAccountClass(){
     echo get_class(new A2());
}

or

public static function getAccountClass(){
    echo get_class(new common\models\Account());
}


问:
What's the preferred way to implement a hook or callback in Python?
I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is created and given the opportunity to modify the instance before it is used.

The way I've implemented it is to declare a module-level factory function that does the instantiation:

```<code># in mymodule.py
def factory(cls, *args, **kwargs):
    return cls(*args, **kwargs)
</code>```

Then when I need an instance of a class in mymodule, I do factory(cls, arg1, arg2) rather than cls(arg1, arg2).

To extend it, a programmer would write in another module a function like this:

```<code>def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance
</code>```

Installation of the above callback looks like this:

```<code>myFactory.chain, mymodule.factory = mymodule.factory, myFactory
</code>```

This seems straightforward enough to me, but I was wondering if you, as a Python programmer, would expect a function to register a callback rather than doing it with an assignment, or if there were other methods you would expect. Does my solution seem workable, idiomatic, and clear to you?

I am looking to keep it as simple as possible; I don't think most applications will actually need to chain more than one user callback, for example (though unlimited chaining comes "for free" with the above pattern). I doubt they will need to remove callbacks or specify priorities or order.  Modules like python-callbacks or PyDispatcher seem to me like overkill, especially the latter, but if there are compelling benefits to a programmer working with my module, I'm open to them.

答:
I might use a decorator so that the user could just write.

```<code>@new_factory
def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance
</code>```

Then in your module,

```<code>import sys

def new_factory(f):
    mod = sys.modules[__name__]
    f.chain = mod.factory
    mod.factory = f
    return f
</code>```

Body:
I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is created and given the opportunity to modify the instance before it is used.

The way I've implemented it is to declare a module-level factory function that does the instantiation:

# in mymodule.py
def factory(cls, *args, **kwargs):
    return cls(*args, **kwargs)

Then when I need an instance of a class in mymodule, I do factory(cls, arg1, arg2) rather than cls(arg1, arg2).

To extend it, a programmer would write in another module a function like this:

def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance

Installation of the above callback looks like this:

myFactory.chain, mymodule.factory = mymodule.factory, myFactory

This seems straightforward enough to me, but I was wondering if you, as a Python programmer, would expect a function to register a callback rather than doing it with an assignment, or if there were other methods you would expect. Does my solution seem workable, idiomatic, and clear to you?

I am looking to keep it as simple as possible; I don't think most applications will actually need to chain more than one user callback, for example (though unlimited chaining comes "for free" with the above pattern). I doubt they will need to remove callbacks or specify priorities or order.  Modules like python-callbacks or PyDispatcher seem to me like overkill, especially the latter, but if there are compelling benefits to a programmer working with my module, I'm open to them.

Body:
I might use a decorator so that the user could just write.

@new_factory
def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance

Then in your module,

import sys

def new_factory(f):
    mod = sys.modules[__name__]
    f.chain = mod.factory
    mod.factory = f
    return f


问:
Connect to MySQL via hibernate
My db:

```<code>CREATE TABLE `ggloor`.`teams` (
  `idteam` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`idteam`));
</code>```

Settings in applicatin.yml

```<code>hibernate:
    cache:
        queries: false
        use_second_level_cache: true
        use_query_cache: false
        region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: 1111

environments:
    development:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?useSSL=false
    test:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?autoreconnect=true;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?autoreconnect=true;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
</code>```

Created domain

```<code>package testgrails12

class Teams {
    Integer idteam
    String name
    static constraints = {
    }
}
</code>```

Controller

```<code>package testgrails12

class Teams {
    Integer idteam
    String name
    static constraints = {
    }
    static mapping = {
        id column: 'idteam', sqlType: 'INT(11)', insertable: false, updateable: false
    }
}
</code>```

I get an error at the execution stage

Error 500: Internal Server Error URI /bdconnect/index Class
  com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException Message null
  Caused by Unknown column 'teams0_.id' in 'field list'

I tried to create hibernate.cfg.xml, Teams.hbm.xml in the conf folder, this did not work.

How to set everything up correctly? Work stopped =(

Error after add mapping

2017-03-29 19:30:34.954 ERROR --- [ost-startStop-1]
  o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat
  context. Exception:
  org.springframework.beans.factory.BeanCreationException. Message:
  Error creating bean with name 'grailsCacheFilter': Cannot create inner
  bean '(inner bean)#4bafa64a' of type
  [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter]
  while setting bean property 'filter'; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name '(inner bean)#4bafa64a': Unsatisfied
  dependency expressed through method 'setUrlMappingsHandlerMapping'
  parameter 0; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied
  dependency expressed through method 'setWebRequestInterceptors'
  parameter 0; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'openSessionInViewInterceptor': Cannot resolve
  reference to bean 'hibernateDatastore' while setting bean property
  'hibernateDatastore'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'hibernateDatastore': Bean instantiation via
  constructor failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor
  threw exception; nested exception is org.hibernate.MappingException:
  Repeated column in mapping for entity: testgrails12.Teams column:
  idteam (should be mapped with insert="false" update="false")
  2017-03-29 19:30:35.003 ERROR --- [           main]
  o.s.boot.SpringApplication               : Application startup failed

答:
The easiest solution is to remove Integer idteam from your entity and let GORM create the DB schema for you.

If you use some legacy database you can align your entity mapping using the static mapping = {} closure as given here, your id field probably will look like that:

```<code>static mapping = {
    ....
    id column: 'idteam', sqlType: 'INT(11)', insertable: false, updateable: false
    ....
}
</code>```

Note: you do not need to define it as a field in your entity. Just use it in mapping.

Title: Connect to MySQL via hibernate

Body:
My db:

CREATE TABLE `ggloor`.`teams` (
  `idteam` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`idteam`));

Settings in applicatin.yml

hibernate:
    cache:
        queries: false
        use_second_level_cache: true
        use_query_cache: false
        region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: 1111

environments:
    development:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?useSSL=false
    test:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?autoreconnect=true;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: create-drop
            url: jdbc:mysql://localhost:3306/ggloor?autoreconnect=true;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

Created domain

package testgrails12

class Teams {
    Integer idteam
    String name
    static constraints = {
    }
}

Controller

package testgrails12

class Teams {
    Integer idteam
    String name
    static constraints = {
    }
    static mapping = {
        id column: 'idteam', sqlType: 'INT(11)', insertable: false, updateable: false
    }
}

I get an error at the execution stage

Error 500: Internal Server Error URI /bdconnect/index Class
  com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException Message null
  Caused by Unknown column 'teams0_.id' in 'field list'

I tried to create hibernate.cfg.xml, Teams.hbm.xml in the conf folder, this did not work.

How to set everything up correctly? Work stopped =(

Error after add mapping

2017-03-29 19:30:34.954 ERROR --- [ost-startStop-1]
  o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat
  context. Exception:
  org.springframework.beans.factory.BeanCreationException. Message:
  Error creating bean with name 'grailsCacheFilter': Cannot create inner
  bean '(inner bean)#4bafa64a' of type
  [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter]
  while setting bean property 'filter'; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name '(inner bean)#4bafa64a': Unsatisfied
  dependency expressed through method 'setUrlMappingsHandlerMapping'
  parameter 0; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied
  dependency expressed through method 'setWebRequestInterceptors'
  parameter 0; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'openSessionInViewInterceptor': Cannot resolve
  reference to bean 'hibernateDatastore' while setting bean property
  'hibernateDatastore'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'hibernateDatastore': Bean instantiation via
  constructor failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor
  threw exception; nested exception is org.hibernate.MappingException:
  Repeated column in mapping for entity: testgrails12.Teams column:
  idteam (should be mapped with insert="false" update="false")
  2017-03-29 19:30:35.003 ERROR --- [           main]
  o.s.boot.SpringApplication               : Application startup failed

Body:
The easiest solution is to remove Integer idteam from your entity and let GORM create the DB schema for you.

If you use some legacy database you can align your entity mapping using the static mapping = {} closure as given here, your id field probably will look like that:

static mapping = {
    ....
    id column: 'idteam', sqlType: 'INT(11)', insertable: false, updateable: false
    ....
}

Note: you do not need to define it as a field in your entity. Just use it in mapping.